added some temporal archives for checking new web pages
authorOscar J. Rodriguez B <josuer08@gmail.com>
Fri, 20 Sep 2019 23:23:16 +0000 (19:23 -0400)
committerOscar J. Rodriguez B <josuer08@gmail.com>
Fri, 20 Sep 2019 23:23:16 +0000 (19:23 -0400)
17 files changed:
js/chromefix.js [new file with mode: 0644]
js/flow-stats.js [new file with mode: 0644]
js/joint.all.js [new file with mode: 0644]
js/joint.all.min.js [new file with mode: 0644]
js/joint.js [new file with mode: 0644]
js/joint.layout.DirectedGraph.js [new file with mode: 0644]
js/joint.shapes.erd.js [new file with mode: 0644]
js/jquery.min.js [new file with mode: 0644]
js/loadbalancer.js [new file with mode: 0644]
js/port-stats.js [new file with mode: 0644]
js/tap.js [new file with mode: 0644]
js/topology.js [new file with mode: 0644]
js/utils.js [new file with mode: 0644]
styles/font-awesome.min.css [new file with mode: 0644]
styles/joint.all.min.css [new file with mode: 0644]
styles/pure-custom.css [new file with mode: 0644]
styles/pure-min-0.5.0.css [new file with mode: 0644]

diff --git a/js/chromefix.js b/js/chromefix.js
new file mode 100644 (file)
index 0000000..6d270be
--- /dev/null
@@ -0,0 +1,3 @@
+SVGElement.prototype.getTransformToElement = SVGElement.prototype.getTransformToElement || function(toElement) {
+    return toElement.getScreenCTM().inverse().multiply(this.getScreenCTM());
+};
diff --git a/js/flow-stats.js b/js/flow-stats.js
new file mode 100644 (file)
index 0000000..eaeed13
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2014 SDN Hub
+ *
+ * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.
+ * You may not use this file except in compliance with this License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.gnu.org/licenses/gpl-3.0.txt
+ *
+ * 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.
+ */
+
+var url = "http://" + location.hostname + ":8080";
+
+function updateFlowStats() {
+    var statsTableBody = document.getElementById('flow-stats-data');
+    while (statsTableBody.firstChild) {
+            statsTableBody.removeChild(statsTableBody.firstChild);
+    }
+
+    $.getJSON(url.concat("/stats/switches"), function(switches){
+        $.each(switches, function(index, dpid){
+            var hex_dpid = parseInt(dpid).toString(16);
+
+            $.getJSON(url.concat("/stats/flow/").concat(dpid), function(flows) {
+                var flowStats = flows[dpid];
+
+                var tr = document.createElement('TR');
+                var numFlows = 0;
+                var switchColTd = document.createElement('TD');
+                switchColTd.appendChild(document.createTextNode(hex_dpid));
+                tr.appendChild(switchColTd);
+
+                var td;
+
+                $.each(flowStats, function(index, obj) {
+                    var outPorts = [];
+                    if ("actions" in obj) {
+                        $.each(obj.actions, function(index, action) {
+                            var command = action.split(':')[0];
+                            var param = action.split(':')[1];
+
+                            if (command == "OUTPUT") {
+                                if (param < 65280) 
+                                    outPorts.push(param);
+                            }
+                        });
+                    }
+                    if (outPorts.length > 0) {
+                        numFlows += 1;
+                        var matchFields = new Array("in_port", "dl_src", "dl_dst", "dl_type",
+                            "nw_src", "nw_dst", "nw_proto", "tp_src", "tp_dst");
+
+                        if (!("match" in obj)) {
+                            obj.match = {};
+                        }
+
+                        $.each(matchFields, function(index, field) {
+                            td = document.createElement('TD');
+                            if (field in obj.match)  {
+                                value = obj.match[field];
+                                if (field == "dl_type")
+                                    value = ethertypeToString(obj.match[field]);
+                                else if (field == "nw_proto")
+                                    value = nwprotoToString(obj.match[field]);
+
+                                td.appendChild(document.createTextNode(value));
+                            }
+                            else
+                                td.appendChild(document.createTextNode("*"));
+                            tr.appendChild(td);
+                        });
+
+                        td = document.createElement('TD');
+                        td.appendChild(document.createTextNode(outPorts));
+                        tr.appendChild(td);
+
+                        td = document.createElement('TD');
+                        var duration = obj.duration_sec + obj.duration_nsec/1000000000;
+                        td.appendChild(document.createTextNode(duration));
+                        tr.appendChild(td);
+
+                        td = document.createElement('TD');
+                        td.appendChild(document.createTextNode(obj.packet_count));
+                        tr.appendChild(td);
+
+                        td = document.createElement('TD');
+                        td.appendChild(document.createTextNode(obj.byte_count));
+                        tr.appendChild(td);
+
+                        statsTableBody.appendChild(tr);
+                        tr = document.createElement('TR');
+                    }
+                });
+
+                switchColTd.rowSpan = numFlows;
+            });
+        });
+    });
+}
+
+updateFlowStats();
+
+var flowStatsIntervalID = setInterval(function(){updateFlowStats()}, 5000);
+
+function stopFlowStatsTableRefresh() {
+    clearInterval(flowStatsIntervalID);
+}
diff --git a/js/joint.all.js b/js/joint.all.js
new file mode 100644 (file)
index 0000000..e2f773e
--- /dev/null
@@ -0,0 +1,28706 @@
+/*! JointJS v0.9.0 - JavaScript diagramming library  2014-05-13 
+
+
+This Source Code Form is subject to the terms of the Mozilla Public
+License, v. 2.0. If a copy of the MPL was not distributed with this
+file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+/*!
+ * jQuery JavaScript Library v2.0.3
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2013-07-03T13:30Z
+ */
+(function( window, undefined ) {
+
+// Can't do this because several apps including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+// Support: Firefox 18+
+//"use strict";
+var
+       // A central reference to the root jQuery(document)
+       rootjQuery,
+
+       // The deferred used on DOM ready
+       readyList,
+
+       // Support: IE9
+       // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
+       core_strundefined = typeof undefined,
+
+       // Use the correct document accordingly with window argument (sandbox)
+       location = window.location,
+       document = window.document,
+       docElem = document.documentElement,
+
+       // Map over jQuery in case of overwrite
+       _jQuery = window.jQuery,
+
+       // Map over the $ in case of overwrite
+       _$ = window.$,
+
+       // [[Class]] -> type pairs
+       class2type = {},
+
+       // List of deleted data cache ids, so we can reuse them
+       core_deletedIds = [],
+
+       core_version = "2.0.3",
+
+       // Save a reference to some core methods
+       core_concat = core_deletedIds.concat,
+       core_push = core_deletedIds.push,
+       core_slice = core_deletedIds.slice,
+       core_indexOf = core_deletedIds.indexOf,
+       core_toString = class2type.toString,
+       core_hasOwn = class2type.hasOwnProperty,
+       core_trim = core_version.trim,
+
+       // Define a local copy of jQuery
+       jQuery = function( selector, context ) {
+               // The jQuery object is actually just the init constructor 'enhanced'
+               return new jQuery.fn.init( selector, context, rootjQuery );
+       },
+
+       // Used for matching numbers
+       core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
+
+       // Used for splitting on whitespace
+       core_rnotwhite = /\S+/g,
+
+       // 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-]*))$/,
+
+       // Match a standalone tag
+       rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
+
+       // 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();
+       },
+
+       // The ready event handler and self cleanup method
+       completed = function() {
+               document.removeEventListener( "DOMContentLoaded", completed, false );
+               window.removeEventListener( "load", completed, false );
+               jQuery.ready();
+       };
+
+jQuery.fn = jQuery.prototype = {
+       // The current version of jQuery being used
+       jquery: core_version,
+
+       constructor: jQuery,
+       init: function( selector, context, rootjQuery ) {
+               var match, elem;
+
+               // HANDLE: $(""), $(null), $(undefined), $(false)
+               if ( !selector ) {
+                       return this;
+               }
+
+               // 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
+                                       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 ) {
+                                               // 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 || rootjQuery ).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 rootjQuery.ready( selector );
+               }
+
+               if ( selector.selector !== undefined ) {
+                       this.selector = selector.selector;
+                       this.context = selector.context;
+               }
+
+               return jQuery.makeArray( selector, this );
+       },
+
+       // Start with an empty selector
+       selector: "",
+
+       // The default length of a jQuery object is 0
+       length: 0,
+
+       toArray: function() {
+               return core_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 a 'clean' array
+                       this.toArray() :
+
+                       // Return just the object
+                       ( num < 0 ? this[ this.length + num ] : this[ num ] );
+       },
+
+       // 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.
+       // (You can seed the arguments with an array of args, but this is
+       // only used internally.)
+       each: function( callback, args ) {
+               return jQuery.each( this, callback, args );
+       },
+
+       ready: function( fn ) {
+               // Add the callback
+               jQuery.ready.promise().done( fn );
+
+               return this;
+       },
+
+       slice: function() {
+               return this.pushStack( core_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] ] : [] );
+       },
+
+       map: function( callback ) {
+               return this.pushStack( jQuery.map(this, function( elem, i ) {
+                       return callback.call( elem, i, elem );
+               }));
+       },
+
+       end: function() {
+               return this.prevObject || this.constructor(null);
+       },
+
+       // For internal use only.
+       // Behaves like an Array's method, not like a jQuery method.
+       push: core_push,
+       sort: [].sort,
+       splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+       var options, name, src, copy, copyIsArray, clone,
+               target = arguments[0] || {},
+               i = 1,
+               length = arguments.length,
+               deep = false;
+
+       // Handle a deep copy situation
+       if ( typeof target === "boolean" ) {
+               deep = target;
+               target = arguments[1] || {};
+               // skip the boolean and the target
+               i = 2;
+       }
+
+       // 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 ( length === i ) {
+               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" + ( core_version + Math.random() ).replace( /\D/g, "" ),
+
+       noConflict: function( deep ) {
+               if ( window.$ === jQuery ) {
+                       window.$ = _$;
+               }
+
+               if ( deep && window.jQuery === jQuery ) {
+                       window.jQuery = _jQuery;
+               }
+
+               return jQuery;
+       },
+
+       // 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.trigger ) {
+                       jQuery( document ).trigger("ready").off("ready");
+               }
+       },
+
+       // 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,
+
+       isWindow: function( obj ) {
+               return obj != null && obj === obj.window;
+       },
+
+       isNumeric: function( obj ) {
+               return !isNaN( parseFloat(obj) ) && isFinite( obj );
+       },
+
+       type: function( obj ) {
+               if ( obj == null ) {
+                       return String( obj );
+               }
+               // Support: Safari <= 5.1 (functionish RegExp)
+               return typeof obj === "object" || typeof obj === "function" ?
+                       class2type[ core_toString.call(obj) ] || "object" :
+                       typeof obj;
+       },
+
+       isPlainObject: function( obj ) {
+               // Not plain objects:
+               // - Any object or value whose internal [[Class]] property is not "[object Object]"
+               // - DOM nodes
+               // - window
+               if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+                       return false;
+               }
+
+               // Support: Firefox <20
+               // The try/catch suppresses exceptions thrown when attempting to access
+               // the "constructor" property of certain host objects, ie. |window.location|
+               // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
+               try {
+                       if ( obj.constructor &&
+                                       !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
+                               return false;
+                       }
+               } catch ( e ) {
+                       return false;
+               }
+
+               // If the function hasn't returned already, we're confident that
+               // |obj| is a plain object, created by {} or constructed with new Object
+               return true;
+       },
+
+       isEmptyObject: function( obj ) {
+               var name;
+               for ( name in obj ) {
+                       return false;
+               }
+               return true;
+       },
+
+       error: function( msg ) {
+               throw new Error( msg );
+       },
+
+       // 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
+       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 = jQuery.buildFragment( [ data ], context, scripts );
+
+               if ( scripts ) {
+                       jQuery( scripts ).remove();
+               }
+
+               return jQuery.merge( [], parsed.childNodes );
+       },
+
+       parseJSON: JSON.parse,
+
+       // Cross-browser xml parsing
+       parseXML: function( data ) {
+               var xml, tmp;
+               if ( !data || typeof data !== "string" ) {
+                       return null;
+               }
+
+               // Support: IE9
+               try {
+                       tmp = new DOMParser();
+                       xml = tmp.parseFromString( data , "text/xml" );
+               } catch ( e ) {
+                       xml = undefined;
+               }
+
+               if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
+                       jQuery.error( "Invalid XML: " + data );
+               }
+               return xml;
+       },
+
+       noop: function() {},
+
+       // Evaluates a script in a global context
+       globalEval: function( code ) {
+               var script,
+                               indirect = eval;
+
+               code = jQuery.trim( code );
+
+               if ( code ) {
+                       // If the code includes a valid, prologue position
+                       // strict mode pragma, execute code by injecting a
+                       // script tag into the document.
+                       if ( code.indexOf("use strict") === 1 ) {
+                               script = document.createElement("script");
+                               script.text = code;
+                               document.head.appendChild( script ).parentNode.removeChild( script );
+                       } else {
+                       // Otherwise, avoid the DOM node creation, insertion
+                       // and removal by using an indirect global eval
+                               indirect( code );
+                       }
+               }
+       },
+
+       // 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();
+       },
+
+       // args is for internal usage only
+       each: function( obj, callback, args ) {
+               var value,
+                       i = 0,
+                       length = obj.length,
+                       isArray = isArraylike( obj );
+
+               if ( args ) {
+                       if ( isArray ) {
+                               for ( ; i < length; i++ ) {
+                                       value = callback.apply( obj[ i ], args );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       } else {
+                               for ( i in obj ) {
+                                       value = callback.apply( obj[ i ], args );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       }
+
+               // A special, fast, case for the most common use of each
+               } else {
+                       if ( isArray ) {
+                               for ( ; i < length; i++ ) {
+                                       value = callback.call( obj[ i ], i, obj[ i ] );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       } else {
+                               for ( i in obj ) {
+                                       value = callback.call( obj[ i ], i, obj[ i ] );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       }
+               }
+
+               return obj;
+       },
+
+       trim: function( text ) {
+               return text == null ? "" : core_trim.call( text );
+       },
+
+       // 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 {
+                               core_push.call( ret, arr );
+                       }
+               }
+
+               return ret;
+       },
+
+       inArray: function( elem, arr, i ) {
+               return arr == null ? -1 : core_indexOf.call( arr, elem, i );
+       },
+
+       merge: function( first, second ) {
+               var l = second.length,
+                       i = first.length,
+                       j = 0;
+
+               if ( typeof l === "number" ) {
+                       for ( ; j < l; j++ ) {
+                               first[ i++ ] = second[ j ];
+                       }
+               } else {
+                       while ( second[j] !== undefined ) {
+                               first[ i++ ] = second[ j++ ];
+                       }
+               }
+
+               first.length = i;
+
+               return first;
+       },
+
+       grep: function( elems, callback, inv ) {
+               var retVal,
+                       ret = [],
+                       i = 0,
+                       length = elems.length;
+               inv = !!inv;
+
+               // Go through the array, only saving the items
+               // that pass the validator function
+               for ( ; i < length; i++ ) {
+                       retVal = !!callback( elems[ i ], i );
+                       if ( inv !== retVal ) {
+                               ret.push( elems[ i ] );
+                       }
+               }
+
+               return ret;
+       },
+
+       // arg is for internal usage only
+       map: function( elems, callback, arg ) {
+               var value,
+                       i = 0,
+                       length = elems.length,
+                       isArray = isArraylike( elems ),
+                       ret = [];
+
+               // Go through the array, translating each of the items to their
+               if ( isArray ) {
+                       for ( ; i < length; i++ ) {
+                               value = callback( elems[ i ], i, arg );
+
+                               if ( value != null ) {
+                                       ret[ ret.length ] = value;
+                               }
+                       }
+
+               // Go through every key on the object,
+               } else {
+                       for ( i in elems ) {
+                               value = callback( elems[ i ], i, arg );
+
+                               if ( value != null ) {
+                                       ret[ ret.length ] = value;
+                               }
+                       }
+               }
+
+               // Flatten any nested arrays
+               return core_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 tmp, args, proxy;
+
+               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 = core_slice.call( arguments, 2 );
+               proxy = function() {
+                       return fn.apply( context || this, args.concat( core_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;
+       },
+
+       // Multifunctional method to get and set values of a collection
+       // The value/s can optionally be executed if it's a function
+       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 ) {
+                               jQuery.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;
+       },
+
+       now: Date.now,
+
+       // A method for quickly swapping in/out CSS properties to get correct calculations.
+       // Note: this method belongs to the css module but it's needed here for the support module.
+       // If support gets modularized, this method should be moved back to the css module.
+       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;
+       }
+});
+
+jQuery.ready.promise = function( obj ) {
+       if ( !readyList ) {
+
+               readyList = jQuery.Deferred();
+
+               // Catch cases where $(document).ready() is called after the browser event has already occurred.
+               // we once tried to use readyState "interactive" here, but it caused issues like the one
+               // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
+               if ( document.readyState === "complete" ) {
+                       // Handle it asynchronously to allow scripts the opportunity to delay ready
+                       setTimeout( jQuery.ready );
+
+               } else {
+
+                       // Use the handy event callback
+                       document.addEventListener( "DOMContentLoaded", completed, false );
+
+                       // A fallback to window.onload, that will always work
+                       window.addEventListener( "load", completed, false );
+               }
+       }
+       return readyList.promise( obj );
+};
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
+       class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+function isArraylike( obj ) {
+       var length = obj.length,
+               type = jQuery.type( obj );
+
+       if ( jQuery.isWindow( obj ) ) {
+               return false;
+       }
+
+       if ( obj.nodeType === 1 && length ) {
+               return true;
+       }
+
+       return type === "array" || type !== "function" &&
+               ( length === 0 ||
+               typeof length === "number" && length > 0 && ( length - 1 ) in obj );
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+/*!
+ * Sizzle CSS Selector Engine v1.9.4-pre
+ * http://sizzlejs.com/
+ *
+ * Copyright 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2013-06-03
+ */
+(function( window, undefined ) {
+
+var i,
+       support,
+       cachedruns,
+       Expr,
+       getText,
+       isXML,
+       compile,
+       outermostContext,
+       sortInput,
+
+       // Local document vars
+       setDocument,
+       document,
+       docElem,
+       documentIsHTML,
+       rbuggyQSA,
+       rbuggyMatches,
+       matches,
+       contains,
+
+       // Instance-specific data
+       expando = "sizzle" + -(new Date()),
+       preferredDoc = window.document,
+       dirruns = 0,
+       done = 0,
+       classCache = createCache(),
+       tokenCache = createCache(),
+       compilerCache = createCache(),
+       hasDuplicate = false,
+       sortOrder = function( a, b ) {
+               if ( a === b ) {
+                       hasDuplicate = true;
+                       return 0;
+               }
+               return 0;
+       },
+
+       // General-purpose constants
+       strundefined = typeof undefined,
+       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 if we can't use a native one
+       indexOf = arr.indexOf || function( elem ) {
+               var i = 0,
+                       len = this.length;
+               for ( ; i < len; i++ ) {
+                       if ( this[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
+
+       // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
+       whitespace = "[\\x20\\t\\r\\n\\f]",
+       // http://www.w3.org/TR/css3-syntax/#characters
+       characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
+
+       // Loosely modeled on CSS identifier characters
+       // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
+       // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
+       identifier = characterEncoding.replace( "w", "w#" ),
+
+       // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
+       attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
+               "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
+
+       // Prefer arguments quoted,
+       //   then not containing pseudos/brackets,
+       //   then attribute selectors/non-parenthetical expressions,
+       //   then anything else
+       // These preferences are here to reduce the number of selectors
+       //   needing tokenize in the PSEUDO preFilter
+       pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
+
+       // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
+       rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
+
+       rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
+       rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
+
+       rsibling = new RegExp( whitespace + "*[+~]" ),
+       rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
+
+       rpseudo = new RegExp( pseudos ),
+       ridentifier = new RegExp( "^" + identifier + "$" ),
+
+       matchExpr = {
+               "ID": new RegExp( "^#(" + characterEncoding + ")" ),
+               "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
+               "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
+               "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" )
+       },
+
+       rnative = /^[^{]+\{\s*\[native \w/,
+
+       // Easily-parseable/retrievable ID or TAG or CLASS selectors
+       rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
+
+       rinputs = /^(?:input|select|textarea|button)$/i,
+       rheader = /^h\d$/i,
+
+       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
+               // Workaround erroneous numeric interpretation of +"0x"
+               return high !== high || escapedWhitespace ?
+                       escaped :
+                       // BMP codepoint
+                       high < 0 ?
+                               String.fromCharCode( high + 0x10000 ) :
+                               // Supplemental Plane codepoint (surrogate pair)
+                               String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
+       };
+
+// 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 match, elem, m, nodeType,
+               // QSA vars
+               i, groups, old, nid, newContext, newSelector;
+
+       if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
+               setDocument( context );
+       }
+
+       context = context || document;
+       results = results || [];
+
+       if ( !selector || typeof selector !== "string" ) {
+               return results;
+       }
+
+       if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
+               return [];
+       }
+
+       if ( documentIsHTML && !seed ) {
+
+               // Shortcuts
+               if ( (match = rquickExpr.exec( selector )) ) {
+                       // Speed-up: Sizzle("#ID")
+                       if ( (m = match[1]) ) {
+                               if ( nodeType === 9 ) {
+                                       elem = context.getElementById( m );
+                                       // 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, Opera, and Webkit return items
+                                               // by name instead of ID
+                                               if ( elem.id === m ) {
+                                                       results.push( elem );
+                                                       return results;
+                                               }
+                                       } else {
+                                               return results;
+                                       }
+                               } else {
+                                       // Context is not a document
+                                       if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
+                                               contains( context, elem ) && elem.id === m ) {
+                                               results.push( elem );
+                                               return results;
+                                       }
+                               }
+
+                       // Speed-up: Sizzle("TAG")
+                       } else if ( match[2] ) {
+                               push.apply( results, context.getElementsByTagName( selector ) );
+                               return results;
+
+                       // Speed-up: Sizzle(".CLASS")
+                       } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
+                               push.apply( results, context.getElementsByClassName( m ) );
+                               return results;
+                       }
+               }
+
+               // QSA path
+               if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
+                       nid = old = expando;
+                       newContext = context;
+                       newSelector = nodeType === 9 && selector;
+
+                       // qSA works strangely on Element-rooted queries
+                       // We can work around this by specifying an extra ID on the root
+                       // and working up from there (Thanks to Andrew Dupont for the technique)
+                       // IE 8 doesn't work on object elements
+                       if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+                               groups = tokenize( selector );
+
+                               if ( (old = context.getAttribute("id")) ) {
+                                       nid = old.replace( rescape, "\\$&" );
+                               } else {
+                                       context.setAttribute( "id", nid );
+                               }
+                               nid = "[id='" + nid + "'] ";
+
+                               i = groups.length;
+                               while ( i-- ) {
+                                       groups[i] = nid + toSelector( groups[i] );
+                               }
+                               newContext = rsibling.test( selector ) && context.parentNode || context;
+                               newSelector = groups.join(",");
+                       }
+
+                       if ( newSelector ) {
+                               try {
+                                       push.apply( results,
+                                               newContext.querySelectorAll( newSelector )
+                                       );
+                                       return results;
+                               } catch(qsaError) {
+                               } finally {
+                                       if ( !old ) {
+                                               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 = attrs.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]);
+                               }
+                       }
+               });
+       });
+}
+
+/**
+ * Detect xml
+ * @param {Element|Object} elem An element or a document
+ */
+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;
+};
+
+// Expose support vars for convenience
+support = Sizzle.support = {};
+
+/**
+ * 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 doc = node ? node.ownerDocument || node : preferredDoc,
+               parent = doc.defaultView;
+
+       // If no document and documentElement is available, return
+       if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
+               return document;
+       }
+
+       // Set our document
+       document = doc;
+       docElem = doc.documentElement;
+
+       // Support tests
+       documentIsHTML = !isXML( doc );
+
+       // Support: IE>8
+       // If iframe document is assigned to "document" variable and if iframe has been reloaded,
+       // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
+       // IE6-8 do not support the defaultView property so parent will be undefined
+       if ( parent && parent.attachEvent && parent !== parent.top ) {
+               parent.attachEvent( "onbeforeunload", function() {
+                       setDocument();
+               });
+       }
+
+       /* 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( doc.createComment("") );
+               return !div.getElementsByTagName("*").length;
+       });
+
+       // Check if getElementsByClassName can be trusted
+       support.getElementsByClassName = assert(function( div ) {
+               div.innerHTML = "<div class='a'></div><div class='a i'></div>";
+
+               // Support: Safari<4
+               // Catch class over-caching
+               div.firstChild.className = "i";
+               // Support: Opera<10
+               // Catch gEBCN failure to find non-leading classes
+               return div.getElementsByClassName("i").length === 2;
+       });
+
+       // 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 !doc.getElementsByName || !doc.getElementsByName( expando ).length;
+       });
+
+       // ID find and filter
+       if ( support.getById ) {
+               Expr.find["ID"] = function( id, context ) {
+                       if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
+                               var m = context.getElementById( id );
+                               // Check parentNode to catch when Blackberry 4.6 returns
+                               // nodes that are no longer in the document #6963
+                               return m && m.parentNode ? [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 !== strundefined && elem.getAttributeNode("id");
+                               return node && node.value === attrId;
+                       };
+               };
+       }
+
+       // Tag
+       Expr.find["TAG"] = support.getElementsByTagName ?
+               function( tag, context ) {
+                       if ( typeof context.getElementsByTagName !== strundefined ) {
+                               return context.getElementsByTagName( tag );
+                       }
+               } :
+               function( tag, context ) {
+                       var elem,
+                               tmp = [],
+                               i = 0,
+                               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 !== strundefined && 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( doc.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
+                       div.innerHTML = "<select><option selected=''></option></select>";
+
+                       // Support: IE8
+                       // Boolean attributes and "value" are not treated correctly
+                       if ( !div.querySelectorAll("[selected]").length ) {
+                               rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
+                       }
+
+                       // 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");
+                       }
+               });
+
+               assert(function( div ) {
+
+                       // Support: Opera 10-12/IE8
+                       // ^= $= *= and empty values
+                       // Should not select anything
+                       // Support: Windows 8 Native Apps
+                       // The type attribute is restricted during .innerHTML assignment
+                       var input = doc.createElement("input");
+                       input.setAttribute( "type", "hidden" );
+                       div.appendChild( input ).setAttribute( "t", "" );
+
+                       if ( div.querySelectorAll("[t^='']").length ) {
+                               rbuggyQSA.push( "[*^$]=" + 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.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
+       ---------------------------------------------------------------------- */
+
+       // Element contains another
+       // Purposefully does not implement inclusive descendent
+       // As in, an element does not contain itself
+       contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
+               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 = docElem.compareDocumentPosition ?
+       function( a, b ) {
+
+               // Flag for duplicate removal
+               if ( a === b ) {
+                       hasDuplicate = true;
+                       return 0;
+               }
+
+               var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
+
+               if ( compare ) {
+                       // Disconnected nodes
+                       if ( compare & 1 ||
+                               (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
+
+                               // Choose the first element that is related to our preferred document
+                               if ( a === doc || contains(preferredDoc, a) ) {
+                                       return -1;
+                               }
+                               if ( b === doc || contains(preferredDoc, b) ) {
+                                       return 1;
+                               }
+
+                               // Maintain original order
+                               return sortInput ?
+                                       ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
+                                       0;
+                       }
+
+                       return compare & 4 ? -1 : 1;
+               }
+
+               // Not directly comparable, sort on existence of method
+               return a.compareDocumentPosition ? -1 : 1;
+       } :
+       function( a, b ) {
+               var cur,
+                       i = 0,
+                       aup = a.parentNode,
+                       bup = b.parentNode,
+                       ap = [ a ],
+                       bp = [ b ];
+
+               // Exit early if the nodes are identical
+               if ( a === b ) {
+                       hasDuplicate = true;
+                       return 0;
+
+               // Parentless nodes are either documents or disconnected
+               } else if ( !aup || !bup ) {
+                       return a === doc ? -1 :
+                               b === doc ? 1 :
+                               aup ? -1 :
+                               bup ? 1 :
+                               sortInput ?
+                               ( indexOf.call( sortInput, a ) - indexOf.call( 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 doc;
+};
+
+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 &&
+               ( !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 ?
+               support.attributes || !documentIsHTML ?
+                       elem.getAttribute( name ) :
+                       (val = elem.getAttributeNode(name)) && val.specified ?
+                               val.value :
+                               null :
+               val;
+};
+
+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 );
+               }
+       }
+
+       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
+               for ( ; (node = elem[i]); 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 (see #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[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[5] && match[2];
+
+                       if ( matchExpr["CHILD"].test( match[0] ) ) {
+                               return null;
+                       }
+
+                       // Accept quoted arguments as-is
+                       if ( match[3] && match[4] !== undefined ) {
+                               match[2] = match[4];
+
+                       // 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 !== strundefined && 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 + " " ).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, outerCache, node, diff, nodeIndex, start,
+                                               dir = simple !== forward ? "nextSibling" : "previousSibling",
+                                               parent = elem.parentNode,
+                                               name = ofType && elem.nodeName.toLowerCase(),
+                                               useCache = !xml && !ofType;
+
+                                       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
+                                                       outerCache = parent[ expando ] || (parent[ expando ] = {});
+                                                       cache = outerCache[ type ] || [];
+                                                       nodeIndex = cache[0] === dirruns && cache[1];
+                                                       diff = cache[0] === dirruns && 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 ) {
+                                                                       outerCache[ type ] = [ dirruns, nodeIndex, diff ];
+                                                                       break;
+                                                               }
+                                                       }
+
+                                               // Use previously-cached element index if available
+                                               } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
+                                                       diff = cache[1];
+
+                                               // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
+                                               } else {
+                                                       // 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 ) {
+                                                                               (node[ expando ] || (node[ expando ] = {}))[ 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.call( 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 );
+                                       return !results.pop();
+                               };
+               }),
+
+               "has": markFunction(function( selector ) {
+                       return function( elem ) {
+                               return Sizzle( selector, elem ).length > 0;
+                       };
+               }),
+
+               "contains": markFunction(function( text ) {
+                       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 only affected by element nodes and content nodes(including text(3), cdata(4)),
+                       //   not comment, processing instructions, or others
+                       // Thanks to Diego Perini for the nodeName shortcut
+                       //   Greater than "@" means alpha characters (specifically not starting with "#" or "?")
+                       for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+                               if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
+                                       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;
+                       // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
+                       // use getAttribute instead to test this case
+                       return elem.nodeName.toLowerCase() === "input" &&
+                               elem.type === "text" &&
+                               ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
+               },
+
+               // 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();
+
+function tokenize( 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 data, cache, outerCache,
+                               dirkey = dirruns + " " + doneName;
+
+                       // We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
+                                               if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
+                                                       if ( (data = cache[1]) === true || data === cachedruns ) {
+                                                               return data === true;
+                                                       }
+                                               } else {
+                                                       cache = outerCache[ dir ] = [ dirkey ];
+                                                       cache[1] = matcher( elem, context, xml ) || cachedruns;
+                                                       if ( cache[1] === true ) {
+                                                               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 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.call( 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.call( checkContext, elem ) > -1;
+               }, implicitRelative, true ),
+               matchers = [ function( elem, context, xml ) {
+                       return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
+                               (checkContext = context).nodeType ?
+                                       matchContext( elem, context, xml ) :
+                                       matchAnyContext( elem, context, xml ) );
+               } ];
+
+       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 ) {
+       // A counter to specify which element is currently being matched
+       var matcherCachedRuns = 0,
+               bySet = setMatchers.length > 0,
+               byElement = elementMatchers.length > 0,
+               superMatcher = function( seed, context, xml, results, expandContext ) {
+                       var elem, j, matcher,
+                               setMatched = [],
+                               matchedCount = 0,
+                               i = "0",
+                               unmatched = seed && [],
+                               outermost = expandContext != null,
+                               contextBackup = outermostContext,
+                               // We must always have either seed elements or context
+                               elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
+                               // Use integer dirruns iff this is the outermost matcher
+                               dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
+
+                       if ( outermost ) {
+                               outermostContext = context !== document && context;
+                               cachedruns = matcherCachedRuns;
+                       }
+
+                       // Add elements passing elementMatchers directly to results
+                       // Keep `i` a string if there are no elements so `matchedCount` will be "00" below
+                       for ( ; (elem = elems[i]) != null; i++ ) {
+                               if ( byElement && elem ) {
+                                       j = 0;
+                                       while ( (matcher = elementMatchers[j++]) ) {
+                                               if ( matcher( elem, context, xml ) ) {
+                                                       results.push( elem );
+                                                       break;
+                                               }
+                                       }
+                                       if ( outermost ) {
+                                               dirruns = dirrunsUnique;
+                                               cachedruns = ++matcherCachedRuns;
+                                       }
+                               }
+
+                               // 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 );
+                                       }
+                               }
+                       }
+
+                       // Apply set filters to unmatched elements
+                       matchedCount += i;
+                       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, group /* 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 ( !group ) {
+                       group = tokenize( selector );
+               }
+               i = group.length;
+               while ( i-- ) {
+                       cached = matcherFromTokens( group[i] );
+                       if ( cached[ expando ] ) {
+                               setMatchers.push( cached );
+                       } else {
+                               elementMatchers.push( cached );
+                       }
+               }
+
+               // Cache the compiled function
+               cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
+       }
+       return cached;
+};
+
+function multipleContexts( selector, contexts, results ) {
+       var i = 0,
+               len = contexts.length;
+       for ( ; i < len; i++ ) {
+               Sizzle( selector, contexts[i], results );
+       }
+       return results;
+}
+
+function select( selector, context, results, seed ) {
+       var i, tokens, token, type, find,
+               match = tokenize( selector );
+
+       if ( !seed ) {
+               // Try to minimize operations if there is only one group
+               if ( match.length === 1 ) {
+
+                       // Take a shortcut and set the context if the root 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;
+                               }
+                               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 ) && 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
+       // Provide `match` to avoid retokenization if we modified the selector above
+       compile( selector, match )(
+               seed,
+               context,
+               !documentIsHTML,
+               results,
+               rsibling.test( selector )
+       );
+       return results;
+}
+
+// One-time assignments
+
+// Sort stability
+support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
+
+// Support: Chrome<14
+// 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 (val = elem.getAttributeNode( name )) && val.specified ?
+                               val.value :
+                               elem[ name ] === true ? name.toLowerCase() : null;
+               }
+       });
+}
+
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.pseudos;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+})( window );
+// String to Object options format cache
+var optionsCache = {};
+
+// Convert String-formatted options into Object-formatted ones and store in cache
+function createOptions( options ) {
+       var object = optionsCache[ options ] = {};
+       jQuery.each( options.match( core_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" ?
+               ( optionsCache[ options ] || createOptions( options ) ) :
+               jQuery.extend( {}, options );
+
+       var // Last fire value (for non-forgettable lists)
+               memory,
+               // Flag to know if list was already fired
+               fired,
+               // Flag to know if list is currently firing
+               firing,
+               // First callback to fire (used internally by add and fireWith)
+               firingStart,
+               // End of the loop when firing
+               firingLength,
+               // Index of currently firing callback (modified by remove if needed)
+               firingIndex,
+               // Actual callback list
+               list = [],
+               // Stack of fire calls for repeatable lists
+               stack = !options.once && [],
+               // Fire callbacks
+               fire = function( data ) {
+                       memory = options.memory && data;
+                       fired = true;
+                       firingIndex = firingStart || 0;
+                       firingStart = 0;
+                       firingLength = list.length;
+                       firing = true;
+                       for ( ; list && firingIndex < firingLength; firingIndex++ ) {
+                               if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
+                                       memory = false; // To prevent further calls using add
+                                       break;
+                               }
+                       }
+                       firing = false;
+                       if ( list ) {
+                               if ( stack ) {
+                                       if ( stack.length ) {
+                                               fire( stack.shift() );
+                                       }
+                               } else if ( memory ) {
+                                       list = [];
+                               } else {
+                                       self.disable();
+                               }
+                       }
+               },
+               // Actual Callbacks object
+               self = {
+                       // Add a callback or a collection of callbacks to the list
+                       add: function() {
+                               if ( list ) {
+                                       // First, we save the current length
+                                       var start = list.length;
+                                       (function add( args ) {
+                                               jQuery.each( args, function( _, arg ) {
+                                                       var type = jQuery.type( arg );
+                                                       if ( type === "function" ) {
+                                                               if ( !options.unique || !self.has( arg ) ) {
+                                                                       list.push( arg );
+                                                               }
+                                                       } else if ( arg && arg.length && type !== "string" ) {
+                                                               // Inspect recursively
+                                                               add( arg );
+                                                       }
+                                               });
+                                       })( arguments );
+                                       // Do we need to add the callbacks to the
+                                       // current firing batch?
+                                       if ( firing ) {
+                                               firingLength = list.length;
+                                       // With memory, if we're not firing then
+                                       // we should call right away
+                                       } else if ( memory ) {
+                                               firingStart = start;
+                                               fire( memory );
+                                       }
+                               }
+                               return this;
+                       },
+                       // Remove a callback from the list
+                       remove: function() {
+                               if ( list ) {
+                                       jQuery.each( arguments, function( _, arg ) {
+                                               var index;
+                                               while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
+                                                       list.splice( index, 1 );
+                                                       // Handle firing indexes
+                                                       if ( firing ) {
+                                                               if ( index <= firingLength ) {
+                                                                       firingLength--;
+                                                               }
+                                                               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 && list.length );
+                       },
+                       // Remove all callbacks from the list
+                       empty: function() {
+                               list = [];
+                               firingLength = 0;
+                               return this;
+                       },
+                       // Have the list do nothing anymore
+                       disable: function() {
+                               list = stack = memory = undefined;
+                               return this;
+                       },
+                       // Is it disabled?
+                       disabled: function() {
+                               return !list;
+                       },
+                       // Lock the list in its current state
+                       lock: function() {
+                               stack = undefined;
+                               if ( !memory ) {
+                                       self.disable();
+                               }
+                               return this;
+                       },
+                       // Is it locked?
+                       locked: function() {
+                               return !stack;
+                       },
+                       // Call all callbacks with the given context and arguments
+                       fireWith: function( context, args ) {
+                               if ( list && ( !fired || stack ) ) {
+                                       args = args || [];
+                                       args = [ context, args.slice ? args.slice() : args ];
+                                       if ( firing ) {
+                                               stack.push( args );
+                                       } else {
+                                               fire( args );
+                                       }
+                               }
+                               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 action = tuple[ 0 ],
+                                                               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()
+                                                                               .done( newDefer.resolve )
+                                                                               .fail( newDefer.reject )
+                                                                               .progress( newDefer.notify );
+                                                               } else {
+                                                                       newDefer[ action + "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 = core_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 ? core_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()
+                                               .done( updateFunc( i, resolveContexts, resolveValues ) )
+                                               .fail( deferred.reject )
+                                               .progress( updateFunc( i, progressContexts, progressValues ) );
+                               } else {
+                                       --remaining;
+                               }
+                       }
+               }
+
+               // if we're not waiting on anything, resolve the master
+               if ( !remaining ) {
+                       deferred.resolveWith( resolveContexts, resolveValues );
+               }
+
+               return deferred.promise();
+       }
+});
+jQuery.support = (function( support ) {
+       var input = document.createElement("input"),
+               fragment = document.createDocumentFragment(),
+               div = document.createElement("div"),
+               select = document.createElement("select"),
+               opt = select.appendChild( document.createElement("option") );
+
+       // Finish early in limited environments
+       if ( !input.type ) {
+               return support;
+       }
+
+       input.type = "checkbox";
+
+       // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
+       // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
+       support.checkOn = input.value !== "";
+
+       // Must access the parent to make an option select properly
+       // Support: IE9, IE10
+       support.optSelected = opt.selected;
+
+       // Will be defined later
+       support.reliableMarginRight = true;
+       support.boxSizingReliable = true;
+       support.pixelPosition = false;
+
+       // Make sure checked status is properly cloned
+       // Support: IE9, IE10
+       input.checked = true;
+       support.noCloneChecked = input.cloneNode( true ).checked;
+
+       // 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;
+
+       // Check if an input maintains its value after becoming a radio
+       // Support: IE9, IE10
+       input = document.createElement("input");
+       input.value = "t";
+       input.type = "radio";
+       support.radioValue = input.value === "t";
+
+       // #11217 - WebKit loses check when the name is after the checked attribute
+       input.setAttribute( "checked", "t" );
+       input.setAttribute( "name", "t" );
+
+       fragment.appendChild( input );
+
+       // Support: Safari 5.1, Android 4.x, Android 2.3
+       // old WebKit doesn't clone checked state correctly in fragments
+       support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+       // Support: Firefox, Chrome, Safari
+       // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
+       support.focusinBubbles = "onfocusin" in window;
+
+       div.style.backgroundClip = "content-box";
+       div.cloneNode( true ).style.backgroundClip = "";
+       support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+       // Run tests that need a body at doc ready
+       jQuery(function() {
+               var container, marginDiv,
+                       // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
+                       divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",
+                       body = document.getElementsByTagName("body")[ 0 ];
+
+               if ( !body ) {
+                       // Return for frameset docs that don't have a body
+                       return;
+               }
+
+               container = document.createElement("div");
+               container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
+
+               // Check box-sizing and margin behavior.
+               body.appendChild( container ).appendChild( div );
+               div.innerHTML = "";
+               // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
+               div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%";
+
+               // Workaround failing boxSizing test due to offsetWidth returning wrong value
+               // with some non-1 values of body zoom, ticket #13543
+               jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
+                       support.boxSizing = div.offsetWidth === 4;
+               });
+
+               // Use window.getComputedStyle because jsdom on node.js will break without it.
+               if ( window.getComputedStyle ) {
+                       support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
+                       support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
+
+                       // Support: Android 2.3
+                       // Check if 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
+                       marginDiv = div.appendChild( document.createElement("div") );
+                       marginDiv.style.cssText = div.style.cssText = divReset;
+                       marginDiv.style.marginRight = marginDiv.style.width = "0";
+                       div.style.width = "1px";
+
+                       support.reliableMarginRight =
+                               !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
+               }
+
+               body.removeChild( container );
+       });
+
+       return support;
+})( {} );
+
+/*
+       Implementation Summary
+
+       1. Enforce API surface and semantic compatibility with 1.9.x branch
+       2. Improve the module's maintainability by reducing the storage
+               paths to a single mechanism.
+       3. Use the same single mechanism to support "private" and "user" data.
+       4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
+       5. Avoid exposing implementation details on user objects (eg. expando properties)
+       6. Provide a clear path for implementation upgrade to WeakMap in 2014
+*/
+var data_user, data_priv,
+       rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
+       rmultiDash = /([A-Z])/g;
+
+function Data() {
+       // Support: Android < 4,
+       // Old WebKit does not have Object.preventExtensions/freeze method,
+       // return new empty object instead with no [[set]] accessor
+       Object.defineProperty( this.cache = {}, 0, {
+               get: function() {
+                       return {};
+               }
+       });
+
+       this.expando = jQuery.expando + Math.random();
+}
+
+Data.uid = 1;
+
+Data.accepts = function( owner ) {
+       // Accepts only:
+       //  - Node
+       //    - Node.ELEMENT_NODE
+       //    - Node.DOCUMENT_NODE
+       //  - Object
+       //    - Any
+       return owner.nodeType ?
+               owner.nodeType === 1 || owner.nodeType === 9 : true;
+};
+
+Data.prototype = {
+       key: function( owner ) {
+               // We can accept data for non-element nodes in modern browsers,
+               // but we should not, see #8335.
+               // Always return the key for a frozen object.
+               if ( !Data.accepts( owner ) ) {
+                       return 0;
+               }
+
+               var descriptor = {},
+                       // Check if the owner object already has a cache key
+                       unlock = owner[ this.expando ];
+
+               // If not, create one
+               if ( !unlock ) {
+                       unlock = Data.uid++;
+
+                       // Secure it in a non-enumerable, non-writable property
+                       try {
+                               descriptor[ this.expando ] = { value: unlock };
+                               Object.defineProperties( owner, descriptor );
+
+                       // Support: Android < 4
+                       // Fallback to a less secure definition
+                       } catch ( e ) {
+                               descriptor[ this.expando ] = unlock;
+                               jQuery.extend( owner, descriptor );
+                       }
+               }
+
+               // Ensure the cache object
+               if ( !this.cache[ unlock ] ) {
+                       this.cache[ unlock ] = {};
+               }
+
+               return unlock;
+       },
+       set: function( owner, data, value ) {
+               var prop,
+                       // There may be an unlock assigned to this node,
+                       // if there is no entry for this "owner", create one inline
+                       // and set the unlock as though an owner entry had always existed
+                       unlock = this.key( owner ),
+                       cache = this.cache[ unlock ];
+
+               // Handle: [ owner, key, value ] args
+               if ( typeof data === "string" ) {
+                       cache[ data ] = value;
+
+               // Handle: [ owner, { properties } ] args
+               } else {
+                       // Fresh assignments by object are shallow copied
+                       if ( jQuery.isEmptyObject( cache ) ) {
+                               jQuery.extend( this.cache[ unlock ], data );
+                       // Otherwise, copy the properties one-by-one to the cache object
+                       } else {
+                               for ( prop in data ) {
+                                       cache[ prop ] = data[ prop ];
+                               }
+                       }
+               }
+               return cache;
+       },
+       get: function( owner, key ) {
+               // Either a valid cache is found, or will be created.
+               // New caches will be created and the unlock returned,
+               // allowing direct access to the newly created
+               // empty data object. A valid owner object must be provided.
+               var cache = this.cache[ this.key( owner ) ];
+
+               return key === undefined ?
+                       cache : cache[ key ];
+       },
+       access: function( owner, key, value ) {
+               var stored;
+               // In cases where either:
+               //
+               //   1. No key was specified
+               //   2. A string key was specified, but no value provided
+               //
+               // Take the "read" path and allow the get method to determine
+               // which value to return, respectively either:
+               //
+               //   1. The entire cache object
+               //   2. The data stored at the key
+               //
+               if ( key === undefined ||
+                               ((key && typeof key === "string") && value === undefined) ) {
+
+                       stored = this.get( owner, key );
+
+                       return stored !== undefined ?
+                               stored : this.get( owner, jQuery.camelCase(key) );
+               }
+
+               // [*]When the key is not a string, or both a key and value
+               // are specified, set or extend (existing objects) with either:
+               //
+               //   1. An object of properties
+               //   2. A key and value
+               //
+               this.set( owner, key, value );
+
+               // Since the "set" path can have two possible entry points
+               // return the expected data based on which path was taken[*]
+               return value !== undefined ? value : key;
+       },
+       remove: function( owner, key ) {
+               var i, name, camel,
+                       unlock = this.key( owner ),
+                       cache = this.cache[ unlock ];
+
+               if ( key === undefined ) {
+                       this.cache[ unlock ] = {};
+
+               } else {
+                       // Support array or space separated string of keys
+                       if ( jQuery.isArray( key ) ) {
+                               // 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 = key.concat( key.map( jQuery.camelCase ) );
+                       } else {
+                               camel = jQuery.camelCase( key );
+                               // Try the string as a key before any manipulation
+                               if ( key in cache ) {
+                                       name = [ key, camel ];
+                               } else {
+                                       // If a key with the spaces exists, use it.
+                                       // Otherwise, create an array by matching non-whitespace
+                                       name = camel;
+                                       name = name in cache ?
+                                               [ name ] : ( name.match( core_rnotwhite ) || [] );
+                               }
+                       }
+
+                       i = name.length;
+                       while ( i-- ) {
+                               delete cache[ name[ i ] ];
+                       }
+               }
+       },
+       hasData: function( owner ) {
+               return !jQuery.isEmptyObject(
+                       this.cache[ owner[ this.expando ] ] || {}
+               );
+       },
+       discard: function( owner ) {
+               if ( owner[ this.expando ] ) {
+                       delete this.cache[ owner[ this.expando ] ];
+               }
+       }
+};
+
+// These may be used throughout the jQuery core codebase
+data_user = new Data();
+data_priv = new Data();
+
+
+jQuery.extend({
+       acceptData: Data.accepts,
+
+       hasData: function( elem ) {
+               return data_user.hasData( elem ) || data_priv.hasData( elem );
+       },
+
+       data: function( elem, name, data ) {
+               return data_user.access( elem, name, data );
+       },
+
+       removeData: function( elem, name ) {
+               data_user.remove( elem, name );
+       },
+
+       // TODO: Now that all calls to _data and _removeData have been replaced
+       // with direct calls to data_priv methods, these can be deprecated.
+       _data: function( elem, name, data ) {
+               return data_priv.access( elem, name, data );
+       },
+
+       _removeData: function( elem, name ) {
+               data_priv.remove( elem, name );
+       }
+});
+
+jQuery.fn.extend({
+       data: function( key, value ) {
+               var attrs, name,
+                       elem = this[ 0 ],
+                       i = 0,
+                       data = null;
+
+               // Gets all values
+               if ( key === undefined ) {
+                       if ( this.length ) {
+                               data = data_user.get( elem );
+
+                               if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
+                                       attrs = elem.attributes;
+                                       for ( ; i < attrs.length; i++ ) {
+                                               name = attrs[ i ].name;
+
+                                               if ( name.indexOf( "data-" ) === 0 ) {
+                                                       name = jQuery.camelCase( name.slice(5) );
+                                                       dataAttr( elem, name, data[ name ] );
+                                               }
+                                       }
+                                       data_priv.set( elem, "hasDataAttrs", true );
+                               }
+                       }
+
+                       return data;
+               }
+
+               // Sets multiple values
+               if ( typeof key === "object" ) {
+                       return this.each(function() {
+                               data_user.set( this, key );
+                       });
+               }
+
+               return jQuery.access( this, function( value ) {
+                       var data,
+                               camelKey = jQuery.camelCase( key );
+
+                       // The calling jQuery object (element matches) is not empty
+                       // (and therefore has an element appears at this[ 0 ]) and the
+                       // `value` parameter was not undefined. An empty jQuery object
+                       // will result in `undefined` for elem = this[ 0 ] which will
+                       // throw an exception if an attempt to read a data cache is made.
+                       if ( elem && value === undefined ) {
+                               // Attempt to get data from the cache
+                               // with the key as-is
+                               data = data_user.get( elem, key );
+                               if ( data !== undefined ) {
+                                       return data;
+                               }
+
+                               // Attempt to get data from the cache
+                               // with the key camelized
+                               data = data_user.get( elem, camelKey );
+                               if ( data !== undefined ) {
+                                       return data;
+                               }
+
+                               // Attempt to "discover" the data in
+                               // HTML5 custom data-* attrs
+                               data = dataAttr( elem, camelKey, undefined );
+                               if ( data !== undefined ) {
+                                       return data;
+                               }
+
+                               // We tried really hard, but the data doesn't exist.
+                               return;
+                       }
+
+                       // Set the data...
+                       this.each(function() {
+                               // First, attempt to store a copy or reference of any
+                               // data that might've been store with a camelCased key.
+                               var data = data_user.get( this, camelKey );
+
+                               // For HTML5 data-* attribute interop, we have to
+                               // store property names with dashes in a camelCase form.
+                               // This might not apply to all properties...*
+                               data_user.set( this, camelKey, value );
+
+                               // *... In the case of properties that might _actually_
+                               // have dashes, we need to also store a copy of that
+                               // unchanged property.
+                               if ( key.indexOf("-") !== -1 && data !== undefined ) {
+                                       data_user.set( this, key, value );
+                               }
+                       });
+               }, null, value, arguments.length > 1, null, true );
+       },
+
+       removeData: function( key ) {
+               return this.each(function() {
+                       data_user.remove( this, key );
+               });
+       }
+});
+
+function dataAttr( elem, key, data ) {
+       var name;
+
+       // If nothing was found internally, try to fetch any
+       // data from the HTML5 data-* attribute
+       if ( data === undefined && elem.nodeType === 1 ) {
+               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 ) ? JSON.parse( data ) :
+                                       data;
+                       } catch( e ) {}
+
+                       // Make sure we set the data so it isn't changed later
+                       data_user.set( elem, key, data );
+               } else {
+                       data = undefined;
+               }
+       }
+       return data;
+}
+jQuery.extend({
+       queue: function( elem, type, data ) {
+               var queue;
+
+               if ( elem ) {
+                       type = ( type || "fx" ) + "queue";
+                       queue = data_priv.get( elem, type );
+
+                       // Speed up dequeue by getting out quickly if this is just a lookup
+                       if ( data ) {
+                               if ( !queue || jQuery.isArray( data ) ) {
+                                       queue = data_priv.access( 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 data_priv.get( elem, key ) || data_priv.access( elem, key, {
+                       empty: jQuery.Callbacks("once memory").add(function() {
+                               data_priv.remove( elem, [ type + "queue", 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 );
+               });
+       },
+       // Based off of the plugin by Clint Helfers, with permission.
+       // http://blindsignals.com/index.php/2009/07/jquery-delay/
+       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 = setTimeout( next, time );
+                       hooks.stop = function() {
+                               clearTimeout( timeout );
+                       };
+               });
+       },
+       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 = data_priv.get( elements[ i ], type + "queueHooks" );
+                       if ( tmp && tmp.empty ) {
+                               count++;
+                               tmp.empty.add( resolve );
+                       }
+               }
+               resolve();
+               return defer.promise( obj );
+       }
+});
+var nodeHook, boolHook,
+       rclass = /[\t\r\n\f]/g,
+       rreturn = /\r/g,
+       rfocusable = /^(?:input|select|textarea|button)$/i;
+
+jQuery.fn.extend({
+       attr: function( name, value ) {
+               return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
+       },
+
+       removeAttr: function( name ) {
+               return this.each(function() {
+                       jQuery.removeAttr( this, name );
+               });
+       },
+
+       prop: function( name, value ) {
+               return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
+       },
+
+       removeProp: function( name ) {
+               return this.each(function() {
+                       delete this[ jQuery.propFix[ name ] || name ];
+               });
+       },
+
+       addClass: function( value ) {
+               var classes, elem, cur, clazz, j,
+                       i = 0,
+                       len = this.length,
+                       proceed = typeof value === "string" && value;
+
+               if ( jQuery.isFunction( value ) ) {
+                       return this.each(function( j ) {
+                               jQuery( this ).addClass( value.call( this, j, this.className ) );
+                       });
+               }
+
+               if ( proceed ) {
+                       // The disjunction here is for better compressibility (see removeClass)
+                       classes = ( value || "" ).match( core_rnotwhite ) || [];
+
+                       for ( ; i < len; i++ ) {
+                               elem = this[ i ];
+                               cur = elem.nodeType === 1 && ( elem.className ?
+                                       ( " " + elem.className + " " ).replace( rclass, " " ) :
+                                       " "
+                               );
+
+                               if ( cur ) {
+                                       j = 0;
+                                       while ( (clazz = classes[j++]) ) {
+                                               if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
+                                                       cur += clazz + " ";
+                                               }
+                                       }
+                                       elem.className = jQuery.trim( cur );
+
+                               }
+                       }
+               }
+
+               return this;
+       },
+
+       removeClass: function( value ) {
+               var classes, elem, cur, clazz, j,
+                       i = 0,
+                       len = this.length,
+                       proceed = arguments.length === 0 || typeof value === "string" && value;
+
+               if ( jQuery.isFunction( value ) ) {
+                       return this.each(function( j ) {
+                               jQuery( this ).removeClass( value.call( this, j, this.className ) );
+                       });
+               }
+               if ( proceed ) {
+                       classes = ( value || "" ).match( core_rnotwhite ) || [];
+
+                       for ( ; i < len; i++ ) {
+                               elem = this[ i ];
+                               // This expression is here for better compressibility (see addClass)
+                               cur = elem.nodeType === 1 && ( elem.className ?
+                                       ( " " + elem.className + " " ).replace( rclass, " " ) :
+                                       ""
+                               );
+
+                               if ( cur ) {
+                                       j = 0;
+                                       while ( (clazz = classes[j++]) ) {
+                                               // Remove *all* instances
+                                               while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
+                                                       cur = cur.replace( " " + clazz + " ", " " );
+                                               }
+                                       }
+                                       elem.className = value ? jQuery.trim( cur ) : "";
+                               }
+                       }
+               }
+
+               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, this.className, stateVal), stateVal );
+                       });
+               }
+
+               return this.each(function() {
+                       if ( type === "string" ) {
+                               // toggle individual class names
+                               var className,
+                                       i = 0,
+                                       self = jQuery( this ),
+                                       classNames = value.match( core_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 ( type === core_strundefined || type === "boolean" ) {
+                               if ( this.className ) {
+                                       // store className if set
+                                       data_priv.set( this, "__className__", this.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.
+                               this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
+                       }
+               });
+       },
+
+       hasClass: function( selector ) {
+               var className = " " + selector + " ",
+                       i = 0,
+                       l = this.length;
+               for ( ; i < l; i++ ) {
+                       if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
+                               return true;
+                       }
+               }
+
+               return false;
+       },
+
+       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 ) {
+                               // attributes.value is undefined in Blackberry 4.7 but
+                               // uses .value. See #6932
+                               var val = elem.attributes.value;
+                               return !val || val.specified ? elem.value : elem.text;
+                       }
+               },
+               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 ];
+
+                                       // IE6-9 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
+                                                       ( jQuery.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 ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
+                                               optionSet = true;
+                                       }
+                               }
+
+                               // force browsers to behave consistently when non-matching value is set
+                               if ( !optionSet ) {
+                                       elem.selectedIndex = -1;
+                               }
+                               return values;
+                       }
+               }
+       },
+
+       attr: function( elem, name, value ) {
+               var hooks, ret,
+                       nType = elem.nodeType;
+
+               // don't get/set attributes on text, comment and attribute nodes
+               if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+                       return;
+               }
+
+               // Fallback to prop when attributes are not supported
+               if ( typeof elem.getAttribute === core_strundefined ) {
+                       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 );
+
+                       } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+                               return ret;
+
+                       } else {
+                               elem.setAttribute( name, value + "" );
+                               return value;
+                       }
+
+               } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+                       return ret;
+
+               } else {
+                       ret = jQuery.find.attr( elem, name );
+
+                       // Non-existent attributes return null, we normalize to undefined
+                       return ret == null ?
+                               undefined :
+                               ret;
+               }
+       },
+
+       removeAttr: function( elem, value ) {
+               var name, propName,
+                       i = 0,
+                       attrNames = value && value.match( core_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
+                                       elem[ propName ] = false;
+                               }
+
+                               elem.removeAttribute( name );
+                       }
+               }
+       },
+
+       attrHooks: {
+               type: {
+                       set: function( elem, value ) {
+                               if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
+                                       // Setting the type on a radio button after the value resets the value in IE6-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;
+                               }
+                       }
+               }
+       },
+
+       propFix: {
+               "for": "htmlFor",
+               "class": "className"
+       },
+
+       prop: function( elem, name, value ) {
+               var ret, hooks, notxml,
+                       nType = elem.nodeType;
+
+               // don't get/set properties on text, comment and attribute nodes
+               if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+                       return;
+               }
+
+               notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+               if ( notxml ) {
+                       // Fix name and attach hooks
+                       name = jQuery.propFix[ name ] || name;
+                       hooks = jQuery.propHooks[ name ];
+               }
+
+               if ( value !== undefined ) {
+                       return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
+                               ret :
+                               ( elem[ name ] = value );
+
+               } else {
+                       return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
+                               ret :
+                               elem[ name ];
+               }
+       },
+
+       propHooks: {
+               tabIndex: {
+                       get: function( elem ) {
+                               return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
+                                       elem.tabIndex :
+                                       -1;
+                       }
+               }
+       }
+});
+
+// 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 {
+                       elem.setAttribute( name, name );
+               }
+               return name;
+       }
+};
+jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
+       var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
+
+       jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) {
+               var fn = jQuery.expr.attrHandle[ name ],
+                       ret = isXML ?
+                               undefined :
+                               /* jshint eqeqeq: false */
+                               // Temporarily disable this handler to check existence
+                               (jQuery.expr.attrHandle[ name ] = undefined) !=
+                                       getter( elem, name, isXML ) ?
+
+                                       name.toLowerCase() :
+                                       null;
+
+               // Restore handler
+               jQuery.expr.attrHandle[ name ] = fn;
+
+               return ret;
+       };
+});
+
+// Support: IE9+
+// Selectedness for an option in an optgroup can be inaccurate
+if ( !jQuery.support.optSelected ) {
+       jQuery.propHooks.selected = {
+               get: function( elem ) {
+                       var parent = elem.parentNode;
+                       if ( parent && parent.parentNode ) {
+                               parent.parentNode.selectedIndex;
+                       }
+                       return null;
+               }
+       };
+}
+
+jQuery.each([
+       "tabIndex",
+       "readOnly",
+       "maxLength",
+       "cellSpacing",
+       "cellPadding",
+       "rowSpan",
+       "colSpan",
+       "useMap",
+       "frameBorder",
+       "contentEditable"
+], function() {
+       jQuery.propFix[ this.toLowerCase() ] = this;
+});
+
+// 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 ) >= 0 );
+                       }
+               }
+       };
+       if ( !jQuery.support.checkOn ) {
+               jQuery.valHooks[ this ].get = function( elem ) {
+                       // Support: Webkit
+                       // "" is returned instead of "on" if a value isn't specified
+                       return elem.getAttribute("value") === null ? "on" : elem.value;
+               };
+       }
+});
+var rkeyEvent = /^key/,
+       rmouseEvent = /^(?:mouse|contextmenu)|click/,
+       rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+       rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
+
+function returnTrue() {
+       return true;
+}
+
+function returnFalse() {
+       return false;
+}
+
+function safeActiveElement() {
+       try {
+               return document.activeElement;
+       } catch ( err ) { }
+}
+
+/*
+ * 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 handleObjIn, eventHandle, tmp,
+                       events, t, handleObj,
+                       special, handlers, type, namespaces, origType,
+                       elemData = data_priv.get( 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 !== core_strundefined && (!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( core_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 if the special events handler returns false
+                               if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+                                       if ( elem.addEventListener ) {
+                                               elem.addEventListener( type, eventHandle, false );
+                                       }
+                               }
+                       }
+
+                       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, origCount, tmp,
+                       events, t, handleObj,
+                       special, handlers, type, namespaces, origType,
+                       elemData = data_priv.hasData( elem ) && data_priv.get( elem );
+
+               if ( !elemData || !(events = elemData.events) ) {
+                       return;
+               }
+
+               // Once for each type.namespace in types; type may be omitted
+               types = ( types || "" ).match( core_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;
+                       data_priv.remove( elem, "events" );
+               }
+       },
+
+       trigger: function( event, data, elem, onlyHandlers ) {
+
+               var i, cur, tmp, bubbleType, ontype, handle, special,
+                       eventPath = [ elem || document ],
+                       type = core_hasOwn.call( event, "type" ) ? event.type : event,
+                       namespaces = core_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(".") >= 0 ) {
+                       // 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.namespace_re = 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
+                       if ( handle ) {
+                               handle.apply( cur, data );
+                       }
+
+                       // Native handler
+                       handle = ontype && cur[ ontype ];
+                       if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === 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) &&
+                               jQuery.acceptData( elem ) ) {
+
+                               // Call a native DOM method on the target with the same name name as the event.
+                               // Don't do default actions on window, that's where global variables be (#6170)
+                               if ( ontype && jQuery.isFunction( 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;
+                                       elem[ type ]();
+                                       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 = core_slice.call( arguments ),
+                       handlers = ( data_priv.get( 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.namespace_re || event.namespace_re.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;
+
+               // Find delegate handlers
+               // Black-hole SVG <use> instance trees (#13180)
+               // Avoid non-left-click bubbling in Firefox (#3861)
+               if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
+
+                       for ( ; cur !== this; cur = cur.parentNode || this ) {
+
+                               // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
+                               if ( 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 ) >= 0 :
+                                                               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;
+       },
+
+       // Includes some event props shared by KeyEvent and MouseEvent
+       props: "altKey bubbles cancelable ctrlKey currentTarget 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
+               filter: function( event, original ) {
+                       var eventDoc, doc, body,
+                               button = original.button;
+
+                       // 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 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;
+               }
+       },
+
+       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: Cordova 2.5 (WebKit) (#13255)
+               // All events should have a target; Cordova deviceready doesn't
+               if ( !event.target ) {
+                       event.target = document;
+               }
+
+               // Support: Safari 6.0+, Chrome < 28
+               // Target should not be a text node (#504, #13143)
+               if ( event.target.nodeType === 3 ) {
+                       event.target = event.target.parentNode;
+               }
+
+               return fixHook.filter? fixHook.filter( event, originalEvent ) : 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 ) {
+                                       this.focus();
+                                       return false;
+                               }
+                       },
+                       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 ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
+                                       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.returnValue = event.result;
+                               }
+                       }
+               }
+       },
+
+       simulate: function( type, elem, event, bubble ) {
+               // Piggyback on a donor event to simulate a different one.
+               // Fake originalEvent to avoid donor's stopPropagation, but if the
+               // simulated event prevents default then we do the same on the donor.
+               var e = jQuery.extend(
+                       new jQuery.Event(),
+                       event,
+                       {
+                               type: type,
+                               isSimulated: true,
+                               originalEvent: {}
+                       }
+               );
+               if ( bubble ) {
+                       jQuery.event.trigger( e, null, elem );
+               } else {
+                       jQuery.event.dispatch.call( elem, e );
+               }
+               if ( e.isDefaultPrevented() ) {
+                       event.preventDefault();
+               }
+       }
+};
+
+jQuery.removeEvent = function( elem, type, handle ) {
+       if ( elem.removeEventListener ) {
+               elem.removeEventListener( type, handle, false );
+       }
+};
+
+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.getPreventDefault && src.getPreventDefault() ) ? 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 = {
+       isDefaultPrevented: returnFalse,
+       isPropagationStopped: returnFalse,
+       isImmediatePropagationStopped: returnFalse,
+
+       preventDefault: function() {
+               var e = this.originalEvent;
+
+               this.isDefaultPrevented = returnTrue;
+
+               if ( e && e.preventDefault ) {
+                       e.preventDefault();
+               }
+       },
+       stopPropagation: function() {
+               var e = this.originalEvent;
+
+               this.isPropagationStopped = returnTrue;
+
+               if ( e && e.stopPropagation ) {
+                       e.stopPropagation();
+               }
+       },
+       stopImmediatePropagation: function() {
+               this.isImmediatePropagationStopped = returnTrue;
+               this.stopPropagation();
+       }
+};
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+// Support: Chrome 15+
+jQuery.each({
+       mouseenter: "mouseover",
+       mouseleave: "mouseout"
+}, 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 mousenter/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;
+               }
+       };
+});
+
+// Create "bubbling" focus and blur events
+// Support: Firefox, Chrome, Safari
+if ( !jQuery.support.focusinBubbles ) {
+       jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+               // Attach a single capturing handler while someone wants focusin/focusout
+               var attaches = 0,
+                       handler = function( event ) {
+                               jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
+                       };
+
+               jQuery.event.special[ fix ] = {
+                       setup: function() {
+                               if ( attaches++ === 0 ) {
+                                       document.addEventListener( orig, handler, true );
+                               }
+                       },
+                       teardown: function() {
+                               if ( --attaches === 0 ) {
+                                       document.removeEventListener( orig, handler, true );
+                               }
+                       }
+               };
+       });
+}
+
+jQuery.fn.extend({
+
+       on: function( types, selector, data, fn, /*INTERNAL*/ 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 ) {
+                               this.on( type, selector, data, types[ type ], one );
+                       }
+                       return this;
+               }
+
+               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 this;
+               }
+
+               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 this.each( function() {
+                       jQuery.event.add( this, types, fn, data, selector );
+               });
+       },
+       one: function( types, selector, data, fn ) {
+               return this.on( 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 isSimple = /^.[^:#\[\.,]*$/,
+       rparentsprev = /^(?:parents|prev(?:Until|All))/,
+       rneedsContext = jQuery.expr.match.needsContext,
+       // 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({
+       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;
+       },
+
+       has: function( target ) {
+               var targets = jQuery( target, this ),
+                       l = targets.length;
+
+               return this.filter(function() {
+                       var i = 0;
+                       for ( ; i < l; i++ ) {
+                               if ( jQuery.contains( this, targets[i] ) ) {
+                                       return true;
+                               }
+                       }
+               });
+       },
+
+       not: function( selector ) {
+               return this.pushStack( winnow(this, selector || [], true) );
+       },
+
+       filter: function( selector ) {
+               return this.pushStack( winnow(this, selector || [], false) );
+       },
+
+       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;
+       },
+
+       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)) ) {
+
+                                       cur = matched.push( cur );
+                                       break;
+                               }
+                       }
+               }
+
+               return this.pushStack( matched.length > 1 ? jQuery.unique( 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 core_indexOf.call( jQuery( elem ), this[ 0 ] );
+               }
+
+               // Locate the position of the desired element
+               return core_indexOf.call( this,
+
+                       // If it receives a jQuery object, the first element is used
+                       elem.jquery ? elem[ 0 ] : elem
+               );
+       },
+
+       add: function( selector, context ) {
+               var set = typeof selector === "string" ?
+                               jQuery( selector, context ) :
+                               jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
+                       all = jQuery.merge( this.get(), set );
+
+               return this.pushStack( jQuery.unique(all) );
+       },
+
+       addBack: function( selector ) {
+               return this.add( selector == null ?
+                       this.prevObject : this.prevObject.filter(selector)
+               );
+       }
+});
+
+function sibling( cur, dir ) {
+       while ( (cur = cur[dir]) && 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 jQuery.dir( elem, "parentNode" );
+       },
+       parentsUntil: function( elem, i, until ) {
+               return jQuery.dir( elem, "parentNode", until );
+       },
+       next: function( elem ) {
+               return sibling( elem, "nextSibling" );
+       },
+       prev: function( elem ) {
+               return sibling( elem, "previousSibling" );
+       },
+       nextAll: function( elem ) {
+               return jQuery.dir( elem, "nextSibling" );
+       },
+       prevAll: function( elem ) {
+               return jQuery.dir( elem, "previousSibling" );
+       },
+       nextUntil: function( elem, i, until ) {
+               return jQuery.dir( elem, "nextSibling", until );
+       },
+       prevUntil: function( elem, i, until ) {
+               return jQuery.dir( elem, "previousSibling", until );
+       },
+       siblings: function( elem ) {
+               return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
+       },
+       children: function( elem ) {
+               return jQuery.sibling( elem.firstChild );
+       },
+       contents: function( elem ) {
+               return elem.contentDocument || jQuery.merge( [], elem.childNodes );
+       }
+}, function( name, fn ) {
+       jQuery.fn[ name ] = function( until, selector ) {
+               var matched = jQuery.map( this, fn, until );
+
+               if ( name.slice( -5 ) !== "Until" ) {
+                       selector = until;
+               }
+
+               if ( selector && typeof selector === "string" ) {
+                       matched = jQuery.filter( selector, matched );
+               }
+
+               if ( this.length > 1 ) {
+                       // Remove duplicates
+                       if ( !guaranteedUnique[ name ] ) {
+                               jQuery.unique( matched );
+                       }
+
+                       // Reverse order for parents* and prev-derivatives
+                       if ( rparentsprev.test( name ) ) {
+                               matched.reverse();
+                       }
+               }
+
+               return this.pushStack( matched );
+       };
+});
+
+jQuery.extend({
+       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;
+                       }));
+       },
+
+       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;
+       },
+
+       sibling: function( n, elem ) {
+               var matched = [];
+
+               for ( ; n; n = n.nextSibling ) {
+                       if ( n.nodeType === 1 && n !== elem ) {
+                               matched.push( n );
+                       }
+               }
+
+               return matched;
+       }
+});
+
+// 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 ( isSimple.test( qualifier ) ) {
+                       return jQuery.filter( qualifier, elements, not );
+               }
+
+               qualifier = jQuery.filter( qualifier, elements );
+       }
+
+       return jQuery.grep( elements, function( elem ) {
+               return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
+       });
+}
+var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
+       rtagName = /<([\w:]+)/,
+       rhtml = /<|&#?\w+;/,
+       rnoInnerhtml = /<(?:script|style|link)/i,
+       manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
+       // checked="checked" or checked
+       rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+       rscriptType = /^$|\/(?:java|ecma)script/i,
+       rscriptTypeMasked = /^true\/(.*)/,
+       rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
+
+       // We have to close these tags to support XHTML (#13200)
+       wrapMap = {
+
+               // Support: IE 9
+               option: [ 1, "<select multiple='multiple'>", "</select>" ],
+
+               thead: [ 1, "<table>", "</table>" ],
+               col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
+               tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+               td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+
+               _default: [ 0, "", "" ]
+       };
+
+// Support: IE 9
+wrapMap.optgroup = wrapMap.option;
+
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+jQuery.fn.extend({
+       text: function( value ) {
+               return jQuery.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 this.domManip( arguments, function( elem ) {
+                       if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+                               var target = manipulationTarget( this, elem );
+                               target.appendChild( elem );
+                       }
+               });
+       },
+
+       prepend: function() {
+               return this.domManip( 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 this.domManip( arguments, function( elem ) {
+                       if ( this.parentNode ) {
+                               this.parentNode.insertBefore( elem, this );
+                       }
+               });
+       },
+
+       after: function() {
+               return this.domManip( arguments, function( elem ) {
+                       if ( this.parentNode ) {
+                               this.parentNode.insertBefore( elem, this.nextSibling );
+                       }
+               });
+       },
+
+       // keepData is for internal use only--do not document
+       remove: function( selector, keepData ) {
+               var elem,
+                       elems = selector ? jQuery.filter( selector, this ) : this,
+                       i = 0;
+
+               for ( ; (elem = elems[i]) != null; i++ ) {
+                       if ( !keepData && elem.nodeType === 1 ) {
+                               jQuery.cleanData( getAll( elem ) );
+                       }
+
+                       if ( elem.parentNode ) {
+                               if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
+                                       setGlobalEval( getAll( elem, "script" ) );
+                               }
+                               elem.parentNode.removeChild( elem );
+                       }
+               }
+
+               return this;
+       },
+
+       empty: function() {
+               var elem,
+                       i = 0;
+
+               for ( ; (elem = this[i]) != null; i++ ) {
+                       if ( elem.nodeType === 1 ) {
+
+                               // Prevent memory leaks
+                               jQuery.cleanData( getAll( elem, false ) );
+
+                               // Remove any remaining nodes
+                               elem.textContent = "";
+                       }
+               }
+
+               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 jQuery.access( this, function( value ) {
+                       var elem = this[ 0 ] || {},
+                               i = 0,
+                               l = this.length;
+
+                       if ( value === undefined && elem.nodeType === 1 ) {
+                               return elem.innerHTML;
+                       }
+
+                       // See if we can take a shortcut and just use innerHTML
+                       if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
+                               !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
+
+                               value = value.replace( rxhtmlTag, "<$1></$2>" );
+
+                               try {
+                                       for ( ; i < l; i++ ) {
+                                               elem = this[ i ] || {};
+
+                                               // Remove element nodes and prevent memory leaks
+                                               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
+                       // Snapshot the DOM in case .domManip sweeps something relevant into its fragment
+                       args = jQuery.map( this, function( elem ) {
+                               return [ elem.nextSibling, elem.parentNode ];
+                       }),
+                       i = 0;
+
+               // Make the changes, replacing each context element with the new content
+               this.domManip( arguments, function( elem ) {
+                       var next = args[ i++ ],
+                               parent = args[ i++ ];
+
+                       if ( parent ) {
+                               // Don't use the snapshot next if it has moved (#13810)
+                               if ( next && next.parentNode !== parent ) {
+                                       next = this.nextSibling;
+                               }
+                               jQuery( this ).remove();
+                               parent.insertBefore( elem, next );
+                       }
+               // Allow new content to include elements from the context set
+               }, true );
+
+               // Force removal if there was no new content (e.g., from empty arguments)
+               return i ? this : this.remove();
+       },
+
+       detach: function( selector ) {
+               return this.remove( selector, true );
+       },
+
+       domManip: function( args, callback, allowIntersection ) {
+
+               // Flatten any nested arrays
+               args = core_concat.apply( [], args );
+
+               var fragment, first, scripts, hasScripts, node, doc,
+                       i = 0,
+                       l = this.length,
+                       set = this,
+                       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" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
+                       return this.each(function( index ) {
+                               var self = set.eq( index );
+                               if ( isFunction ) {
+                                       args[ 0 ] = value.call( this, index, self.html() );
+                               }
+                               self.domManip( args, callback, allowIntersection );
+                       });
+               }
+
+               if ( l ) {
+                       fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
+                       first = fragment.firstChild;
+
+                       if ( fragment.childNodes.length === 1 ) {
+                               fragment = first;
+                       }
+
+                       if ( first ) {
+                               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: QtWebKit
+                                                       // jQuery.merge because core_push.apply(_, arraylike) throws
+                                                       jQuery.merge( scripts, getAll( node, "script" ) );
+                                               }
+                                       }
+
+                                       callback.call( this[ 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 || "" ) &&
+                                                       !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
+
+                                                       if ( node.src ) {
+                                                               // Hope ajax is available...
+                                                               jQuery._evalUrl( node.src );
+                                                       } else {
+                                                               jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               return this;
+       }
+});
+
+jQuery.each({
+       appendTo: "append",
+       prependTo: "prepend",
+       insertBefore: "before",
+       insertAfter: "after",
+       replaceAll: "replaceWith"
+}, function( name, original ) {
+       jQuery.fn[ name ] = function( selector ) {
+               var elems,
+                       ret = [],
+                       insert = jQuery( selector ),
+                       last = insert.length - 1,
+                       i = 0;
+
+               for ( ; i <= last; i++ ) {
+                       elems = i === last ? this : this.clone( true );
+                       jQuery( insert[ i ] )[ original ]( elems );
+
+                       // Support: QtWebKit
+                       // .get() because core_push.apply(_, arraylike) throws
+                       core_push.apply( ret, elems.get() );
+               }
+
+               return this.pushStack( ret );
+       };
+});
+
+jQuery.extend({
+       clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+               var i, l, srcElements, destElements,
+                       clone = elem.cloneNode( true ),
+                       inPage = jQuery.contains( elem.ownerDocument, elem );
+
+               // Support: IE >= 9
+               // Fix Cloning issues
+               if ( !jQuery.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 );
+
+                       for ( i = 0, l = srcElements.length; i < l; i++ ) {
+                               fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) {
+                                       cloneCopyEvent( srcElements[ i ], destElements[ i ] );
+                               }
+                       } else {
+                               cloneCopyEvent( elem, clone );
+                       }
+               }
+
+               // Preserve script evaluation history
+               destElements = getAll( clone, "script" );
+               if ( destElements.length > 0 ) {
+                       setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
+               }
+
+               // Return the cloned set
+               return clone;
+       },
+
+       buildFragment: function( elems, context, scripts, selection ) {
+               var elem, tmp, tag, wrap, contains, j,
+                       i = 0,
+                       l = elems.length,
+                       fragment = context.createDocumentFragment(),
+                       nodes = [];
+
+               for ( ; i < l; i++ ) {
+                       elem = elems[ i ];
+
+                       if ( elem || elem === 0 ) {
+
+                               // Add nodes directly
+                               if ( jQuery.type( elem ) === "object" ) {
+                                       // Support: QtWebKit
+                                       // jQuery.merge because core_push.apply(_, arraylike) throws
+                                       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 || fragment.appendChild( context.createElement("div") );
+
+                                       // Deserialize a standard representation
+                                       tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase();
+                                       wrap = wrapMap[ tag ] || wrapMap._default;
+                                       tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
+
+                                       // Descend through wrappers to the right content
+                                       j = wrap[ 0 ];
+                                       while ( j-- ) {
+                                               tmp = tmp.lastChild;
+                                       }
+
+                                       // Support: QtWebKit
+                                       // jQuery.merge because core_push.apply(_, arraylike) throws
+                                       jQuery.merge( nodes, tmp.childNodes );
+
+                                       // Remember the top-level container
+                                       tmp = fragment.firstChild;
+
+                                       // Fixes #12346
+                                       // Support: Webkit, IE
+                                       tmp.textContent = "";
+                               }
+                       }
+               }
+
+               // Remove wrapper from fragment
+               fragment.textContent = "";
+
+               i = 0;
+               while ( (elem = nodes[ i++ ]) ) {
+
+                       // #4087 - If origin and destination elements are the same, and this is
+                       // that element, do not do anything
+                       if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
+                               continue;
+                       }
+
+                       contains = jQuery.contains( elem.ownerDocument, elem );
+
+                       // Append to fragment
+                       tmp = getAll( fragment.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 );
+                                       }
+                               }
+                       }
+               }
+
+               return fragment;
+       },
+
+       cleanData: function( elems ) {
+               var data, elem, events, type, key, j,
+                       special = jQuery.event.special,
+                       i = 0;
+
+               for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
+                       if ( Data.accepts( elem ) ) {
+                               key = elem[ data_priv.expando ];
+
+                               if ( key && (data = data_priv.cache[ key ]) ) {
+                                       events = Object.keys( data.events || {} );
+                                       if ( events.length ) {
+                                               for ( j = 0; (type = events[j]) !== undefined; j++ ) {
+                                                       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 );
+                                                       }
+                                               }
+                                       }
+                                       if ( data_priv.cache[ key ] ) {
+                                               // Discard any remaining `private` data
+                                               delete data_priv.cache[ key ];
+                                       }
+                               }
+                       }
+                       // Discard any remaining `user` data
+                       delete data_user.cache[ elem[ data_user.expando ] ];
+               }
+       },
+
+       _evalUrl: function( url ) {
+               return jQuery.ajax({
+                       url: url,
+                       type: "GET",
+                       dataType: "script",
+                       async: false,
+                       global: false,
+                       "throws": true
+               });
+       }
+});
+
+// Support: 1.x compatibility
+// Manipulating tables requires a tbody
+function manipulationTarget( elem, content ) {
+       return jQuery.nodeName( elem, "table" ) &&
+               jQuery.nodeName( content.nodeType === 1 ? 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 = (elem.getAttribute("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;
+}
+
+// Mark scripts as having already been evaluated
+function setGlobalEval( elems, refElements ) {
+       var l = elems.length,
+               i = 0;
+
+       for ( ; i < l; i++ ) {
+               data_priv.set(
+                       elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
+               );
+       }
+}
+
+function cloneCopyEvent( src, dest ) {
+       var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
+
+       if ( dest.nodeType !== 1 ) {
+               return;
+       }
+
+       // 1. Copy private data: events, handlers, etc.
+       if ( data_priv.hasData( src ) ) {
+               pdataOld = data_priv.access( src );
+               pdataCur = data_priv.set( dest, pdataOld );
+               events = pdataOld.events;
+
+               if ( events ) {
+                       delete pdataCur.handle;
+                       pdataCur.events = {};
+
+                       for ( type in events ) {
+                               for ( i = 0, l = events[ type ].length; i < l; i++ ) {
+                                       jQuery.event.add( dest, type, events[ type ][ i ] );
+                               }
+                       }
+               }
+       }
+
+       // 2. Copy user data
+       if ( data_user.hasData( src ) ) {
+               udataOld = data_user.access( src );
+               udataCur = jQuery.extend( {}, udataOld );
+
+               data_user.set( dest, udataCur );
+       }
+}
+
+
+function getAll( context, tag ) {
+       var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
+                       context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
+                       [];
+
+       return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
+               jQuery.merge( [ context ], ret ) :
+               ret;
+}
+
+// Support: IE >= 9
+function fixInput( src, dest ) {
+       var nodeName = dest.nodeName.toLowerCase();
+
+       // Fails to persist the checked state of a cloned checkbox or radio button.
+       if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
+               dest.checked = src.checked;
+
+       // Fails to return the selected option to the default selected state when cloning options
+       } else if ( nodeName === "input" || nodeName === "textarea" ) {
+               dest.defaultValue = src.defaultValue;
+       }
+}
+jQuery.fn.extend({
+       wrapAll: function( html ) {
+               var wrap;
+
+               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
+                       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.firstElementChild ) {
+                                       elem = elem.firstElementChild;
+                               }
+
+                               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();
+       }
+});
+var curCSS, iframe,
+       // 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]).+)/,
+       rmargin = /^margin/,
+       rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
+       rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
+       rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
+       elemdisplay = { BODY: "block" },
+
+       cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+       cssNormalTransform = {
+               letterSpacing: 0,
+               fontWeight: 400
+       },
+
+       cssExpand = [ "Top", "Right", "Bottom", "Left" ],
+       cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
+
+// return a css property mapped to a potentially vendor prefixed property
+function vendorPropName( style, name ) {
+
+       // shortcut for names that are not vendor prefixed
+       if ( name in style ) {
+               return name;
+       }
+
+       // check for vendor prefixed names
+       var capName = name.charAt(0).toUpperCase() + name.slice(1),
+               origName = name,
+               i = cssPrefixes.length;
+
+       while ( i-- ) {
+               name = cssPrefixes[ i ] + capName;
+               if ( name in style ) {
+                       return name;
+               }
+       }
+
+       return origName;
+}
+
+function isHidden( 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 );
+}
+
+// NOTE: we've included the "window" in window.getComputedStyle
+// because jsdom on node.js will break without it.
+function getStyles( elem ) {
+       return window.getComputedStyle( elem, null );
+}
+
+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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
+                       }
+               } else {
+
+                       if ( !values[ index ] ) {
+                               hidden = isHidden( elem );
+
+                               if ( display && display !== "none" || !hidden ) {
+                                       data_priv.set( 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;
+}
+
+jQuery.fn.extend({
+       css: function( name, value ) {
+               return jQuery.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();
+                       }
+               });
+       }
+});
+
+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: {
+               "columnCount": true,
+               "fillOpacity": 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": "cssFloat"
+       },
+
+       // 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( style, 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 relative number strings (+= or -=) to relative numbers. #7345
+                       if ( type === "string" && (ret = rrelNum.exec( value )) ) {
+                               value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
+                               // Fixes bug #9237
+                               type = "number";
+                       }
+
+                       // Make sure that NaN and null values aren't set. See: #7116
+                       if ( value == null || type === "number" && isNaN( value ) ) {
+                               return;
+                       }
+
+                       // If a number was passed in, add 'px' to the (except for certain CSS properties)
+                       if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+                               value += "px";
+                       }
+
+                       // Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
+                       // but it would mean to define eight (for every problematic property) identical functions
+                       if ( !jQuery.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 ) {
+                               style[ name ] = value;
+                       }
+
+               } 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 val, num, hooks,
+                       origName = jQuery.camelCase( name );
+
+               // Make sure that we're working with the right name
+               name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, 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 || jQuery.isNumeric( num ) ? num || 0 : val;
+               }
+               return val;
+       }
+});
+
+curCSS = function( elem, name, _computed ) {
+       var width, minWidth, maxWidth,
+               computed = _computed || getStyles( elem ),
+
+               // Support: IE9
+               // getPropertyValue is only needed for .css('filter') in IE9, see #12537
+               ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
+               style = elem.style;
+
+       if ( computed ) {
+
+               if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
+                       ret = jQuery.style( elem, name );
+               }
+
+               // Support: Safari 5.1
+               // A tribute to the "awesome hack by Dean Edwards"
+               // 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 ( 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;
+               }
+       }
+
+       return ret;
+};
+
+
+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 = jQuery.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 && ( jQuery.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";
+}
+
+// Try to determine the default display value of an element
+function css_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'/>")
+                               .css( "cssText", "display:block !important" )
+                       ).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;
+                       doc.write("<!doctype html><html><body>");
+                       doc.close();
+
+                       display = actualDisplay( nodeName, doc );
+                       iframe.detach();
+               }
+
+               // Store the correct default display
+               elemdisplay[ nodeName ] = display;
+       }
+
+       return display;
+}
+
+// Called ONLY from within css_defaultDisplay
+function actualDisplay( name, doc ) {
+       var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
+               display = jQuery.css( elem[0], "display" );
+       elem.remove();
+       return display;
+}
+
+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 elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
+                                       jQuery.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,
+                                       jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
+                                       styles
+                               ) : 0
+                       );
+               }
+       };
+});
+
+// These hooks cannot be added until DOM ready because the support test
+// for it is not run until after DOM ready
+jQuery(function() {
+       // Support: Android 2.3
+       if ( !jQuery.support.reliableMarginRight ) {
+               jQuery.cssHooks.marginRight = {
+                       get: function( elem, computed ) {
+                               if ( computed ) {
+                                       // Support: Android 2.3
+                                       // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+                                       // Work around by temporarily setting element display to inline-block
+                                       return jQuery.swap( elem, { "display": "inline-block" },
+                                               curCSS, [ elem, "marginRight" ] );
+                               }
+                       }
+               };
+       }
+
+       // 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
+       if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
+               jQuery.each( [ "top", "left" ], function( i, prop ) {
+                       jQuery.cssHooks[ prop ] = {
+                               get: 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;
+                                       }
+                               }
+                       };
+               });
+       }
+
+});
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+       jQuery.expr.filters.hidden = function( elem ) {
+               // Support: Opera <= 12.12
+               // Opera reports offsetWidths and offsetHeights less than zero on some elements
+               return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
+       };
+
+       jQuery.expr.filters.visible = function( elem ) {
+               return !jQuery.expr.filters.hidden( elem );
+       };
+}
+
+// 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;
+       }
+});
+var r20 = /%20/g,
+       rbracket = /\[\]$/,
+       rCRLF = /\r?\n/g,
+       rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+       rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+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 || !manipulation_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();
+       }
+});
+
+//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, "+" );
+};
+
+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" ? 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 );
+       }
+}
+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 );
+       },
+
+       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 );
+       }
+});
+var
+       // Document location
+       ajaxLocParts,
+       ajaxLocation,
+
+       ajax_nonce = jQuery.now(),
+
+       ajax_rquery = /\?/,
+       rhash = /#.*$/,
+       rts = /([?&])_=[^&]*/,
+       rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
+       // #7653, #8125, #8152: local protocol detection
+       rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
+       rnoContent = /^(?:GET|HEAD)$/,
+       rprotocol = /^\/\//,
+       rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
+
+       // Keep a copy of the old load method
+       _load = jQuery.fn.load,
+
+       /* 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("*");
+
+// #8138, IE may throw an exception when accessing
+// a field from window.location if document.domain has been set
+try {
+       ajaxLocation = location.href;
+} catch( e ) {
+       // Use the href attribute of an A element
+       // since IE will modify it given document.location
+       ajaxLocation = document.createElement( "a" );
+       ajaxLocation.href = "";
+       ajaxLocation = ajaxLocation.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( core_rnotwhite ) || [];
+
+               if ( jQuery.isFunction( func ) ) {
+                       // For each dataType in the dataTypeExpression
+                       while ( (dataType = dataTypes[i++]) ) {
+                               // Prepend if requested
+                               if ( dataType[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 key, deep,
+               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;
+}
+
+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 >= 0 ) {
+               selector = url.slice( off );
+               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
+                       type: type,
+                       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 );
+
+               }).complete( callback && function( jqXHR, status ) {
+                       self.each( callback, 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.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: /xml/,
+                       html: /html/,
+                       json: /json/
+               },
+
+               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 transport,
+                       // URL without anti-cache param
+                       cacheURL,
+                       // Response headers
+                       responseHeadersString,
+                       responseHeaders,
+                       // timeout handle
+                       timeoutTimer,
+                       // Cross-domain detection vars
+                       parts,
+                       // To know if global events are to be dispatched
+                       fireGlobals,
+                       // Loop variable
+                       i,
+                       // 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 (prefilters might expect it)
+               // 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( core_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
+               fireGlobals = 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 += ( ajax_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_=" + ajax_nonce++ ) :
+
+                                       // Otherwise add one to the end
+                                       cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_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 ] );
+                       }
+                       // Timeout
+                       if ( s.async && s.timeout > 0 ) {
+                               timeoutTimer = 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 ) {
+                               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;
+               }
+
+               return jQuery.ajax({
+                       url: url,
+                       type: method,
+                       dataType: type,
+                       data: data,
+                       success: callback
+               });
+       };
+});
+
+/* 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 ct, type, finalDataType, firstDataType,
+               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" ] ) {
+                                               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 };
+}
+// Install script dataType
+jQuery.ajaxSetup({
+       accepts: {
+               script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+       },
+       contents: {
+               script: /(?:java|ecma)script/
+       },
+       converters: {
+               "text script": function( text ) {
+                       jQuery.globalEval( text );
+                       return text;
+               }
+       }
+});
+
+// Handle cache's special case and crossDomain
+jQuery.ajaxPrefilter( "script", function( s ) {
+       if ( s.cache === undefined ) {
+               s.cache = false;
+       }
+       if ( s.crossDomain ) {
+               s.type = "GET";
+       }
+});
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function( s ) {
+       // This transport only deals with cross domain requests
+       if ( s.crossDomain ) {
+               var script, callback;
+               return {
+                       send: function( _, complete ) {
+                               script = jQuery("<script>").prop({
+                                       async: true,
+                                       charset: s.scriptCharset,
+                                       src: s.url
+                               }).on(
+                                       "load error",
+                                       callback = function( evt ) {
+                                               script.remove();
+                                               callback = null;
+                                               if ( evt ) {
+                                                       complete( evt.type === "error" ? 404 : 200, evt.type );
+                                               }
+                                       }
+                               );
+                               document.head.appendChild( script[ 0 ] );
+                       },
+                       abort: function() {
+                               if ( callback ) {
+                                       callback();
+                               }
+                       }
+               };
+       }
+});
+var oldCallbacks = [],
+       rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+       jsonp: "callback",
+       jsonpCallback: function() {
+               var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_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") && 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 += ( ajax_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() {
+                       // Restore preexisting value
+                       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";
+       }
+});
+jQuery.ajaxSettings.xhr = function() {
+       try {
+               return new XMLHttpRequest();
+       } catch( e ) {}
+};
+
+var xhrSupported = jQuery.ajaxSettings.xhr(),
+       xhrSuccessStatus = {
+               // file protocol always yields status code 0, assume 200
+               0: 200,
+               // Support: IE9
+               // #1450: sometimes IE returns 1223 when it should be 204
+               1223: 204
+       },
+       // Support: IE9
+       // We need to keep track of outbound xhr and abort them manually
+       // because IE is not smart enough to do it all by itself
+       xhrId = 0,
+       xhrCallbacks = {};
+
+if ( window.ActiveXObject ) {
+       jQuery( window ).on( "unload", function() {
+               for( var key in xhrCallbacks ) {
+                       xhrCallbacks[ key ]();
+               }
+               xhrCallbacks = undefined;
+       });
+}
+
+jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+jQuery.support.ajax = xhrSupported = !!xhrSupported;
+
+jQuery.ajaxTransport(function( options ) {
+       var callback;
+       // Cross domain only allowed if supported through XMLHttpRequest
+       if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) {
+               return {
+                       send: function( headers, complete ) {
+                               var i, id,
+                                       xhr = options.xhr();
+                               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 ) {
+                                       xhr.setRequestHeader( i, headers[ i ] );
+                               }
+                               // Callback
+                               callback = function( type ) {
+                                       return function() {
+                                               if ( callback ) {
+                                                       delete xhrCallbacks[ id ];
+                                                       callback = xhr.onload = xhr.onerror = null;
+                                                       if ( type === "abort" ) {
+                                                               xhr.abort();
+                                                       } else if ( type === "error" ) {
+                                                               complete(
+                                                                       // file protocol always yields status 0, assume 404
+                                                                       xhr.status || 404,
+                                                                       xhr.statusText
+                                                               );
+                                                       } else {
+                                                               complete(
+                                                                       xhrSuccessStatus[ xhr.status ] || xhr.status,
+                                                                       xhr.statusText,
+                                                                       // Support: IE9
+                                                                       // #11426: When requesting binary data, IE9 will throw an exception
+                                                                       // on any attempt to access responseText
+                                                                       typeof xhr.responseText === "string" ? {
+                                                                               text: xhr.responseText
+                                                                       } : undefined,
+                                                                       xhr.getAllResponseHeaders()
+                                                               );
+                                                       }
+                                               }
+                                       };
+                               };
+                               // Listen to events
+                               xhr.onload = callback();
+                               xhr.onerror = callback("error");
+                               // Create the abort callback
+                               callback = xhrCallbacks[( id = xhrId++ )] = callback("abort");
+                               // 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 );
+                       },
+                       abort: function() {
+                               if ( callback ) {
+                                       callback();
+                               }
+                       }
+               };
+       }
+});
+var fxNow, timerId,
+       rfxtypes = /^(?:toggle|show|hide)$/,
+       rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
+       rrun = /queueHooks$/,
+       animationPrefilters = [ defaultPrefilter ],
+       tweeners = {
+               "*": [function( prop, value ) {
+                       var tween = this.createTween( prop, value ),
+                               target = tween.cur(),
+                               parts = rfxnum.exec( value ),
+                               unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
+
+                               // Starting value computation is required for potential unit mismatches
+                               start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
+                                       rfxnum.exec( jQuery.css( tween.elem, prop ) ),
+                               scale = 1,
+                               maxIterations = 20;
+
+                       if ( start && start[ 3 ] !== unit ) {
+                               // Trust units reported by jQuery.css
+                               unit = unit || start[ 3 ];
+
+                               // Make sure we update the tween properties later on
+                               parts = parts || [];
+
+                               // Iteratively approximate from a nonzero starting point
+                               start = +target || 1;
+
+                               do {
+                                       // If previous iteration zeroed out, double until we get *something*
+                                       // Use a string for doubling factor so we don't accidentally see scale as unchanged below
+                                       scale = scale || ".5";
+
+                                       // Adjust and apply
+                                       start = start / scale;
+                                       jQuery.style( tween.elem, prop, start + unit );
+
+                               // Update scale, tolerating zero or NaN from tween.cur()
+                               // And breaking the loop if scale is unchanged or perfect, or if we've just had enough
+                               } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
+                       }
+
+                       // Update tween properties
+                       if ( parts ) {
+                               start = tween.start = +start || +target || 0;
+                               tween.unit = unit;
+                               // If a +=/-= token was provided, we're doing a relative animation
+                               tween.end = parts[ 1 ] ?
+                                       start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+                                       +parts[ 2 ];
+                       }
+
+                       return tween;
+               }]
+       };
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+       setTimeout(function() {
+               fxNow = undefined;
+       });
+       return ( fxNow = jQuery.now() );
+}
+
+function createTween( value, prop, animation ) {
+       var tween,
+               collection = ( tweeners[ prop ] || [] ).concat( 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 Animation( elem, properties, options ) {
+       var result,
+               stopped,
+               index = 0,
+               length = animationPrefilters.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 ),
+                               // 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: {} }, 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.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 = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
+               if ( 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 );
+}
+
+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;
+               }
+       }
+}
+
+jQuery.Animation = jQuery.extend( Animation, {
+
+       tweener: function( props, callback ) {
+               if ( jQuery.isFunction( props ) ) {
+                       callback = props;
+                       props = [ "*" ];
+               } else {
+                       props = props.split(" ");
+               }
+
+               var prop,
+                       index = 0,
+                       length = props.length;
+
+               for ( ; index < length ; index++ ) {
+                       prop = props[ index ];
+                       tweeners[ prop ] = tweeners[ prop ] || [];
+                       tweeners[ prop ].unshift( callback );
+               }
+       },
+
+       prefilter: function( callback, prepend ) {
+               if ( prepend ) {
+                       animationPrefilters.unshift( callback );
+               } else {
+                       animationPrefilters.push( callback );
+               }
+       }
+});
+
+function defaultPrefilter( elem, props, opts ) {
+       /* jshint validthis: true */
+       var prop, value, toggle, tween, hooks, oldfire,
+               anim = this,
+               orig = {},
+               style = elem.style,
+               hidden = elem.nodeType && isHidden( elem ),
+               dataShow = data_priv.get( 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 IE9-10 do 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
+               if ( jQuery.css( elem, "display" ) === "inline" &&
+                               jQuery.css( elem, "float" ) === "none" ) {
+
+                       style.display = "inline-block";
+               }
+       }
+
+       if ( opts.overflow ) {
+               style.overflow = "hidden";
+               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 );
+               }
+       }
+
+       if ( !jQuery.isEmptyObject( orig ) ) {
+               if ( dataShow ) {
+                       if ( "hidden" in dataShow ) {
+                               hidden = dataShow.hidden;
+                       }
+               } else {
+                       dataShow = data_priv.access( 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;
+
+                       data_priv.remove( 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;
+                               }
+                       }
+               }
+       }
+}
+
+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 || "swing";
+               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;
+
+                       if ( tween.elem[ tween.prop ] != null &&
+                               (!tween.elem.style || 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.style && ( 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: IE9
+// 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.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 );
+       };
+});
+
+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 || data_priv.get( 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 = data_priv.get( 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 = data_priv.get( 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;
+               });
+       }
+});
+
+// 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;
+}
+
+// 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.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.easing = {
+       linear: function( p ) {
+               return p;
+       },
+       swing: function( p ) {
+               return 0.5 - Math.cos( p*Math.PI ) / 2;
+       }
+};
+
+jQuery.timers = [];
+jQuery.fx = Tween.prototype.init;
+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 ) {
+       if ( timer() && jQuery.timers.push( timer ) ) {
+               jQuery.fx.start();
+       }
+};
+
+jQuery.fx.interval = 13;
+
+jQuery.fx.start = function() {
+       if ( !timerId ) {
+               timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
+       }
+};
+
+jQuery.fx.stop = function() {
+       clearInterval( timerId );
+       timerId = null;
+};
+
+jQuery.fx.speeds = {
+       slow: 600,
+       fast: 200,
+       // Default speed
+       _default: 400
+};
+
+// Back Compat <1.8 extension point
+jQuery.fx.step = {};
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+       jQuery.expr.filters.animated = function( elem ) {
+               return jQuery.grep(jQuery.timers, function( fn ) {
+                       return elem === fn.elem;
+               }).length;
+       };
+}
+jQuery.fn.offset = function( options ) {
+       if ( arguments.length ) {
+               return options === undefined ?
+                       this :
+                       this.each(function( i ) {
+                               jQuery.offset.setOffset( this, options, i );
+                       });
+       }
+
+       var docElem, win,
+               elem = this[ 0 ],
+               box = { top: 0, left: 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 !== core_strundefined ) {
+               box = elem.getBoundingClientRect();
+       }
+       win = getWindow( doc );
+       return {
+               top: box.top + win.pageYOffset - docElem.clientTop,
+               left: box.left + win.pageXOffset - docElem.clientLeft
+       };
+};
+
+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" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -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 ) ) {
+                       options = options.call( elem, i, 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({
+
+       position: function() {
+               if ( !this[ 0 ] ) {
+                       return;
+               }
+
+               var offsetParent, offset,
+                       elem = this[ 0 ],
+                       parentOffset = { top: 0, left: 0 };
+
+               // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's 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
+               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 || docElem;
+
+                       while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
+                               offsetParent = offsetParent.offsetParent;
+                       }
+
+                       return offsetParent || docElem;
+               });
+       }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
+       var top = "pageYOffset" === prop;
+
+       jQuery.fn[ method ] = function( val ) {
+               return jQuery.access( this, function( elem, method, val ) {
+                       var win = getWindow( elem );
+
+                       if ( val === undefined ) {
+                               return win ? win[ prop ] : elem[ method ];
+                       }
+
+                       if ( win ) {
+                               win.scrollTo(
+                                       !top ? val : window.pageXOffset,
+                                       top ? val : window.pageYOffset
+                               );
+
+                       } else {
+                               elem[ method ] = val;
+                       }
+               }, method, val, arguments.length, null );
+       };
+});
+
+function getWindow( elem ) {
+       return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
+}
+// 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 jQuery.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
+                                       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 );
+               };
+       });
+});
+// Limit scope pollution from any deprecated API
+// (function() {
+
+// The number of elements contained in the matched element set
+jQuery.fn.size = function() {
+       return this.length;
+};
+
+jQuery.fn.andSelf = jQuery.fn.addBack;
+
+// })();
+if ( typeof module === "object" && module && typeof module.exports === "object" ) {
+       // Expose jQuery as module.exports in loaders that implement the Node
+       // module pattern (including browserify). Do not create the global, since
+       // the user will be storing it themselves locally, and globals are frowned
+       // upon in the Node module world.
+       module.exports = jQuery;
+} else {
+       // 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.
+       if ( typeof define === "function" && define.amd ) {
+               define( "jquery", [], function () { return jQuery; } );
+       }
+}
+
+// If there is a window object, that at least has a document property,
+// define jQuery and $ identifiers
+if ( typeof window === "object" && typeof window.document === "object" ) {
+       window.jQuery = window.$ = jQuery;
+}
+
+})( window );
+
+/**
+ * @license
+ * Lo-Dash 2.2.1 (Custom Build) <http://lodash.com/>
+ * Build: `lodash modern -o ./dist/lodash.js`
+ * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
+ * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license <http://lodash.com/license>
+ */
+;(function() {
+
+  /** Used as a safe reference for `undefined` in pre ES5 environments */
+  var undefined;
+
+  /** Used to pool arrays and objects used internally */
+  var arrayPool = [],
+      objectPool = [];
+
+  /** Used to generate unique IDs */
+  var idCounter = 0;
+
+  /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
+  var keyPrefix = +new Date + '';
+
+  /** Used as the size when optimizations are enabled for large arrays */
+  var largeArraySize = 75;
+
+  /** Used as the max size of the `arrayPool` and `objectPool` */
+  var maxPoolSize = 40;
+
+  /** Used to detect and test whitespace */
+  var whitespace = (
+    // whitespace
+    ' \t\x0B\f\xA0\ufeff' +
+
+    // line terminators
+    '\n\r\u2028\u2029' +
+
+    // unicode category "Zs" space separators
+    '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
+  );
+
+  /** Used to match empty string literals in compiled template source */
+  var reEmptyStringLeading = /\b__p \+= '';/g,
+      reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
+      reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
+
+  /**
+   * Used to match ES6 template delimiters
+   * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6
+   */
+  var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
+
+  /** Used to match regexp flags from their coerced string values */
+  var reFlags = /\w*$/;
+
+  /** Used to detected named functions */
+  var reFuncName = /^function[ \n\r\t]+\w/;
+
+  /** Used to match "interpolate" template delimiters */
+  var reInterpolate = /<%=([\s\S]+?)%>/g;
+
+  /** Used to match leading whitespace and zeros to be removed */
+  var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
+
+  /** Used to ensure capturing order of template delimiters */
+  var reNoMatch = /($^)/;
+
+  /** Used to detect functions containing a `this` reference */
+  var reThis = /\bthis\b/;
+
+  /** Used to match unescaped characters in compiled string literals */
+  var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
+
+  /** Used to assign default `context` object properties */
+  var contextProps = [
+    'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object',
+    'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
+    'parseInt', 'setImmediate', 'setTimeout'
+  ];
+
+  /** Used to make template sourceURLs easier to identify */
+  var templateCounter = 0;
+
+  /** `Object#toString` result shortcuts */
+  var argsClass = '[object Arguments]',
+      arrayClass = '[object Array]',
+      boolClass = '[object Boolean]',
+      dateClass = '[object Date]',
+      funcClass = '[object Function]',
+      numberClass = '[object Number]',
+      objectClass = '[object Object]',
+      regexpClass = '[object RegExp]',
+      stringClass = '[object String]';
+
+  /** Used to identify object classifications that `_.clone` supports */
+  var cloneableClasses = {};
+  cloneableClasses[funcClass] = false;
+  cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
+  cloneableClasses[boolClass] = cloneableClasses[dateClass] =
+  cloneableClasses[numberClass] = cloneableClasses[objectClass] =
+  cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
+
+  /** Used as an internal `_.debounce` options object */
+  var debounceOptions = {
+    'leading': false,
+    'maxWait': 0,
+    'trailing': false
+  };
+
+  /** Used as the property descriptor for `__bindData__` */
+  var descriptor = {
+    'configurable': false,
+    'enumerable': false,
+    'value': null,
+    'writable': false
+  };
+
+  /** Used to determine if values are of the language type Object */
+  var objectTypes = {
+    'boolean': false,
+    'function': true,
+    'object': true,
+    'number': false,
+    'string': false,
+    'undefined': false
+  };
+
+  /** Used to escape characters for inclusion in compiled string literals */
+  var stringEscapes = {
+    '\\': '\\',
+    "'": "'",
+    '\n': 'n',
+    '\r': 'r',
+    '\t': 't',
+    '\u2028': 'u2028',
+    '\u2029': 'u2029'
+  };
+
+  /** Used as a reference to the global object */
+  var root = (objectTypes[typeof window] && window) || this;
+
+  /** Detect free variable `exports` */
+  var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
+
+  /** Detect free variable `module` */
+  var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
+
+  /** Detect the popular CommonJS extension `module.exports` */
+  var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
+
+  /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
+  var freeGlobal = objectTypes[typeof global] && global;
+  if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
+    root = freeGlobal;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * The base implementation of `_.indexOf` without support for binary searches
+   * or `fromIndex` constraints.
+   *
+   * @private
+   * @param {Array} array The array to search.
+   * @param {*} value The value to search for.
+   * @param {number} [fromIndex=0] The index to search from.
+   * @returns {number} Returns the index of the matched value or `-1`.
+   */
+  function baseIndexOf(array, value, fromIndex) {
+    var index = (fromIndex || 0) - 1,
+        length = array ? array.length : 0;
+
+    while (++index < length) {
+      if (array[index] === value) {
+        return index;
+      }
+    }
+    return -1;
+  }
+
+  /**
+   * An implementation of `_.contains` for cache objects that mimics the return
+   * signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
+   *
+   * @private
+   * @param {Object} cache The cache object to inspect.
+   * @param {*} value The value to search for.
+   * @returns {number} Returns `0` if `value` is found, else `-1`.
+   */
+  function cacheIndexOf(cache, value) {
+    var type = typeof value;
+    cache = cache.cache;
+
+    if (type == 'boolean' || value == null) {
+      return cache[value] ? 0 : -1;
+    }
+    if (type != 'number' && type != 'string') {
+      type = 'object';
+    }
+    var key = type == 'number' ? value : keyPrefix + value;
+    cache = (cache = cache[type]) && cache[key];
+
+    return type == 'object'
+      ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
+      : (cache ? 0 : -1);
+  }
+
+  /**
+   * Adds a given value to the corresponding cache object.
+   *
+   * @private
+   * @param {*} value The value to add to the cache.
+   */
+  function cachePush(value) {
+    var cache = this.cache,
+        type = typeof value;
+
+    if (type == 'boolean' || value == null) {
+      cache[value] = true;
+    } else {
+      if (type != 'number' && type != 'string') {
+        type = 'object';
+      }
+      var key = type == 'number' ? value : keyPrefix + value,
+          typeCache = cache[type] || (cache[type] = {});
+
+      if (type == 'object') {
+        (typeCache[key] || (typeCache[key] = [])).push(value);
+      } else {
+        typeCache[key] = true;
+      }
+    }
+  }
+
+  /**
+   * Used by `_.max` and `_.min` as the default callback when a given
+   * collection is a string value.
+   *
+   * @private
+   * @param {string} value The character to inspect.
+   * @returns {number} Returns the code unit of given character.
+   */
+  function charAtCallback(value) {
+    return value.charCodeAt(0);
+  }
+
+  /**
+   * Used by `sortBy` to compare transformed `collection` elements, stable sorting
+   * them in ascending order.
+   *
+   * @private
+   * @param {Object} a The object to compare to `b`.
+   * @param {Object} b The object to compare to `a`.
+   * @returns {number} Returns the sort order indicator of `1` or `-1`.
+   */
+  function compareAscending(a, b) {
+    var ac = a.criteria,
+        bc = b.criteria;
+
+    // ensure a stable sort in V8 and other engines
+    // http://code.google.com/p/v8/issues/detail?id=90
+    if (ac !== bc) {
+      if (ac > bc || typeof ac == 'undefined') {
+        return 1;
+      }
+      if (ac < bc || typeof bc == 'undefined') {
+        return -1;
+      }
+    }
+    // The JS engine embedded in Adobe applications like InDesign has a buggy
+    // `Array#sort` implementation that causes it, under certain circumstances,
+    // to return the same value for `a` and `b`.
+    // See https://github.com/jashkenas/underscore/pull/1247
+    return a.index - b.index;
+  }
+
+  /**
+   * Creates a cache object to optimize linear searches of large arrays.
+   *
+   * @private
+   * @param {Array} [array=[]] The array to search.
+   * @returns {null|Object} Returns the cache object or `null` if caching should not be used.
+   */
+  function createCache(array) {
+    var index = -1,
+        length = array.length,
+        first = array[0],
+        mid = array[(length / 2) | 0],
+        last = array[length - 1];
+
+    if (first && typeof first == 'object' &&
+        mid && typeof mid == 'object' && last && typeof last == 'object') {
+      return false;
+    }
+    var cache = getObject();
+    cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
+
+    var result = getObject();
+    result.array = array;
+    result.cache = cache;
+    result.push = cachePush;
+
+    while (++index < length) {
+      result.push(array[index]);
+    }
+    return result;
+  }
+
+  /**
+   * Used by `template` to escape characters for inclusion in compiled
+   * string literals.
+   *
+   * @private
+   * @param {string} match The matched character to escape.
+   * @returns {string} Returns the escaped character.
+   */
+  function escapeStringChar(match) {
+    return '\\' + stringEscapes[match];
+  }
+
+  /**
+   * Gets an array from the array pool or creates a new one if the pool is empty.
+   *
+   * @private
+   * @returns {Array} The array from the pool.
+   */
+  function getArray() {
+    return arrayPool.pop() || [];
+  }
+
+  /**
+   * Gets an object from the object pool or creates a new one if the pool is empty.
+   *
+   * @private
+   * @returns {Object} The object from the pool.
+   */
+  function getObject() {
+    return objectPool.pop() || {
+      'array': null,
+      'cache': null,
+      'criteria': null,
+      'false': false,
+      'index': 0,
+      'null': false,
+      'number': null,
+      'object': null,
+      'push': null,
+      'string': null,
+      'true': false,
+      'undefined': false,
+      'value': null
+    };
+  }
+
+  /**
+   * A no-operation function.
+   *
+   * @private
+   */
+  function noop() {
+    // no operation performed
+  }
+
+  /**
+   * Releases the given array back to the array pool.
+   *
+   * @private
+   * @param {Array} [array] The array to release.
+   */
+  function releaseArray(array) {
+    array.length = 0;
+    if (arrayPool.length < maxPoolSize) {
+      arrayPool.push(array);
+    }
+  }
+
+  /**
+   * Releases the given object back to the object pool.
+   *
+   * @private
+   * @param {Object} [object] The object to release.
+   */
+  function releaseObject(object) {
+    var cache = object.cache;
+    if (cache) {
+      releaseObject(cache);
+    }
+    object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
+    if (objectPool.length < maxPoolSize) {
+      objectPool.push(object);
+    }
+  }
+
+  /**
+   * Slices the `collection` from the `start` index up to, but not including,
+   * the `end` index.
+   *
+   * Note: This function is used instead of `Array#slice` to support node lists
+   * in IE < 9 and to ensure dense arrays are returned.
+   *
+   * @private
+   * @param {Array|Object|string} collection The collection to slice.
+   * @param {number} start The start index.
+   * @param {number} end The end index.
+   * @returns {Array} Returns the new array.
+   */
+  function slice(array, start, end) {
+    start || (start = 0);
+    if (typeof end == 'undefined') {
+      end = array ? array.length : 0;
+    }
+    var index = -1,
+        length = end - start || 0,
+        result = Array(length < 0 ? 0 : length);
+
+    while (++index < length) {
+      result[index] = array[start + index];
+    }
+    return result;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Create a new `lodash` function using the given context object.
+   *
+   * @static
+   * @memberOf _
+   * @category Utilities
+   * @param {Object} [context=root] The context object.
+   * @returns {Function} Returns the `lodash` function.
+   */
+  function runInContext(context) {
+    // Avoid issues with some ES3 environments that attempt to use values, named
+    // after built-in constructors like `Object`, for the creation of literals.
+    // ES5 clears this up by stating that literals must use built-in constructors.
+    // See http://es5.github.io/#x11.1.5.
+    context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
+
+    /** Native constructor references */
+    var Array = context.Array,
+        Boolean = context.Boolean,
+        Date = context.Date,
+        Function = context.Function,
+        Math = context.Math,
+        Number = context.Number,
+        Object = context.Object,
+        RegExp = context.RegExp,
+        String = context.String,
+        TypeError = context.TypeError;
+
+    /**
+     * Used for `Array` method references.
+     *
+     * Normally `Array.prototype` would suffice, however, using an array literal
+     * avoids issues in Narwhal.
+     */
+    var arrayRef = [];
+
+    /** Used for native method references */
+    var objectProto = Object.prototype;
+
+    /** Used to restore the original `_` reference in `noConflict` */
+    var oldDash = context._;
+
+    /** Used to detect if a method is native */
+    var reNative = RegExp('^' +
+      String(objectProto.valueOf)
+        .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+        .replace(/valueOf|for [^\]]+/g, '.+?') + '$'
+    );
+
+    /** Native method shortcuts */
+    var ceil = Math.ceil,
+        clearTimeout = context.clearTimeout,
+        floor = Math.floor,
+        fnToString = Function.prototype.toString,
+        getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
+        hasOwnProperty = objectProto.hasOwnProperty,
+        now = reNative.test(now = Date.now) && now || function() { return +new Date; },
+        push = arrayRef.push,
+        setImmediate = context.setImmediate,
+        setTimeout = context.setTimeout,
+        splice = arrayRef.splice,
+        toString = objectProto.toString,
+        unshift = arrayRef.unshift;
+
+    var defineProperty = (function() {
+      try {
+        var o = {},
+            func = reNative.test(func = Object.defineProperty) && func,
+            result = func(o, o, o) && func;
+      } catch(e) { }
+      return result;
+    }());
+
+    /* Native method shortcuts for methods with the same name as other `lodash` methods */
+    var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind,
+        nativeCreate = reNative.test(nativeCreate = Object.create) && nativeCreate,
+        nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
+        nativeIsFinite = context.isFinite,
+        nativeIsNaN = context.isNaN,
+        nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
+        nativeMax = Math.max,
+        nativeMin = Math.min,
+        nativeParseInt = context.parseInt,
+        nativeRandom = Math.random,
+        nativeSlice = arrayRef.slice;
+
+    /** Detect various environments */
+    var isIeOpera = reNative.test(context.attachEvent),
+        isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera);
+
+    /** Used to lookup a built-in constructor by [[Class]] */
+    var ctorByClass = {};
+    ctorByClass[arrayClass] = Array;
+    ctorByClass[boolClass] = Boolean;
+    ctorByClass[dateClass] = Date;
+    ctorByClass[funcClass] = Function;
+    ctorByClass[objectClass] = Object;
+    ctorByClass[numberClass] = Number;
+    ctorByClass[regexpClass] = RegExp;
+    ctorByClass[stringClass] = String;
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates a `lodash` object which wraps the given value to enable intuitive
+     * method chaining.
+     *
+     * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
+     * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
+     * and `unshift`
+     *
+     * Chaining is supported in custom builds as long as the `value` method is
+     * implicitly or explicitly included in the build.
+     *
+     * The chainable wrapper functions are:
+     * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
+     * `compose`, `concat`, `countBy`, `createCallback`, `curry`, `debounce`,
+     * `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`,
+     * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`,
+     * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`,
+     * `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, `once`, `pairs`,
+     * `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, `range`, `reject`,
+     * `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`,
+     * `tap`, `throttle`, `times`, `toArray`, `transform`, `union`, `uniq`, `unshift`,
+     * `unzip`, `values`, `where`, `without`, `wrap`, and `zip`
+     *
+     * The non-chainable wrapper functions are:
+     * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
+     * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
+     * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
+     * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
+     * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
+     * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
+     * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
+     * `template`, `unescape`, `uniqueId`, and `value`
+     *
+     * The wrapper functions `first` and `last` return wrapped values when `n` is
+     * provided, otherwise they return unwrapped values.
+     *
+     * Explicit chaining can be enabled by using the `_.chain` method.
+     *
+     * @name _
+     * @constructor
+     * @category Chaining
+     * @param {*} value The value to wrap in a `lodash` instance.
+     * @returns {Object} Returns a `lodash` instance.
+     * @example
+     *
+     * var wrapped = _([1, 2, 3]);
+     *
+     * // returns an unwrapped value
+     * wrapped.reduce(function(sum, num) {
+     *   return sum + num;
+     * });
+     * // => 6
+     *
+     * // returns a wrapped value
+     * var squares = wrapped.map(function(num) {
+     *   return num * num;
+     * });
+     *
+     * _.isArray(squares);
+     * // => false
+     *
+     * _.isArray(squares.value());
+     * // => true
+     */
+    function lodash(value) {
+      // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
+      return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
+       ? value
+       : new lodashWrapper(value);
+    }
+
+    /**
+     * A fast path for creating `lodash` wrapper objects.
+     *
+     * @private
+     * @param {*} value The value to wrap in a `lodash` instance.
+     * @param {boolean} chainAll A flag to enable chaining for all methods
+     * @returns {Object} Returns a `lodash` instance.
+     */
+    function lodashWrapper(value, chainAll) {
+      this.__chain__ = !!chainAll;
+      this.__wrapped__ = value;
+    }
+    // ensure `new lodashWrapper` is an instance of `lodash`
+    lodashWrapper.prototype = lodash.prototype;
+
+    /**
+     * An object used to flag environments features.
+     *
+     * @static
+     * @memberOf _
+     * @type Object
+     */
+    var support = lodash.support = {};
+
+    /**
+     * Detect if `Function#bind` exists and is inferred to be fast (all but V8).
+     *
+     * @memberOf _.support
+     * @type boolean
+     */
+    support.fastBind = nativeBind && !isV8;
+
+    /**
+     * Detect if functions can be decompiled by `Function#toString`
+     * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
+     *
+     * @memberOf _.support
+     * @type boolean
+     */
+    support.funcDecomp = !reNative.test(context.WinRTError) && reThis.test(runInContext);
+
+    /**
+     * Detect if `Function#name` is supported (all but IE).
+     *
+     * @memberOf _.support
+     * @type boolean
+     */
+    support.funcNames = typeof Function.name == 'string';
+
+    /**
+     * By default, the template delimiters used by Lo-Dash are similar to those in
+     * embedded Ruby (ERB). Change the following template settings to use alternative
+     * delimiters.
+     *
+     * @static
+     * @memberOf _
+     * @type Object
+     */
+    lodash.templateSettings = {
+
+      /**
+       * Used to detect `data` property values to be HTML-escaped.
+       *
+       * @memberOf _.templateSettings
+       * @type RegExp
+       */
+      'escape': /<%-([\s\S]+?)%>/g,
+
+      /**
+       * Used to detect code to be evaluated.
+       *
+       * @memberOf _.templateSettings
+       * @type RegExp
+       */
+      'evaluate': /<%([\s\S]+?)%>/g,
+
+      /**
+       * Used to detect `data` property values to inject.
+       *
+       * @memberOf _.templateSettings
+       * @type RegExp
+       */
+      'interpolate': reInterpolate,
+
+      /**
+       * Used to reference the data object in the template text.
+       *
+       * @memberOf _.templateSettings
+       * @type string
+       */
+      'variable': '',
+
+      /**
+       * Used to import variables into the compiled template.
+       *
+       * @memberOf _.templateSettings
+       * @type Object
+       */
+      'imports': {
+
+        /**
+         * A reference to the `lodash` function.
+         *
+         * @memberOf _.templateSettings.imports
+         * @type Function
+         */
+        '_': lodash
+      }
+    };
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * The base implementation of `_.clone` without argument juggling or support
+     * for `thisArg` binding.
+     *
+     * @private
+     * @param {*} value The value to clone.
+     * @param {boolean} [deep=false] Specify a deep clone.
+     * @param {Function} [callback] The function to customize cloning values.
+     * @param {Array} [stackA=[]] Tracks traversed source objects.
+     * @param {Array} [stackB=[]] Associates clones with source counterparts.
+     * @returns {*} Returns the cloned value.
+     */
+    function baseClone(value, deep, callback, stackA, stackB) {
+      if (callback) {
+        var result = callback(value);
+        if (typeof result != 'undefined') {
+          return result;
+        }
+      }
+      // inspect [[Class]]
+      var isObj = isObject(value);
+      if (isObj) {
+        var className = toString.call(value);
+        if (!cloneableClasses[className]) {
+          return value;
+        }
+        var ctor = ctorByClass[className];
+        switch (className) {
+          case boolClass:
+          case dateClass:
+            return new ctor(+value);
+
+          case numberClass:
+          case stringClass:
+            return new ctor(value);
+
+          case regexpClass:
+            result = ctor(value.source, reFlags.exec(value));
+            result.lastIndex = value.lastIndex;
+            return result;
+        }
+      } else {
+        return value;
+      }
+      var isArr = isArray(value);
+      if (deep) {
+        // check for circular references and return corresponding clone
+        var initedStack = !stackA;
+        stackA || (stackA = getArray());
+        stackB || (stackB = getArray());
+
+        var length = stackA.length;
+        while (length--) {
+          if (stackA[length] == value) {
+            return stackB[length];
+          }
+        }
+        result = isArr ? ctor(value.length) : {};
+      }
+      else {
+        result = isArr ? slice(value) : assign({}, value);
+      }
+      // add array properties assigned by `RegExp#exec`
+      if (isArr) {
+        if (hasOwnProperty.call(value, 'index')) {
+          result.index = value.index;
+        }
+        if (hasOwnProperty.call(value, 'input')) {
+          result.input = value.input;
+        }
+      }
+      // exit for shallow clone
+      if (!deep) {
+        return result;
+      }
+      // add the source value to the stack of traversed objects
+      // and associate it with its clone
+      stackA.push(value);
+      stackB.push(result);
+
+      // recursively populate clone (susceptible to call stack limits)
+      (isArr ? forEach : forOwn)(value, function(objValue, key) {
+        result[key] = baseClone(objValue, deep, callback, stackA, stackB);
+      });
+
+      if (initedStack) {
+        releaseArray(stackA);
+        releaseArray(stackB);
+      }
+      return result;
+    }
+
+    /**
+     * The base implementation of `_.createCallback` without support for creating
+     * "_.pluck" or "_.where" style callbacks.
+     *
+     * @private
+     * @param {*} [func=identity] The value to convert to a callback.
+     * @param {*} [thisArg] The `this` binding of the created callback.
+     * @param {number} [argCount] The number of arguments the callback accepts.
+     * @returns {Function} Returns a callback function.
+     */
+    function baseCreateCallback(func, thisArg, argCount) {
+      if (typeof func != 'function') {
+        return identity;
+      }
+      // exit early if there is no `thisArg`
+      if (typeof thisArg == 'undefined') {
+        return func;
+      }
+      var bindData = func.__bindData__ || (support.funcNames && !func.name);
+      if (typeof bindData == 'undefined') {
+        var source = reThis && fnToString.call(func);
+        if (!support.funcNames && source && !reFuncName.test(source)) {
+          bindData = true;
+        }
+        if (support.funcNames || !bindData) {
+          // checks if `func` references the `this` keyword and stores the result
+          bindData = !support.funcDecomp || reThis.test(source);
+          setBindData(func, bindData);
+        }
+      }
+      // exit early if there are no `this` references or `func` is bound
+      if (bindData !== true && (bindData && bindData[1] & 1)) {
+        return func;
+      }
+      switch (argCount) {
+        case 1: return function(value) {
+          return func.call(thisArg, value);
+        };
+        case 2: return function(a, b) {
+          return func.call(thisArg, a, b);
+        };
+        case 3: return function(value, index, collection) {
+          return func.call(thisArg, value, index, collection);
+        };
+        case 4: return function(accumulator, value, index, collection) {
+          return func.call(thisArg, accumulator, value, index, collection);
+        };
+      }
+      return bind(func, thisArg);
+    }
+
+    /**
+     * The base implementation of `_.flatten` without support for callback
+     * shorthands or `thisArg` binding.
+     *
+     * @private
+     * @param {Array} array The array to flatten.
+     * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
+     * @param {boolean} [isArgArrays=false] A flag to restrict flattening to arrays and `arguments` objects.
+     * @param {number} [fromIndex=0] The index to start from.
+     * @returns {Array} Returns a new flattened array.
+     */
+    function baseFlatten(array, isShallow, isArgArrays, fromIndex) {
+      var index = (fromIndex || 0) - 1,
+          length = array ? array.length : 0,
+          result = [];
+
+      while (++index < length) {
+        var value = array[index];
+
+        if (value && typeof value == 'object' && typeof value.length == 'number'
+            && (isArray(value) || isArguments(value))) {
+          // recursively flatten arrays (susceptible to call stack limits)
+          if (!isShallow) {
+            value = baseFlatten(value, isShallow, isArgArrays);
+          }
+          var valIndex = -1,
+              valLength = value.length,
+              resIndex = result.length;
+
+          result.length += valLength;
+          while (++valIndex < valLength) {
+            result[resIndex++] = value[valIndex];
+          }
+        } else if (!isArgArrays) {
+          result.push(value);
+        }
+      }
+      return result;
+    }
+
+    /**
+     * The base implementation of `_.isEqual`, without support for `thisArg` binding,
+     * that allows partial "_.where" style comparisons.
+     *
+     * @private
+     * @param {*} a The value to compare.
+     * @param {*} b The other value to compare.
+     * @param {Function} [callback] The function to customize comparing values.
+     * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
+     * @param {Array} [stackA=[]] Tracks traversed `a` objects.
+     * @param {Array} [stackB=[]] Tracks traversed `b` objects.
+     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+     */
+    function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
+      // used to indicate that when comparing objects, `a` has at least the properties of `b`
+      if (callback) {
+        var result = callback(a, b);
+        if (typeof result != 'undefined') {
+          return !!result;
+        }
+      }
+      // exit early for identical values
+      if (a === b) {
+        // treat `+0` vs. `-0` as not equal
+        return a !== 0 || (1 / a == 1 / b);
+      }
+      var type = typeof a,
+          otherType = typeof b;
+
+      // exit early for unlike primitive values
+      if (a === a &&
+          !(a && objectTypes[type]) &&
+          !(b && objectTypes[otherType])) {
+        return false;
+      }
+      // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
+      // http://es5.github.io/#x15.3.4.4
+      if (a == null || b == null) {
+        return a === b;
+      }
+      // compare [[Class]] names
+      var className = toString.call(a),
+          otherClass = toString.call(b);
+
+      if (className == argsClass) {
+        className = objectClass;
+      }
+      if (otherClass == argsClass) {
+        otherClass = objectClass;
+      }
+      if (className != otherClass) {
+        return false;
+      }
+      switch (className) {
+        case boolClass:
+        case dateClass:
+          // coerce dates and booleans to numbers, dates to milliseconds and booleans
+          // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
+          return +a == +b;
+
+        case numberClass:
+          // treat `NaN` vs. `NaN` as equal
+          return (a != +a)
+            ? b != +b
+            // but treat `+0` vs. `-0` as not equal
+            : (a == 0 ? (1 / a == 1 / b) : a == +b);
+
+        case regexpClass:
+        case stringClass:
+          // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
+          // treat string primitives and their corresponding object instances as equal
+          return a == String(b);
+      }
+      var isArr = className == arrayClass;
+      if (!isArr) {
+        // unwrap any `lodash` wrapped values
+        if (hasOwnProperty.call(a, '__wrapped__ ') || hasOwnProperty.call(b, '__wrapped__')) {
+          return baseIsEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, isWhere, stackA, stackB);
+        }
+        // exit for functions and DOM nodes
+        if (className != objectClass) {
+          return false;
+        }
+        // in older versions of Opera, `arguments` objects have `Array` constructors
+        var ctorA = a.constructor,
+            ctorB = b.constructor;
+
+        // non `Object` object instances with different constructors are not equal
+        if (ctorA != ctorB && !(
+              isFunction(ctorA) && ctorA instanceof ctorA &&
+              isFunction(ctorB) && ctorB instanceof ctorB
+            )) {
+          return false;
+        }
+      }
+      // assume cyclic structures are equal
+      // the algorithm for detecting cyclic structures is adapted from ES 5.1
+      // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
+      var initedStack = !stackA;
+      stackA || (stackA = getArray());
+      stackB || (stackB = getArray());
+
+      var length = stackA.length;
+      while (length--) {
+        if (stackA[length] == a) {
+          return stackB[length] == b;
+        }
+      }
+      var size = 0;
+      result = true;
+
+      // add `a` and `b` to the stack of traversed objects
+      stackA.push(a);
+      stackB.push(b);
+
+      // recursively compare objects and arrays (susceptible to call stack limits)
+      if (isArr) {
+        length = a.length;
+        size = b.length;
+
+        // compare lengths to determine if a deep comparison is necessary
+        result = size == a.length;
+        if (!result && !isWhere) {
+          return result;
+        }
+        // deep compare the contents, ignoring non-numeric properties
+        while (size--) {
+          var index = length,
+              value = b[size];
+
+          if (isWhere) {
+            while (index--) {
+              if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
+                break;
+              }
+            }
+          } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
+            break;
+          }
+        }
+        return result;
+      }
+      // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
+      // which, in this case, is more costly
+      forIn(b, function(value, key, b) {
+        if (hasOwnProperty.call(b, key)) {
+          // count the number of properties.
+          size++;
+          // deep compare each property value.
+          return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
+        }
+      });
+
+      if (result && !isWhere) {
+        // ensure both objects have the same number of properties
+        forIn(a, function(value, key, a) {
+          if (hasOwnProperty.call(a, key)) {
+            // `size` will be `-1` if `a` has more properties than `b`
+            return (result = --size > -1);
+          }
+        });
+      }
+      if (initedStack) {
+        releaseArray(stackA);
+        releaseArray(stackB);
+      }
+      return result;
+    }
+
+    /**
+     * The base implementation of `_.merge` without argument juggling or support
+     * for `thisArg` binding.
+     *
+     * @private
+     * @param {Object} object The destination object.
+     * @param {Object} source The source object.
+     * @param {Function} [callback] The function to customize merging properties.
+     * @param {Array} [stackA=[]] Tracks traversed source objects.
+     * @param {Array} [stackB=[]] Associates values with source counterparts.
+     */
+    function baseMerge(object, source, callback, stackA, stackB) {
+      (isArray(source) ? forEach : forOwn)(source, function(source, key) {
+        var found,
+            isArr,
+            result = source,
+            value = object[key];
+
+        if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
+          // avoid merging previously merged cyclic sources
+          var stackLength = stackA.length;
+          while (stackLength--) {
+            if ((found = stackA[stackLength] == source)) {
+              value = stackB[stackLength];
+              break;
+            }
+          }
+          if (!found) {
+            var isShallow;
+            if (callback) {
+              result = callback(value, source);
+              if ((isShallow = typeof result != 'undefined')) {
+                value = result;
+              }
+            }
+            if (!isShallow) {
+              value = isArr
+                ? (isArray(value) ? value : [])
+                : (isPlainObject(value) ? value : {});
+            }
+            // add `source` and associated `value` to the stack of traversed objects
+            stackA.push(source);
+            stackB.push(value);
+
+            // recursively merge objects and arrays (susceptible to call stack limits)
+            if (!isShallow) {
+              baseMerge(value, source, callback, stackA, stackB);
+            }
+          }
+        }
+        else {
+          if (callback) {
+            result = callback(value, source);
+            if (typeof result == 'undefined') {
+              result = source;
+            }
+          }
+          if (typeof result != 'undefined') {
+            value = result;
+          }
+        }
+        object[key] = value;
+      });
+    }
+
+    /**
+     * The base implementation of `_.uniq` without support for callback shorthands
+     * or `thisArg` binding.
+     *
+     * @private
+     * @param {Array} array The array to process.
+     * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
+     * @param {Function} [callback] The function called per iteration.
+     * @returns {Array} Returns a duplicate-value-free array.
+     */
+    function baseUniq(array, isSorted, callback) {
+      var index = -1,
+          indexOf = getIndexOf(),
+          length = array ? array.length : 0,
+          result = [];
+
+      var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
+          seen = (callback || isLarge) ? getArray() : result;
+
+      if (isLarge) {
+        var cache = createCache(seen);
+        if (cache) {
+          indexOf = cacheIndexOf;
+          seen = cache;
+        } else {
+          isLarge = false;
+          seen = callback ? seen : (releaseArray(seen), result);
+        }
+      }
+      while (++index < length) {
+        var value = array[index],
+            computed = callback ? callback(value, index, array) : value;
+
+        if (isSorted
+              ? !index || seen[seen.length - 1] !== computed
+              : indexOf(seen, computed) < 0
+            ) {
+          if (callback || isLarge) {
+            seen.push(computed);
+          }
+          result.push(value);
+        }
+      }
+      if (isLarge) {
+        releaseArray(seen.array);
+        releaseObject(seen);
+      } else if (callback) {
+        releaseArray(seen);
+      }
+      return result;
+    }
+
+    /**
+     * Creates a function that aggregates a collection, creating an object composed
+     * of keys generated from the results of running each element of the collection
+     * through a callback. The given `setter` function sets the keys and values
+     * of the composed object.
+     *
+     * @private
+     * @param {Function} setter The setter function.
+     * @returns {Function} Returns the new aggregator function.
+     */
+    function createAggregator(setter) {
+      return function(collection, callback, thisArg) {
+        var result = {};
+        callback = lodash.createCallback(callback, thisArg, 3);
+
+        var index = -1,
+            length = collection ? collection.length : 0;
+
+        if (typeof length == 'number') {
+          while (++index < length) {
+            var value = collection[index];
+            setter(result, value, callback(value, index, collection), collection);
+          }
+        } else {
+          forOwn(collection, function(value, key, collection) {
+            setter(result, value, callback(value, key, collection), collection);
+          });
+        }
+        return result;
+      };
+    }
+
+    /**
+     * Creates a function that, when called, either curries or invokes `func`
+     * with an optional `this` binding and partially applied arguments.
+     *
+     * @private
+     * @param {Function|string} func The function or method name to reference.
+     * @param {number} bitmask The bitmask of method flags to compose.
+     *  The bitmask may be composed of the following flags:
+     *  1 - `_.bind`
+     *  2 - `_.bindKey`
+     *  4 - `_.curry`
+     *  8 - `_.curry` (bound)
+     *  16 - `_.partial`
+     *  32 - `_.partialRight`
+     * @param {Array} [partialArgs] An array of arguments to prepend to those
+     *  provided to the new function.
+     * @param {Array} [partialRightArgs] An array of arguments to append to those
+     *  provided to the new function.
+     * @param {*} [thisArg] The `this` binding of `func`.
+     * @param {number} [arity] The arity of `func`.
+     * @returns {Function} Returns the new bound function.
+     */
+    function createBound(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
+      var isBind = bitmask & 1,
+          isBindKey = bitmask & 2,
+          isCurry = bitmask & 4,
+          isCurryBound = bitmask & 8,
+          isPartial = bitmask & 16,
+          isPartialRight = bitmask & 32,
+          key = func;
+
+      if (!isBindKey && !isFunction(func)) {
+        throw new TypeError;
+      }
+      if (isPartial && !partialArgs.length) {
+        bitmask &= ~16;
+        isPartial = partialArgs = false;
+      }
+      if (isPartialRight && !partialRightArgs.length) {
+        bitmask &= ~32;
+        isPartialRight = partialRightArgs = false;
+      }
+      var bindData = func && func.__bindData__;
+      if (bindData) {
+        if (isBind && !(bindData[1] & 1)) {
+          bindData[4] = thisArg;
+        }
+        if (!isBind && bindData[1] & 1) {
+          bitmask |= 8;
+        }
+        if (isCurry && !(bindData[1] & 4)) {
+          bindData[5] = arity;
+        }
+        if (isPartial) {
+          push.apply(bindData[2] || (bindData[2] = []), partialArgs);
+        }
+        if (isPartialRight) {
+          push.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
+        }
+        bindData[1] |= bitmask;
+        return createBound.apply(null, bindData);
+      }
+      // use `Function#bind` if it exists and is fast
+      // (in V8 `Function#bind` is slower except when partially applied)
+      if (isBind && !(isBindKey || isCurry || isPartialRight) &&
+          (support.fastBind || (nativeBind && isPartial))) {
+        if (isPartial) {
+          var args = [thisArg];
+          push.apply(args, partialArgs);
+        }
+        var bound = isPartial
+          ? nativeBind.apply(func, args)
+          : nativeBind.call(func, thisArg);
+      }
+      else {
+        bound = function() {
+          // `Function#bind` spec
+          // http://es5.github.io/#x15.3.4.5
+          var args = arguments,
+              thisBinding = isBind ? thisArg : this;
+
+          if (isCurry || isPartial || isPartialRight) {
+            args = nativeSlice.call(args);
+            if (isPartial) {
+              unshift.apply(args, partialArgs);
+            }
+            if (isPartialRight) {
+              push.apply(args, partialRightArgs);
+            }
+            if (isCurry && args.length < arity) {
+              bitmask |= 16 & ~32;
+              return createBound(func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity);
+            }
+          }
+          if (isBindKey) {
+            func = thisBinding[key];
+          }
+          if (this instanceof bound) {
+            // ensure `new bound` is an instance of `func`
+            thisBinding = createObject(func.prototype);
+
+            // mimic the constructor's `return` behavior
+            // http://es5.github.io/#x13.2.2
+            var result = func.apply(thisBinding, args);
+            return isObject(result) ? result : thisBinding;
+          }
+          return func.apply(thisBinding, args);
+        };
+      }
+      setBindData(bound, nativeSlice.call(arguments));
+      return bound;
+    }
+
+    /**
+     * Creates a new object with the specified `prototype`.
+     *
+     * @private
+     * @param {Object} prototype The prototype object.
+     * @returns {Object} Returns the new object.
+     */
+    function createObject(prototype) {
+      return isObject(prototype) ? nativeCreate(prototype) : {};
+    }
+    // fallback for browsers without `Object.create`
+    if (!nativeCreate) {
+      createObject = function(prototype) {
+        if (isObject(prototype)) {
+          noop.prototype = prototype;
+          var result = new noop;
+          noop.prototype = null;
+        }
+        return result || {};
+      };
+    }
+
+    /**
+     * Used by `escape` to convert characters to HTML entities.
+     *
+     * @private
+     * @param {string} match The matched character to escape.
+     * @returns {string} Returns the escaped character.
+     */
+    function escapeHtmlChar(match) {
+      return htmlEscapes[match];
+    }
+
+    /**
+     * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
+     * customized, this method returns the custom method, otherwise it returns
+     * the `baseIndexOf` function.
+     *
+     * @private
+     * @returns {Function} Returns the "indexOf" function.
+     */
+    function getIndexOf() {
+      var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
+      return result;
+    }
+
+    /**
+     * Sets `this` binding data on a given function.
+     *
+     * @private
+     * @param {Function} func The function to set data on.
+     * @param {*} value The value to set.
+     */
+    var setBindData = !defineProperty ? noop : function(func, value) {
+      descriptor.value = value;
+      defineProperty(func, '__bindData__', descriptor);
+    };
+
+    /**
+     * A fallback implementation of `isPlainObject` which checks if a given value
+     * is an object created by the `Object` constructor, assuming objects created
+     * by the `Object` constructor have no inherited enumerable properties and that
+     * there are no `Object.prototype` extensions.
+     *
+     * @private
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
+     */
+    function shimIsPlainObject(value) {
+      var ctor,
+          result;
+
+      // avoid non Object objects, `arguments` objects, and DOM elements
+      if (!(value && toString.call(value) == objectClass) ||
+          (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
+        return false;
+      }
+      // In most environments an object's own properties are iterated before
+      // its inherited properties. If the last iterated property is an object's
+      // own property then there are no inherited enumerable properties.
+      forIn(value, function(value, key) {
+        result = key;
+      });
+      return typeof result == 'undefined' || hasOwnProperty.call(value, result);
+    }
+
+    /**
+     * Used by `unescape` to convert HTML entities to characters.
+     *
+     * @private
+     * @param {string} match The matched character to unescape.
+     * @returns {string} Returns the unescaped character.
+     */
+    function unescapeHtmlChar(match) {
+      return htmlUnescapes[match];
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Checks if `value` is an `arguments` object.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
+     * @example
+     *
+     * (function() { return _.isArguments(arguments); })(1, 2, 3);
+     * // => true
+     *
+     * _.isArguments([1, 2, 3]);
+     * // => false
+     */
+    function isArguments(value) {
+      return value && typeof value == 'object' && typeof value.length == 'number' &&
+        toString.call(value) == argsClass || false;
+    }
+
+    /**
+     * Checks if `value` is an array.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is an array, else `false`.
+     * @example
+     *
+     * (function() { return _.isArray(arguments); })();
+     * // => false
+     *
+     * _.isArray([1, 2, 3]);
+     * // => true
+     */
+    var isArray = nativeIsArray || function(value) {
+      return value && typeof value == 'object' && typeof value.length == 'number' &&
+        toString.call(value) == arrayClass || false;
+    };
+
+    /**
+     * A fallback implementation of `Object.keys` which produces an array of the
+     * given object's own enumerable property names.
+     *
+     * @private
+     * @type Function
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property names.
+     */
+    var shimKeys = function(object) {
+      var index, iterable = object, result = [];
+      if (!iterable) return result;
+      if (!(objectTypes[typeof object])) return result;
+        for (index in iterable) {
+          if (hasOwnProperty.call(iterable, index)) {
+            result.push(index);
+          }
+        }
+      return result
+    };
+
+    /**
+     * Creates an array composed of the own enumerable property names of an object.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property names.
+     * @example
+     *
+     * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
+     * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
+     */
+    var keys = !nativeKeys ? shimKeys : function(object) {
+      if (!isObject(object)) {
+        return [];
+      }
+      return nativeKeys(object);
+    };
+
+    /**
+     * Used to convert characters to HTML entities:
+     *
+     * Though the `>` character is escaped for symmetry, characters like `>` and `/`
+     * don't require escaping in HTML and have no special meaning unless they're part
+     * of a tag or an unquoted attribute value.
+     * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
+     */
+    var htmlEscapes = {
+      '&': '&amp;',
+      '<': '&lt;',
+      '>': '&gt;',
+      '"': '&quot;',
+      "'": '&#39;'
+    };
+
+    /** Used to convert HTML entities to characters */
+    var htmlUnescapes = invert(htmlEscapes);
+
+    /** Used to match HTML entities and HTML characters */
+    var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
+        reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Assigns own enumerable properties of source object(s) to the destination
+     * object. Subsequent sources will overwrite property assignments of previous
+     * sources. If a callback is provided it will be executed to produce the
+     * assigned values. The callback is bound to `thisArg` and invoked with two
+     * arguments; (objectValue, sourceValue).
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @alias extend
+     * @category Objects
+     * @param {Object} object The destination object.
+     * @param {...Object} [source] The source objects.
+     * @param {Function} [callback] The function to customize assigning values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the destination object.
+     * @example
+     *
+     * _.assign({ 'name': 'moe' }, { 'age': 40 });
+     * // => { 'name': 'moe', 'age': 40 }
+     *
+     * var defaults = _.partialRight(_.assign, function(a, b) {
+     *   return typeof a == 'undefined' ? b : a;
+     * });
+     *
+     * var food = { 'name': 'apple' };
+     * defaults(food, { 'name': 'banana', 'type': 'fruit' });
+     * // => { 'name': 'apple', 'type': 'fruit' }
+     */
+    var assign = function(object, source, guard) {
+      var index, iterable = object, result = iterable;
+      if (!iterable) return result;
+      var args = arguments,
+          argsIndex = 0,
+          argsLength = typeof guard == 'number' ? 2 : args.length;
+      if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
+        var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);
+      } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
+        callback = args[--argsLength];
+      }
+      while (++argsIndex < argsLength) {
+        iterable = args[argsIndex];
+        if (iterable && objectTypes[typeof iterable]) {
+        var ownIndex = -1,
+            ownProps = objectTypes[typeof iterable] && keys(iterable),
+            length = ownProps ? ownProps.length : 0;
+
+        while (++ownIndex < length) {
+          index = ownProps[ownIndex];
+          result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
+        }
+        }
+      }
+      return result
+    };
+
+    /**
+     * Creates a clone of `value`. If `deep` is `true` nested objects will also
+     * be cloned, otherwise they will be assigned by reference. If a callback
+     * is provided it will be executed to produce the cloned values. If the
+     * callback returns `undefined` cloning will be handled by the method instead.
+     * The callback is bound to `thisArg` and invoked with one argument; (value).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to clone.
+     * @param {boolean} [deep=false] Specify a deep clone.
+     * @param {Function} [callback] The function to customize cloning values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the cloned value.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * var shallow = _.clone(stooges);
+     * shallow[0] === stooges[0];
+     * // => true
+     *
+     * var deep = _.clone(stooges, true);
+     * deep[0] === stooges[0];
+     * // => false
+     *
+     * _.mixin({
+     *   'clone': _.partialRight(_.clone, function(value) {
+     *     return _.isElement(value) ? value.cloneNode(false) : undefined;
+     *   })
+     * });
+     *
+     * var clone = _.clone(document.body);
+     * clone.childNodes.length;
+     * // => 0
+     */
+    function clone(value, deep, callback, thisArg) {
+      // allows working with "Collections" methods without using their `index`
+      // and `collection` arguments for `deep` and `callback`
+      if (typeof deep != 'boolean' && deep != null) {
+        thisArg = callback;
+        callback = deep;
+        deep = false;
+      }
+      return baseClone(value, deep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
+    }
+
+    /**
+     * Creates a deep clone of `value`. If a callback is provided it will be
+     * executed to produce the cloned values. If the callback returns `undefined`
+     * cloning will be handled by the method instead. The callback is bound to
+     * `thisArg` and invoked with one argument; (value).
+     *
+     * Note: This method is loosely based on the structured clone algorithm. Functions
+     * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
+     * objects created by constructors other than `Object` are cloned to plain `Object` objects.
+     * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to deep clone.
+     * @param {Function} [callback] The function to customize cloning values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the deep cloned value.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * var deep = _.cloneDeep(stooges);
+     * deep[0] === stooges[0];
+     * // => false
+     *
+     * var view = {
+     *   'label': 'docs',
+     *   'node': element
+     * };
+     *
+     * var clone = _.cloneDeep(view, function(value) {
+     *   return _.isElement(value) ? value.cloneNode(true) : undefined;
+     * });
+     *
+     * clone.node == view.node;
+     * // => false
+     */
+    function cloneDeep(value, callback, thisArg) {
+      return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
+    }
+
+    /**
+     * Assigns own enumerable properties of source object(s) to the destination
+     * object for all destination properties that resolve to `undefined`. Once a
+     * property is set, additional defaults of the same property will be ignored.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {Object} object The destination object.
+     * @param {...Object} [source] The source objects.
+     * @param- {Object} [guard] Allows working with `_.reduce` without using its
+     *  `key` and `object` arguments as sources.
+     * @returns {Object} Returns the destination object.
+     * @example
+     *
+     * var food = { 'name': 'apple' };
+     * _.defaults(food, { 'name': 'banana', 'type': 'fruit' });
+     * // => { 'name': 'apple', 'type': 'fruit' }
+     */
+    var defaults = function(object, source, guard) {
+      var index, iterable = object, result = iterable;
+      if (!iterable) return result;
+      var args = arguments,
+          argsIndex = 0,
+          argsLength = typeof guard == 'number' ? 2 : args.length;
+      while (++argsIndex < argsLength) {
+        iterable = args[argsIndex];
+        if (iterable && objectTypes[typeof iterable]) {
+        var ownIndex = -1,
+            ownProps = objectTypes[typeof iterable] && keys(iterable),
+            length = ownProps ? ownProps.length : 0;
+
+        while (++ownIndex < length) {
+          index = ownProps[ownIndex];
+          if (typeof result[index] == 'undefined') result[index] = iterable[index];
+        }
+        }
+      }
+      return result
+    };
+
+    /**
+     * This method is like `_.findIndex` except that it returns the key of the
+     * first element that passes the callback check, instead of the element itself.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to search.
+     * @param {Function|Object|string} [callback=identity] The function called per
+     *  iteration. If a property name or object is provided it will be used to
+     *  create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {string|undefined} Returns the key of the found element, else `undefined`.
+     * @example
+     *
+     * _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
+     *   return num % 2 == 0;
+     * });
+     * // => 'b' (property order is not guaranteed across environments)
+     */
+    function findKey(object, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forOwn(object, function(value, key, object) {
+        if (callback(value, key, object)) {
+          result = key;
+          return false;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * This method is like `_.findKey` except that it iterates over elements
+     * of a `collection` in the opposite order.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to search.
+     * @param {Function|Object|string} [callback=identity] The function called per
+     *  iteration. If a property name or object is provided it will be used to
+     *  create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {string|undefined} Returns the key of the found element, else `undefined`.
+     * @example
+     *
+     * _.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
+     *   return num % 2 == 1;
+     * });
+     * // => returns `c`, assuming `_.findKey` returns `a`
+     */
+    function findLastKey(object, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forOwnRight(object, function(value, key, object) {
+        if (callback(value, key, object)) {
+          result = key;
+          return false;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * Iterates over own and inherited enumerable properties of an object,
+     * executing the callback for each property. The callback is bound to `thisArg`
+     * and invoked with three arguments; (value, key, object). Callbacks may exit
+     * iteration early by explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * function Dog(name) {
+     *   this.name = name;
+     * }
+     *
+     * Dog.prototype.bark = function() {
+     *   console.log('Woof, woof!');
+     * };
+     *
+     * _.forIn(new Dog('Dagny'), function(value, key) {
+     *   console.log(key);
+     * });
+     * // => logs 'bark' and 'name' (property order is not guaranteed across environments)
+     */
+    var forIn = function(collection, callback, thisArg) {
+      var index, iterable = collection, result = iterable;
+      if (!iterable) return result;
+      if (!objectTypes[typeof iterable]) return result;
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+        for (index in iterable) {
+          if (callback(iterable[index], index, collection) === false) return result;
+        }
+      return result
+    };
+
+    /**
+     * This method is like `_.forIn` except that it iterates over elements
+     * of a `collection` in the opposite order.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * function Dog(name) {
+     *   this.name = name;
+     * }
+     *
+     * Dog.prototype.bark = function() {
+     *   console.log('Woof, woof!');
+     * };
+     *
+     * _.forInRight(new Dog('Dagny'), function(value, key) {
+     *   console.log(key);
+     * });
+     * // => logs 'name' and 'bark' assuming `_.forIn ` logs 'bark' and 'name'
+     */
+    function forInRight(object, callback, thisArg) {
+      var pairs = [];
+
+      forIn(object, function(value, key) {
+        pairs.push(key, value);
+      });
+
+      var length = pairs.length;
+      callback = baseCreateCallback(callback, thisArg, 3);
+      while (length--) {
+        if (callback(pairs[length--], pairs[length], object) === false) {
+          break;
+        }
+      }
+      return object;
+    }
+
+    /**
+     * Iterates over own enumerable properties of an object, executing the callback
+     * for each property. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, key, object). Callbacks may exit iteration early by
+     * explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
+     *   console.log(key);
+     * });
+     * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
+     */
+    var forOwn = function(collection, callback, thisArg) {
+      var index, iterable = collection, result = iterable;
+      if (!iterable) return result;
+      if (!objectTypes[typeof iterable]) return result;
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+        var ownIndex = -1,
+            ownProps = objectTypes[typeof iterable] && keys(iterable),
+            length = ownProps ? ownProps.length : 0;
+
+        while (++ownIndex < length) {
+          index = ownProps[ownIndex];
+          if (callback(iterable[index], index, collection) === false) return result;
+        }
+      return result
+    };
+
+    /**
+     * This method is like `_.forOwn` except that it iterates over elements
+     * of a `collection` in the opposite order.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
+     *   console.log(key);
+     * });
+     * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
+     */
+    function forOwnRight(object, callback, thisArg) {
+      var props = keys(object),
+          length = props.length;
+
+      callback = baseCreateCallback(callback, thisArg, 3);
+      while (length--) {
+        var key = props[length];
+        if (callback(object[key], key, object) === false) {
+          break;
+        }
+      }
+      return object;
+    }
+
+    /**
+     * Creates a sorted array of property names of all enumerable properties,
+     * own and inherited, of `object` that have function values.
+     *
+     * @static
+     * @memberOf _
+     * @alias methods
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property names that have function values.
+     * @example
+     *
+     * _.functions(_);
+     * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
+     */
+    function functions(object) {
+      var result = [];
+      forIn(object, function(value, key) {
+        if (isFunction(value)) {
+          result.push(key);
+        }
+      });
+      return result.sort();
+    }
+
+    /**
+     * Checks if the specified object `property` exists and is a direct property,
+     * instead of an inherited property.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to check.
+     * @param {string} property The property to check for.
+     * @returns {boolean} Returns `true` if key is a direct property, else `false`.
+     * @example
+     *
+     * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
+     * // => true
+     */
+    function has(object, property) {
+      return object ? hasOwnProperty.call(object, property) : false;
+    }
+
+    /**
+     * Creates an object composed of the inverted keys and values of the given object.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to invert.
+     * @returns {Object} Returns the created inverted object.
+     * @example
+     *
+     *  _.invert({ 'first': 'moe', 'second': 'larry' });
+     * // => { 'moe': 'first', 'larry': 'second' }
+     */
+    function invert(object) {
+      var index = -1,
+          props = keys(object),
+          length = props.length,
+          result = {};
+
+      while (++index < length) {
+        var key = props[index];
+        result[object[key]] = key;
+      }
+      return result;
+    }
+
+    /**
+     * Checks if `value` is a boolean value.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
+     * @example
+     *
+     * _.isBoolean(null);
+     * // => false
+     */
+    function isBoolean(value) {
+      return value === true || value === false || toString.call(value) == boolClass;
+    }
+
+    /**
+     * Checks if `value` is a date.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a date, else `false`.
+     * @example
+     *
+     * _.isDate(new Date);
+     * // => true
+     */
+    function isDate(value) {
+      return value ? (typeof value == 'object' && toString.call(value) == dateClass) : false;
+    }
+
+    /**
+     * Checks if `value` is a DOM element.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
+     * @example
+     *
+     * _.isElement(document.body);
+     * // => true
+     */
+    function isElement(value) {
+      return value ? value.nodeType === 1 : false;
+    }
+
+    /**
+     * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
+     * length of `0` and objects with no own enumerable properties are considered
+     * "empty".
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Array|Object|string} value The value to inspect.
+     * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
+     * @example
+     *
+     * _.isEmpty([1, 2, 3]);
+     * // => false
+     *
+     * _.isEmpty({});
+     * // => true
+     *
+     * _.isEmpty('');
+     * // => true
+     */
+    function isEmpty(value) {
+      var result = true;
+      if (!value) {
+        return result;
+      }
+      var className = toString.call(value),
+          length = value.length;
+
+      if ((className == arrayClass || className == stringClass || className == argsClass ) ||
+          (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
+        return !length;
+      }
+      forOwn(value, function() {
+        return (result = false);
+      });
+      return result;
+    }
+
+    /**
+     * Performs a deep comparison between two values to determine if they are
+     * equivalent to each other. If a callback is provided it will be executed
+     * to compare values. If the callback returns `undefined` comparisons will
+     * be handled by the method instead. The callback is bound to `thisArg` and
+     * invoked with two arguments; (a, b).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} a The value to compare.
+     * @param {*} b The other value to compare.
+     * @param {Function} [callback] The function to customize comparing values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+     * @example
+     *
+     * var moe = { 'name': 'moe', 'age': 40 };
+     * var copy = { 'name': 'moe', 'age': 40 };
+     *
+     * moe == copy;
+     * // => false
+     *
+     * _.isEqual(moe, copy);
+     * // => true
+     *
+     * var words = ['hello', 'goodbye'];
+     * var otherWords = ['hi', 'goodbye'];
+     *
+     * _.isEqual(words, otherWords, function(a, b) {
+     *   var reGreet = /^(?:hello|hi)$/i,
+     *       aGreet = _.isString(a) && reGreet.test(a),
+     *       bGreet = _.isString(b) && reGreet.test(b);
+     *
+     *   return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
+     * });
+     * // => true
+     */
+    function isEqual(a, b, callback, thisArg) {
+      return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
+    }
+
+    /**
+     * Checks if `value` is, or can be coerced to, a finite number.
+     *
+     * Note: This is not the same as native `isFinite` which will return true for
+     * booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is finite, else `false`.
+     * @example
+     *
+     * _.isFinite(-101);
+     * // => true
+     *
+     * _.isFinite('10');
+     * // => true
+     *
+     * _.isFinite(true);
+     * // => false
+     *
+     * _.isFinite('');
+     * // => false
+     *
+     * _.isFinite(Infinity);
+     * // => false
+     */
+    function isFinite(value) {
+      return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
+    }
+
+    /**
+     * Checks if `value` is a function.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
+     * @example
+     *
+     * _.isFunction(_);
+     * // => true
+     */
+    function isFunction(value) {
+      return typeof value == 'function';
+    }
+
+    /**
+     * Checks if `value` is the language type of Object.
+     * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
+     * @example
+     *
+     * _.isObject({});
+     * // => true
+     *
+     * _.isObject([1, 2, 3]);
+     * // => true
+     *
+     * _.isObject(1);
+     * // => false
+     */
+    function isObject(value) {
+      // check if the value is the ECMAScript language type of Object
+      // http://es5.github.io/#x8
+      // and avoid a V8 bug
+      // http://code.google.com/p/v8/issues/detail?id=2291
+      return !!(value && objectTypes[typeof value]);
+    }
+
+    /**
+     * Checks if `value` is `NaN`.
+     *
+     * Note: This is not the same as native `isNaN` which will return `true` for
+     * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
+     * @example
+     *
+     * _.isNaN(NaN);
+     * // => true
+     *
+     * _.isNaN(new Number(NaN));
+     * // => true
+     *
+     * isNaN(undefined);
+     * // => true
+     *
+     * _.isNaN(undefined);
+     * // => false
+     */
+    function isNaN(value) {
+      // `NaN` as a primitive is the only value that is not equal to itself
+      // (perform the [[Class]] check first to avoid errors with some host objects in IE)
+      return isNumber(value) && value != +value;
+    }
+
+    /**
+     * Checks if `value` is `null`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
+     * @example
+     *
+     * _.isNull(null);
+     * // => true
+     *
+     * _.isNull(undefined);
+     * // => false
+     */
+    function isNull(value) {
+      return value === null;
+    }
+
+    /**
+     * Checks if `value` is a number.
+     *
+     * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a number, else `false`.
+     * @example
+     *
+     * _.isNumber(8.4 * 5);
+     * // => true
+     */
+    function isNumber(value) {
+      return typeof value == 'number' || toString.call(value) == numberClass;
+    }
+
+    /**
+     * Checks if `value` is an object created by the `Object` constructor.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
+     * @example
+     *
+     * function Stooge(name, age) {
+     *   this.name = name;
+     *   this.age = age;
+     * }
+     *
+     * _.isPlainObject(new Stooge('moe', 40));
+     * // => false
+     *
+     * _.isPlainObject([1, 2, 3]);
+     * // => false
+     *
+     * _.isPlainObject({ 'name': 'moe', 'age': 40 });
+     * // => true
+     */
+    var isPlainObject = function(value) {
+      if (!(value && toString.call(value) == objectClass)) {
+        return false;
+      }
+      var valueOf = value.valueOf,
+          objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
+
+      return objProto
+        ? (value == objProto || getPrototypeOf(value) == objProto)
+        : shimIsPlainObject(value);
+    };
+
+    /**
+     * Checks if `value` is a regular expression.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
+     * @example
+     *
+     * _.isRegExp(/moe/);
+     * // => true
+     */
+    function isRegExp(value) {
+      return value ? (typeof value == 'object' && toString.call(value) == regexpClass) : false;
+    }
+
+    /**
+     * Checks if `value` is a string.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a string, else `false`.
+     * @example
+     *
+     * _.isString('moe');
+     * // => true
+     */
+    function isString(value) {
+      return typeof value == 'string' || toString.call(value) == stringClass;
+    }
+
+    /**
+     * Checks if `value` is `undefined`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
+     * @example
+     *
+     * _.isUndefined(void 0);
+     * // => true
+     */
+    function isUndefined(value) {
+      return typeof value == 'undefined';
+    }
+
+    /**
+     * Recursively merges own enumerable properties of the source object(s), that
+     * don't resolve to `undefined` into the destination object. Subsequent sources
+     * will overwrite property assignments of previous sources. If a callback is
+     * provided it will be executed to produce the merged values of the destination
+     * and source properties. If the callback returns `undefined` merging will
+     * be handled by the method instead. The callback is bound to `thisArg` and
+     * invoked with two arguments; (objectValue, sourceValue).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The destination object.
+     * @param {...Object} [source] The source objects.
+     * @param {Function} [callback] The function to customize merging properties.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the destination object.
+     * @example
+     *
+     * var names = {
+     *   'stooges': [
+     *     { 'name': 'moe' },
+     *     { 'name': 'larry' }
+     *   ]
+     * };
+     *
+     * var ages = {
+     *   'stooges': [
+     *     { 'age': 40 },
+     *     { 'age': 50 }
+     *   ]
+     * };
+     *
+     * _.merge(names, ages);
+     * // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] }
+     *
+     * var food = {
+     *   'fruits': ['apple'],
+     *   'vegetables': ['beet']
+     * };
+     *
+     * var otherFood = {
+     *   'fruits': ['banana'],
+     *   'vegetables': ['carrot']
+     * };
+     *
+     * _.merge(food, otherFood, function(a, b) {
+     *   return _.isArray(a) ? a.concat(b) : undefined;
+     * });
+     * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
+     */
+    function merge(object) {
+      var args = arguments,
+          length = 2;
+
+      if (!isObject(object)) {
+        return object;
+      }
+      // allows working with `_.reduce` and `_.reduceRight` without using
+      // their `index` and `collection` arguments
+      if (typeof args[2] != 'number') {
+        length = args.length;
+      }
+      if (length > 3 && typeof args[length - 2] == 'function') {
+        var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
+      } else if (length > 2 && typeof args[length - 1] == 'function') {
+        callback = args[--length];
+      }
+      var sources = nativeSlice.call(arguments, 1, length),
+          index = -1,
+          stackA = getArray(),
+          stackB = getArray();
+
+      while (++index < length) {
+        baseMerge(object, sources[index], callback, stackA, stackB);
+      }
+      releaseArray(stackA);
+      releaseArray(stackB);
+      return object;
+    }
+
+    /**
+     * Creates a shallow clone of `object` excluding the specified properties.
+     * Property names may be specified as individual arguments or as arrays of
+     * property names. If a callback is provided it will be executed for each
+     * property of `object` omitting the properties the callback returns truey
+     * for. The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, key, object).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The source object.
+     * @param {Function|...string|string[]} [callback] The properties to omit or the
+     *  function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns an object without the omitted properties.
+     * @example
+     *
+     * _.omit({ 'name': 'moe', 'age': 40 }, 'age');
+     * // => { 'name': 'moe' }
+     *
+     * _.omit({ 'name': 'moe', 'age': 40 }, function(value) {
+     *   return typeof value == 'number';
+     * });
+     * // => { 'name': 'moe' }
+     */
+    function omit(object, callback, thisArg) {
+      var indexOf = getIndexOf(),
+          isFunc = typeof callback == 'function',
+          result = {};
+
+      if (isFunc) {
+        callback = lodash.createCallback(callback, thisArg, 3);
+      } else {
+        var props = baseFlatten(arguments, true, false, 1);
+      }
+      forIn(object, function(value, key, object) {
+        if (isFunc
+              ? !callback(value, key, object)
+              : indexOf(props, key) < 0
+            ) {
+          result[key] = value;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * Creates a two dimensional array of an object's key-value pairs,
+     * i.e. `[[key1, value1], [key2, value2]]`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns new array of key-value pairs.
+     * @example
+     *
+     * _.pairs({ 'moe': 30, 'larry': 40 });
+     * // => [['moe', 30], ['larry', 40]] (property order is not guaranteed across environments)
+     */
+    function pairs(object) {
+      var index = -1,
+          props = keys(object),
+          length = props.length,
+          result = Array(length);
+
+      while (++index < length) {
+        var key = props[index];
+        result[index] = [key, object[key]];
+      }
+      return result;
+    }
+
+    /**
+     * Creates a shallow clone of `object` composed of the specified properties.
+     * Property names may be specified as individual arguments or as arrays of
+     * property names. If a callback is provided it will be executed for each
+     * property of `object` picking the properties the callback returns truey
+     * for. The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, key, object).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The source object.
+     * @param {Function|...string|string[]} [callback] The function called per
+     *  iteration or property names to pick, specified as individual property
+     *  names or arrays of property names.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns an object composed of the picked properties.
+     * @example
+     *
+     * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
+     * // => { 'name': 'moe' }
+     *
+     * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
+     *   return key.charAt(0) != '_';
+     * });
+     * // => { 'name': 'moe' }
+     */
+    function pick(object, callback, thisArg) {
+      var result = {};
+      if (typeof callback != 'function') {
+        var index = -1,
+            props = baseFlatten(arguments, true, false, 1),
+            length = isObject(object) ? props.length : 0;
+
+        while (++index < length) {
+          var key = props[index];
+          if (key in object) {
+            result[key] = object[key];
+          }
+        }
+      } else {
+        callback = lodash.createCallback(callback, thisArg, 3);
+        forIn(object, function(value, key, object) {
+          if (callback(value, key, object)) {
+            result[key] = value;
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * An alternative to `_.reduce` this method transforms `object` to a new
+     * `accumulator` object which is the result of running each of its elements
+     * through a callback, with each callback execution potentially mutating
+     * the `accumulator` object. The callback is bound to `thisArg` and invoked
+     * with four arguments; (accumulator, value, key, object). Callbacks may exit
+     * iteration early by explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Array|Object} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [accumulator] The custom accumulator value.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the accumulated value.
+     * @example
+     *
+     * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
+     *   num *= num;
+     *   if (num % 2) {
+     *     return result.push(num) < 3;
+     *   }
+     * });
+     * // => [1, 9, 25]
+     *
+     * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
+     *   result[key] = num * 3;
+     * });
+     * // => { 'a': 3, 'b': 6, 'c': 9 }
+     */
+    function transform(object, callback, accumulator, thisArg) {
+      var isArr = isArray(object);
+      callback = baseCreateCallback(callback, thisArg, 4);
+
+      if (accumulator == null) {
+        if (isArr) {
+          accumulator = [];
+        } else {
+          var ctor = object && object.constructor,
+              proto = ctor && ctor.prototype;
+
+          accumulator = createObject(proto);
+        }
+      }
+      (isArr ? forEach : forOwn)(object, function(value, index, object) {
+        return callback(accumulator, value, index, object);
+      });
+      return accumulator;
+    }
+
+    /**
+     * Creates an array composed of the own enumerable property values of `object`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property values.
+     * @example
+     *
+     * _.values({ 'one': 1, 'two': 2, 'three': 3 });
+     * // => [1, 2, 3] (property order is not guaranteed across environments)
+     */
+    function values(object) {
+      var index = -1,
+          props = keys(object),
+          length = props.length,
+          result = Array(length);
+
+      while (++index < length) {
+        result[index] = object[props[index]];
+      }
+      return result;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates an array of elements from the specified indexes, or keys, of the
+     * `collection`. Indexes may be specified as individual arguments or as arrays
+     * of indexes.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
+     *   to retrieve, specified as individual indexes or arrays of indexes.
+     * @returns {Array} Returns a new array of elements corresponding to the
+     *  provided indexes.
+     * @example
+     *
+     * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
+     * // => ['a', 'c', 'e']
+     *
+     * _.at(['moe', 'larry', 'curly'], 0, 2);
+     * // => ['moe', 'curly']
+     */
+    function at(collection) {
+      var args = arguments,
+          index = -1,
+          props = baseFlatten(args, true, false, 1),
+          length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
+          result = Array(length);
+
+      while(++index < length) {
+        result[index] = collection[props[index]];
+      }
+      return result;
+    }
+
+    /**
+     * Checks if a given value is present in a collection using strict equality
+     * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
+     * offset from the end of the collection.
+     *
+     * @static
+     * @memberOf _
+     * @alias include
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {*} target The value to check for.
+     * @param {number} [fromIndex=0] The index to search from.
+     * @returns {boolean} Returns `true` if the `target` element is found, else `false`.
+     * @example
+     *
+     * _.contains([1, 2, 3], 1);
+     * // => true
+     *
+     * _.contains([1, 2, 3], 1, 2);
+     * // => false
+     *
+     * _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
+     * // => true
+     *
+     * _.contains('curly', 'ur');
+     * // => true
+     */
+    function contains(collection, target, fromIndex) {
+      var index = -1,
+          indexOf = getIndexOf(),
+          length = collection ? collection.length : 0,
+          result = false;
+
+      fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
+      if (isArray(collection)) {
+        result = indexOf(collection, target, fromIndex) > -1;
+      } else if (typeof length == 'number') {
+        result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
+      } else {
+        forOwn(collection, function(value) {
+          if (++index >= fromIndex) {
+            return !(result = value === target);
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Creates an object composed of keys generated from the results of running
+     * each element of `collection` through the callback. The corresponding value
+     * of each key is the number of times the key was returned by the callback.
+     * The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the composed aggregate object.
+     * @example
+     *
+     * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
+     * // => { '4': 1, '6': 2 }
+     *
+     * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
+     * // => { '4': 1, '6': 2 }
+     *
+     * _.countBy(['one', 'two', 'three'], 'length');
+     * // => { '3': 2, '5': 1 }
+     */
+    var countBy = createAggregator(function(result, value, key) {
+      (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
+    });
+
+    /**
+     * Checks if the given callback returns truey value for **all** elements of
+     * a collection. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias all
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {boolean} Returns `true` if all elements passed the callback check,
+     *  else `false`.
+     * @example
+     *
+     * _.every([true, 1, null, 'yes'], Boolean);
+     * // => false
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.every(stooges, 'age');
+     * // => true
+     *
+     * // using "_.where" callback shorthand
+     * _.every(stooges, { 'age': 50 });
+     * // => false
+     */
+    function every(collection, callback, thisArg) {
+      var result = true;
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          if (!(result = !!callback(collection[index], index, collection))) {
+            break;
+          }
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          return (result = !!callback(value, index, collection));
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Iterates over elements of a collection, returning an array of all elements
+     * the callback returns truey for. The callback is bound to `thisArg` and
+     * invoked with three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias select
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of elements that passed the callback check.
+     * @example
+     *
+     * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
+     * // => [2, 4, 6]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.filter(food, 'organic');
+     * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
+     *
+     * // using "_.where" callback shorthand
+     * _.filter(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
+     */
+    function filter(collection, callback, thisArg) {
+      var result = [];
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          var value = collection[index];
+          if (callback(value, index, collection)) {
+            result.push(value);
+          }
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          if (callback(value, index, collection)) {
+            result.push(value);
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Iterates over elements of a collection, returning the first element that
+     * the callback returns truey for. The callback is bound to `thisArg` and
+     * invoked with three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias detect, findWhere
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the found element, else `undefined`.
+     * @example
+     *
+     * _.find([1, 2, 3, 4], function(num) {
+     *   return num % 2 == 0;
+     * });
+     * // => 2
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'banana', 'organic': true,  'type': 'fruit' },
+     *   { 'name': 'beet',   'organic': false, 'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.find(food, { 'type': 'vegetable' });
+     * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
+     *
+     * // using "_.pluck" callback shorthand
+     * _.find(food, 'organic');
+     * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' }
+     */
+    function find(collection, callback, thisArg) {
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          var value = collection[index];
+          if (callback(value, index, collection)) {
+            return value;
+          }
+        }
+      } else {
+        var result;
+        forOwn(collection, function(value, index, collection) {
+          if (callback(value, index, collection)) {
+            result = value;
+            return false;
+          }
+        });
+        return result;
+      }
+    }
+
+    /**
+     * This method is like `_.find` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the found element, else `undefined`.
+     * @example
+     *
+     * _.findLast([1, 2, 3, 4], function(num) {
+     *   return num % 2 == 1;
+     * });
+     * // => 3
+     */
+    function findLast(collection, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forEachRight(collection, function(value, index, collection) {
+        if (callback(value, index, collection)) {
+          result = value;
+          return false;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * Iterates over elements of a collection, executing the callback for each
+     * element. The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection). Callbacks may exit iteration early by
+     * explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias each
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array|Object|string} Returns `collection`.
+     * @example
+     *
+     * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
+     * // => logs each number and returns '1,2,3'
+     *
+     * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
+     * // => logs each number and returns the object (property order is not guaranteed across environments)
+     */
+    function forEach(collection, callback, thisArg) {
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+      if (typeof length == 'number') {
+        while (++index < length) {
+          if (callback(collection[index], index, collection) === false) {
+            break;
+          }
+        }
+      } else {
+        forOwn(collection, callback);
+      }
+      return collection;
+    }
+
+    /**
+     * This method is like `_.forEach` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @alias eachRight
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array|Object|string} Returns `collection`.
+     * @example
+     *
+     * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
+     * // => logs each number from right to left and returns '3,2,1'
+     */
+    function forEachRight(collection, callback, thisArg) {
+      var length = collection ? collection.length : 0;
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+      if (typeof length == 'number') {
+        while (length--) {
+          if (callback(collection[length], length, collection) === false) {
+            break;
+          }
+        }
+      } else {
+        var props = keys(collection);
+        length = props.length;
+        forOwn(collection, function(value, key, collection) {
+          key = props ? props[--length] : --length;
+          return callback(collection[key], key, collection);
+        });
+      }
+      return collection;
+    }
+
+    /**
+     * Creates an object composed of keys generated from the results of running
+     * each element of a collection through the callback. The corresponding value
+     * of each key is an array of the elements responsible for generating the key.
+     * The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the composed aggregate object.
+     * @example
+     *
+     * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
+     * // => { '4': [4.2], '6': [6.1, 6.4] }
+     *
+     * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
+     * // => { '4': [4.2], '6': [6.1, 6.4] }
+     *
+     * // using "_.pluck" callback shorthand
+     * _.groupBy(['one', 'two', 'three'], 'length');
+     * // => { '3': ['one', 'two'], '5': ['three'] }
+     */
+    var groupBy = createAggregator(function(result, value, key) {
+      (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
+    });
+
+    /**
+     * Creates an object composed of keys generated from the results of running
+     * each element of the collection through the given callback. The corresponding
+     * value of each key is the last element responsible for generating the key.
+     * The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the composed aggregate object.
+     * @example
+     *
+     * var keys = [
+     *   { 'dir': 'left', 'code': 97 },
+     *   { 'dir': 'right', 'code': 100 }
+     * ];
+     *
+     * _.indexBy(keys, 'dir');
+     * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
+     *
+     * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
+     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
+     *
+     * _.indexBy(stooges, function(key) { this.fromCharCode(key.code); }, String);
+     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
+     */
+    var indexBy = createAggregator(function(result, value, key) {
+      result[key] = value;
+    });
+
+    /**
+     * Invokes the method named by `methodName` on each element in the `collection`
+     * returning an array of the results of each invoked method. Additional arguments
+     * will be provided to each invoked method. If `methodName` is a function it
+     * will be invoked for, and `this` bound to, each element in the `collection`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|string} methodName The name of the method to invoke or
+     *  the function invoked per iteration.
+     * @param {...*} [arg] Arguments to invoke the method with.
+     * @returns {Array} Returns a new array of the results of each invoked method.
+     * @example
+     *
+     * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
+     * // => [[1, 5, 7], [1, 2, 3]]
+     *
+     * _.invoke([123, 456], String.prototype.split, '');
+     * // => [['1', '2', '3'], ['4', '5', '6']]
+     */
+    function invoke(collection, methodName) {
+      var args = nativeSlice.call(arguments, 2),
+          index = -1,
+          isFunc = typeof methodName == 'function',
+          length = collection ? collection.length : 0,
+          result = Array(typeof length == 'number' ? length : 0);
+
+      forEach(collection, function(value) {
+        result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
+      });
+      return result;
+    }
+
+    /**
+     * Creates an array of values by running each element in the collection
+     * through the callback. The callback is bound to `thisArg` and invoked with
+     * three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias collect
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of the results of each `callback` execution.
+     * @example
+     *
+     * _.map([1, 2, 3], function(num) { return num * 3; });
+     * // => [3, 6, 9]
+     *
+     * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
+     * // => [3, 6, 9] (property order is not guaranteed across environments)
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.map(stooges, 'name');
+     * // => ['moe', 'larry']
+     */
+    function map(collection, callback, thisArg) {
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      if (typeof length == 'number') {
+        var result = Array(length);
+        while (++index < length) {
+          result[index] = callback(collection[index], index, collection);
+        }
+      } else {
+        result = [];
+        forOwn(collection, function(value, key, collection) {
+          result[++index] = callback(value, key, collection);
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Retrieves the maximum value of a collection. If the collection is empty or
+     * falsey `-Infinity` is returned. If a callback is provided it will be executed
+     * for each value in the collection to generate the criterion by which the value
+     * is ranked. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the maximum value.
+     * @example
+     *
+     * _.max([4, 2, 8, 6]);
+     * // => 8
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * _.max(stooges, function(stooge) { return stooge.age; });
+     * // => { 'name': 'larry', 'age': 50 };
+     *
+     * // using "_.pluck" callback shorthand
+     * _.max(stooges, 'age');
+     * // => { 'name': 'larry', 'age': 50 };
+     */
+    function max(collection, callback, thisArg) {
+      var computed = -Infinity,
+          result = computed;
+
+      if (!callback && isArray(collection)) {
+        var index = -1,
+            length = collection.length;
+
+        while (++index < length) {
+          var value = collection[index];
+          if (value > result) {
+            result = value;
+          }
+        }
+      } else {
+        callback = (!callback && isString(collection))
+          ? charAtCallback
+          : lodash.createCallback(callback, thisArg, 3);
+
+        forEach(collection, function(value, index, collection) {
+          var current = callback(value, index, collection);
+          if (current > computed) {
+            computed = current;
+            result = value;
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Retrieves the minimum value of a collection. If the collection is empty or
+     * falsey `Infinity` is returned. If a callback is provided it will be executed
+     * for each value in the collection to generate the criterion by which the value
+     * is ranked. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the minimum value.
+     * @example
+     *
+     * _.min([4, 2, 8, 6]);
+     * // => 2
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * _.min(stooges, function(stooge) { return stooge.age; });
+     * // => { 'name': 'moe', 'age': 40 };
+     *
+     * // using "_.pluck" callback shorthand
+     * _.min(stooges, 'age');
+     * // => { 'name': 'moe', 'age': 40 };
+     */
+    function min(collection, callback, thisArg) {
+      var computed = Infinity,
+          result = computed;
+
+      if (!callback && isArray(collection)) {
+        var index = -1,
+            length = collection.length;
+
+        while (++index < length) {
+          var value = collection[index];
+          if (value < result) {
+            result = value;
+          }
+        }
+      } else {
+        callback = (!callback && isString(collection))
+          ? charAtCallback
+          : lodash.createCallback(callback, thisArg, 3);
+
+        forEach(collection, function(value, index, collection) {
+          var current = callback(value, index, collection);
+          if (current < computed) {
+            computed = current;
+            result = value;
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Retrieves the value of a specified property from all elements in the `collection`.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {string} property The property to pluck.
+     * @returns {Array} Returns a new array of property values.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * _.pluck(stooges, 'name');
+     * // => ['moe', 'larry']
+     */
+    function pluck(collection, property) {
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        var result = Array(length);
+        while (++index < length) {
+          result[index] = collection[index][property];
+        }
+      }
+      return result || map(collection, property);
+    }
+
+    /**
+     * Reduces a collection to a value which is the accumulated result of running
+     * each element in the collection through the callback, where each successive
+     * callback execution consumes the return value of the previous execution. If
+     * `accumulator` is not provided the first element of the collection will be
+     * used as the initial `accumulator` value. The callback is bound to `thisArg`
+     * and invoked with four arguments; (accumulator, value, index|key, collection).
+     *
+     * @static
+     * @memberOf _
+     * @alias foldl, inject
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [accumulator] Initial value of the accumulator.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the accumulated value.
+     * @example
+     *
+     * var sum = _.reduce([1, 2, 3], function(sum, num) {
+     *   return sum + num;
+     * });
+     * // => 6
+     *
+     * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
+     *   result[key] = num * 3;
+     *   return result;
+     * }, {});
+     * // => { 'a': 3, 'b': 6, 'c': 9 }
+     */
+    function reduce(collection, callback, accumulator, thisArg) {
+      if (!collection) return accumulator;
+      var noaccum = arguments.length < 3;
+      callback = baseCreateCallback(callback, thisArg, 4);
+
+      var index = -1,
+          length = collection.length;
+
+      if (typeof length == 'number') {
+        if (noaccum) {
+          accumulator = collection[++index];
+        }
+        while (++index < length) {
+          accumulator = callback(accumulator, collection[index], index, collection);
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          accumulator = noaccum
+            ? (noaccum = false, value)
+            : callback(accumulator, value, index, collection)
+        });
+      }
+      return accumulator;
+    }
+
+    /**
+     * This method is like `_.reduce` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @alias foldr
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [accumulator] Initial value of the accumulator.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the accumulated value.
+     * @example
+     *
+     * var list = [[0, 1], [2, 3], [4, 5]];
+     * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
+     * // => [4, 5, 2, 3, 0, 1]
+     */
+    function reduceRight(collection, callback, accumulator, thisArg) {
+      var noaccum = arguments.length < 3;
+      callback = baseCreateCallback(callback, thisArg, 4);
+      forEachRight(collection, function(value, index, collection) {
+        accumulator = noaccum
+          ? (noaccum = false, value)
+          : callback(accumulator, value, index, collection);
+      });
+      return accumulator;
+    }
+
+    /**
+     * The opposite of `_.filter` this method returns the elements of a
+     * collection that the callback does **not** return truey for.
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of elements that failed the callback check.
+     * @example
+     *
+     * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
+     * // => [1, 3, 5]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.reject(food, 'organic');
+     * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
+     *
+     * // using "_.where" callback shorthand
+     * _.reject(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
+     */
+    function reject(collection, callback, thisArg) {
+      callback = lodash.createCallback(callback, thisArg, 3);
+      return filter(collection, function(value, index, collection) {
+        return !callback(value, index, collection);
+      });
+    }
+
+    /**
+     * Retrieves a random element or `n` random elements from a collection.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to sample.
+     * @param {number} [n] The number of elements to sample.
+     * @param- {Object} [guard] Allows working with functions, like `_.map`,
+     *  without using their `key` and `object` arguments as sources.
+     * @returns {Array} Returns the random sample(s) of `collection`.
+     * @example
+     *
+     * _.sample([1, 2, 3, 4]);
+     * // => 2
+     *
+     * _.sample([1, 2, 3, 4], 2);
+     * // => [3, 1]
+     */
+    function sample(collection, n, guard) {
+      var length = collection ? collection.length : 0;
+      if (typeof length != 'number') {
+        collection = values(collection);
+      }
+      if (n == null || guard) {
+        return collection ? collection[random(length - 1)] : undefined;
+      }
+      var result = shuffle(collection);
+      result.length = nativeMin(nativeMax(0, n), result.length);
+      return result;
+    }
+
+    /**
+     * Creates an array of shuffled values, using a version of the Fisher-Yates
+     * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to shuffle.
+     * @returns {Array} Returns a new shuffled collection.
+     * @example
+     *
+     * _.shuffle([1, 2, 3, 4, 5, 6]);
+     * // => [4, 1, 6, 3, 5, 2]
+     */
+    function shuffle(collection) {
+      var index = -1,
+          length = collection ? collection.length : 0,
+          result = Array(typeof length == 'number' ? length : 0);
+
+      forEach(collection, function(value) {
+        var rand = random(++index);
+        result[index] = result[rand];
+        result[rand] = value;
+      });
+      return result;
+    }
+
+    /**
+     * Gets the size of the `collection` by returning `collection.length` for arrays
+     * and array-like objects or the number of own enumerable properties for objects.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to inspect.
+     * @returns {number} Returns `collection.length` or number of own enumerable properties.
+     * @example
+     *
+     * _.size([1, 2]);
+     * // => 2
+     *
+     * _.size({ 'one': 1, 'two': 2, 'three': 3 });
+     * // => 3
+     *
+     * _.size('curly');
+     * // => 5
+     */
+    function size(collection) {
+      var length = collection ? collection.length : 0;
+      return typeof length == 'number' ? length : keys(collection).length;
+    }
+
+    /**
+     * Checks if the callback returns a truey value for **any** element of a
+     * collection. The function returns as soon as it finds a passing value and
+     * does not iterate over the entire collection. The callback is bound to
+     * `thisArg` and invoked with three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias any
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {boolean} Returns `true` if any element passed the callback check,
+     *  else `false`.
+     * @example
+     *
+     * _.some([null, 0, 'yes', false], Boolean);
+     * // => true
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.some(food, 'organic');
+     * // => true
+     *
+     * // using "_.where" callback shorthand
+     * _.some(food, { 'type': 'meat' });
+     * // => false
+     */
+    function some(collection, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          if ((result = callback(collection[index], index, collection))) {
+            break;
+          }
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          return !(result = callback(value, index, collection));
+        });
+      }
+      return !!result;
+    }
+
+    /**
+     * Creates an array of elements, sorted in ascending order by the results of
+     * running each element in a collection through the callback. This method
+     * performs a stable sort, that is, it will preserve the original sort order
+     * of equal elements. The callback is bound to `thisArg` and invoked with
+     * three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of sorted elements.
+     * @example
+     *
+     * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
+     * // => [3, 1, 2]
+     *
+     * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
+     * // => [3, 1, 2]
+     *
+     * // using "_.pluck" callback shorthand
+     * _.sortBy(['banana', 'strawberry', 'apple'], 'length');
+     * // => ['apple', 'banana', 'strawberry']
+     */
+    function sortBy(collection, callback, thisArg) {
+      var index = -1,
+          length = collection ? collection.length : 0,
+          result = Array(typeof length == 'number' ? length : 0);
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forEach(collection, function(value, key, collection) {
+        var object = result[++index] = getObject();
+        object.criteria = callback(value, key, collection);
+        object.index = index;
+        object.value = value;
+      });
+
+      length = result.length;
+      result.sort(compareAscending);
+      while (length--) {
+        var object = result[length];
+        result[length] = object.value;
+        releaseObject(object);
+      }
+      return result;
+    }
+
+    /**
+     * Converts the `collection` to an array.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to convert.
+     * @returns {Array} Returns the new converted array.
+     * @example
+     *
+     * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
+     * // => [2, 3, 4]
+     */
+    function toArray(collection) {
+      if (collection && typeof collection.length == 'number') {
+        return slice(collection);
+      }
+      return values(collection);
+    }
+
+    /**
+     * Performs a deep comparison of each element in a `collection` to the given
+     * `properties` object, returning an array of all elements that have equivalent
+     * property values.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Object} properties The object of property values to filter by.
+     * @returns {Array} Returns a new array of elements that have the given properties.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
+     *   { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }
+     * ];
+     *
+     * _.where(stooges, { 'age': 40 });
+     * // => [{ 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }]
+     *
+     * _.where(stooges, { 'quotes': ['Poifect!'] });
+     * // => [{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }]
+     */
+    var where = filter;
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates an array with all falsey values removed. The values `false`, `null`,
+     * `0`, `""`, `undefined`, and `NaN` are all falsey.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to compact.
+     * @returns {Array} Returns a new array of filtered values.
+     * @example
+     *
+     * _.compact([0, 1, false, 2, '', 3]);
+     * // => [1, 2, 3]
+     */
+    function compact(array) {
+      var index = -1,
+          length = array ? array.length : 0,
+          result = [];
+
+      while (++index < length) {
+        var value = array[index];
+        if (value) {
+          result.push(value);
+        }
+      }
+      return result;
+    }
+
+    /**
+     * Creates an array excluding all values of the provided arrays using strict
+     * equality for comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to process.
+     * @param {...Array} [array] The arrays of values to exclude.
+     * @returns {Array} Returns a new array of filtered values.
+     * @example
+     *
+     * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
+     * // => [1, 3, 4]
+     */
+    function difference(array) {
+      var index = -1,
+          indexOf = getIndexOf(),
+          length = array ? array.length : 0,
+          seen = baseFlatten(arguments, true, true, 1),
+          result = [];
+
+      var isLarge = length >= largeArraySize && indexOf === baseIndexOf;
+
+      if (isLarge) {
+        var cache = createCache(seen);
+        if (cache) {
+          indexOf = cacheIndexOf;
+          seen = cache;
+        } else {
+          isLarge = false;
+        }
+      }
+      while (++index < length) {
+        var value = array[index];
+        if (indexOf(seen, value) < 0) {
+          result.push(value);
+        }
+      }
+      if (isLarge) {
+        releaseObject(seen);
+      }
+      return result;
+    }
+
+    /**
+     * This method is like `_.find` except that it returns the index of the first
+     * element that passes the callback check, instead of the element itself.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {number} Returns the index of the found element, else `-1`.
+     * @example
+     *
+     * _.findIndex(['apple', 'banana', 'beet'], function(food) {
+     *   return /^b/.test(food);
+     * });
+     * // => 1
+     */
+    function findIndex(array, callback, thisArg) {
+      var index = -1,
+          length = array ? array.length : 0;
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      while (++index < length) {
+        if (callback(array[index], index, array)) {
+          return index;
+        }
+      }
+      return -1;
+    }
+
+    /**
+     * This method is like `_.findIndex` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {number} Returns the index of the found element, else `-1`.
+     * @example
+     *
+     * _.findLastIndex(['apple', 'banana', 'beet'], function(food) {
+     *   return /^b/.test(food);
+     * });
+     * // => 2
+     */
+    function findLastIndex(array, callback, thisArg) {
+      var length = array ? array.length : 0;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      while (length--) {
+        if (callback(array[length], length, array)) {
+          return length;
+        }
+      }
+      return -1;
+    }
+
+    /**
+     * Gets the first element or first `n` elements of an array. If a callback
+     * is provided elements at the beginning of the array are returned as long
+     * as the callback returns truey. The callback is bound to `thisArg` and
+     * invoked with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias head, take
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback] The function called
+     *  per element or the number of elements to return. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the first element(s) of `array`.
+     * @example
+     *
+     * _.first([1, 2, 3]);
+     * // => 1
+     *
+     * _.first([1, 2, 3], 2);
+     * // => [1, 2]
+     *
+     * _.first([1, 2, 3], function(num) {
+     *   return num < 3;
+     * });
+     * // => [1, 2]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'organic': true },
+     *   { 'name': 'beet',   'organic': false },
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.first(food, 'organic');
+     * // => [{ 'name': 'banana', 'organic': true }]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'type': 'fruit' },
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.first(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }]
+     */
+    function first(array, callback, thisArg) {
+      var n = 0,
+          length = array ? array.length : 0;
+
+      if (typeof callback != 'number' && callback != null) {
+        var index = -1;
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (++index < length && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = callback;
+        if (n == null || thisArg) {
+          return array ? array[0] : undefined;
+        }
+      }
+      return slice(array, 0, nativeMin(nativeMax(0, n), length));
+    }
+
+    /**
+     * Flattens a nested array (the nesting can be to any depth). If `isShallow`
+     * is truey, the array will only be flattened a single level. If a callback
+     * is provided each element of the array is passed through the callback before
+     * flattening. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to flatten.
+     * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new flattened array.
+     * @example
+     *
+     * _.flatten([1, [2], [3, [[4]]]]);
+     * // => [1, 2, 3, 4];
+     *
+     * _.flatten([1, [2], [3, [[4]]]], true);
+     * // => [1, 2, 3, [[4]]];
+     *
+     * var stooges = [
+     *   { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
+     *   { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.flatten(stooges, 'quotes');
+     * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!']
+     */
+    function flatten(array, isShallow, callback, thisArg) {
+      // juggle arguments
+      if (typeof isShallow != 'boolean' && isShallow != null) {
+        thisArg = callback;
+        callback = !(thisArg && thisArg[isShallow] === array) ? isShallow : null;
+        isShallow = false;
+      }
+      if (callback != null) {
+        array = map(array, callback, thisArg);
+      }
+      return baseFlatten(array, isShallow);
+    }
+
+    /**
+     * Gets the index at which the first occurrence of `value` is found using
+     * strict equality for comparisons, i.e. `===`. If the array is already sorted
+     * providing `true` for `fromIndex` will run a faster binary search.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {*} value The value to search for.
+     * @param {boolean|number} [fromIndex=0] The index to search from or `true`
+     *  to perform a binary search on a sorted array.
+     * @returns {number} Returns the index of the matched value or `-1`.
+     * @example
+     *
+     * _.indexOf([1, 2, 3, 1, 2, 3], 2);
+     * // => 1
+     *
+     * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
+     * // => 4
+     *
+     * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
+     * // => 2
+     */
+    function indexOf(array, value, fromIndex) {
+      if (typeof fromIndex == 'number') {
+        var length = array ? array.length : 0;
+        fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
+      } else if (fromIndex) {
+        var index = sortedIndex(array, value);
+        return array[index] === value ? index : -1;
+      }
+      return baseIndexOf(array, value, fromIndex);
+    }
+
+    /**
+     * Gets all but the last element or last `n` elements of an array. If a
+     * callback is provided elements at the end of the array are excluded from
+     * the result as long as the callback returns truey. The callback is bound
+     * to `thisArg` and invoked with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback=1] The function called
+     *  per element or the number of elements to exclude. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a slice of `array`.
+     * @example
+     *
+     * _.initial([1, 2, 3]);
+     * // => [1, 2]
+     *
+     * _.initial([1, 2, 3], 2);
+     * // => [1]
+     *
+     * _.initial([1, 2, 3], function(num) {
+     *   return num > 1;
+     * });
+     * // => [1]
+     *
+     * var food = [
+     *   { 'name': 'beet',   'organic': false },
+     *   { 'name': 'carrot', 'organic': true }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.initial(food, 'organic');
+     * // => [{ 'name': 'beet',   'organic': false }]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' },
+     *   { 'name': 'carrot', 'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.initial(food, { 'type': 'vegetable' });
+     * // => [{ 'name': 'banana', 'type': 'fruit' }]
+     */
+    function initial(array, callback, thisArg) {
+      var n = 0,
+          length = array ? array.length : 0;
+
+      if (typeof callback != 'number' && callback != null) {
+        var index = length;
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (index-- && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = (callback == null || thisArg) ? 1 : callback || n;
+      }
+      return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
+    }
+
+    /**
+     * Creates an array of unique values present in all provided arrays using
+     * strict equality for comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {...Array} [array] The arrays to inspect.
+     * @returns {Array} Returns an array of composite values.
+     * @example
+     *
+     * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
+     * // => [1, 2]
+     */
+    function intersection(array) {
+      var args = arguments,
+          argsLength = args.length,
+          argsIndex = -1,
+          caches = getArray(),
+          index = -1,
+          indexOf = getIndexOf(),
+          length = array ? array.length : 0,
+          result = [],
+          seen = getArray();
+
+      while (++argsIndex < argsLength) {
+        var value = args[argsIndex];
+        caches[argsIndex] = indexOf === baseIndexOf &&
+          (value ? value.length : 0) >= largeArraySize &&
+          createCache(argsIndex ? args[argsIndex] : seen);
+      }
+      outer:
+      while (++index < length) {
+        var cache = caches[0];
+        value = array[index];
+
+        if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
+          argsIndex = argsLength;
+          (cache || seen).push(value);
+          while (--argsIndex) {
+            cache = caches[argsIndex];
+            if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
+              continue outer;
+            }
+          }
+          result.push(value);
+        }
+      }
+      while (argsLength--) {
+        cache = caches[argsLength];
+        if (cache) {
+          releaseObject(cache);
+        }
+      }
+      releaseArray(caches);
+      releaseArray(seen);
+      return result;
+    }
+
+    /**
+     * Gets the last element or last `n` elements of an array. If a callback is
+     * provided elements at the end of the array are returned as long as the
+     * callback returns truey. The callback is bound to `thisArg` and invoked
+     * with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback] The function called
+     *  per element or the number of elements to return. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the last element(s) of `array`.
+     * @example
+     *
+     * _.last([1, 2, 3]);
+     * // => 3
+     *
+     * _.last([1, 2, 3], 2);
+     * // => [2, 3]
+     *
+     * _.last([1, 2, 3], function(num) {
+     *   return num > 1;
+     * });
+     * // => [2, 3]
+     *
+     * var food = [
+     *   { 'name': 'beet',   'organic': false },
+     *   { 'name': 'carrot', 'organic': true }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.last(food, 'organic');
+     * // => [{ 'name': 'carrot', 'organic': true }]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' },
+     *   { 'name': 'carrot', 'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.last(food, { 'type': 'vegetable' });
+     * // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }]
+     */
+    function last(array, callback, thisArg) {
+      var n = 0,
+          length = array ? array.length : 0;
+
+      if (typeof callback != 'number' && callback != null) {
+        var index = length;
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (index-- && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = callback;
+        if (n == null || thisArg) {
+          return array ? array[length - 1] : undefined;
+        }
+      }
+      return slice(array, nativeMax(0, length - n));
+    }
+
+    /**
+     * Gets the index at which the last occurrence of `value` is found using strict
+     * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
+     * as the offset from the end of the collection.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {*} value The value to search for.
+     * @param {number} [fromIndex=array.length-1] The index to search from.
+     * @returns {number} Returns the index of the matched value or `-1`.
+     * @example
+     *
+     * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
+     * // => 4
+     *
+     * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
+     * // => 1
+     */
+    function lastIndexOf(array, value, fromIndex) {
+      var index = array ? array.length : 0;
+      if (typeof fromIndex == 'number') {
+        index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
+      }
+      while (index--) {
+        if (array[index] === value) {
+          return index;
+        }
+      }
+      return -1;
+    }
+
+    /**
+     * Removes all provided values from the given array using strict equality for
+     * comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to modify.
+     * @param {...*} [value] The values to remove.
+     * @returns {Array} Returns `array`.
+     * @example
+     *
+     * var array = [1, 2, 3, 1, 2, 3];
+     * _.pull(array, 2, 3);
+     * console.log(array);
+     * // => [1, 1]
+     */
+    function pull(array) {
+      var args = arguments,
+          argsIndex = 0,
+          argsLength = args.length,
+          length = array ? array.length : 0;
+
+      while (++argsIndex < argsLength) {
+        var index = -1,
+            value = args[argsIndex];
+        while (++index < length) {
+          if (array[index] === value) {
+            splice.call(array, index--, 1);
+            length--;
+          }
+        }
+      }
+      return array;
+    }
+
+    /**
+     * Creates an array of numbers (positive and/or negative) progressing from
+     * `start` up to but not including `end`. If `start` is less than `stop` a
+     * zero-length range is created unless a negative `step` is specified.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {number} [start=0] The start of the range.
+     * @param {number} end The end of the range.
+     * @param {number} [step=1] The value to increment or decrement by.
+     * @returns {Array} Returns a new range array.
+     * @example
+     *
+     * _.range(10);
+     * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+     *
+     * _.range(1, 11);
+     * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+     *
+     * _.range(0, 30, 5);
+     * // => [0, 5, 10, 15, 20, 25]
+     *
+     * _.range(0, -10, -1);
+     * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
+     *
+     * _.range(1, 4, 0);
+     * // => [1, 1, 1]
+     *
+     * _.range(0);
+     * // => []
+     */
+    function range(start, end, step) {
+      start = +start || 0;
+      step = typeof step == 'number' ? step : (+step || 1);
+
+      if (end == null) {
+        end = start;
+        start = 0;
+      }
+      // use `Array(length)` so engines, like Chakra and V8, avoid slower modes
+      // http://youtu.be/XAqIpGU8ZZk#t=17m25s
+      var index = -1,
+          length = nativeMax(0, ceil((end - start) / (step || 1))),
+          result = Array(length);
+
+      while (++index < length) {
+        result[index] = start;
+        start += step;
+      }
+      return result;
+    }
+
+    /**
+     * Removes all elements from an array that the callback returns truey for
+     * and returns an array of removed elements. The callback is bound to `thisArg`
+     * and invoked with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to modify.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of removed elements.
+     * @example
+     *
+     * var array = [1, 2, 3, 4, 5, 6];
+     * var evens = _.remove(array, function(num) { return num % 2 == 0; });
+     *
+     * console.log(array);
+     * // => [1, 3, 5]
+     *
+     * console.log(evens);
+     * // => [2, 4, 6]
+     */
+    function remove(array, callback, thisArg) {
+      var index = -1,
+          length = array ? array.length : 0,
+          result = [];
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      while (++index < length) {
+        var value = array[index];
+        if (callback(value, index, array)) {
+          result.push(value);
+          splice.call(array, index--, 1);
+          length--;
+        }
+      }
+      return result;
+    }
+
+    /**
+     * The opposite of `_.initial` this method gets all but the first element or
+     * first `n` elements of an array. If a callback function is provided elements
+     * at the beginning of the array are excluded from the result as long as the
+     * callback returns truey. The callback is bound to `thisArg` and invoked
+     * with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias drop, tail
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback=1] The function called
+     *  per element or the number of elements to exclude. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a slice of `array`.
+     * @example
+     *
+     * _.rest([1, 2, 3]);
+     * // => [2, 3]
+     *
+     * _.rest([1, 2, 3], 2);
+     * // => [3]
+     *
+     * _.rest([1, 2, 3], function(num) {
+     *   return num < 3;
+     * });
+     * // => [3]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'organic': true },
+     *   { 'name': 'beet',   'organic': false },
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.rest(food, 'organic');
+     * // => [{ 'name': 'beet', 'organic': false }]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'type': 'fruit' },
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.rest(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'beet', 'type': 'vegetable' }]
+     */
+    function rest(array, callback, thisArg) {
+      if (typeof callback != 'number' && callback != null) {
+        var n = 0,
+            index = -1,
+            length = array ? array.length : 0;
+
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (++index < length && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
+      }
+      return slice(array, n);
+    }
+
+    /**
+     * Uses a binary search to determine the smallest index at which a value
+     * should be inserted into a given sorted array in order to maintain the sort
+     * order of the array. If a callback is provided it will be executed for
+     * `value` and each element of `array` to compute their sort ranking. The
+     * callback is bound to `thisArg` and invoked with one argument; (value).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to inspect.
+     * @param {*} value The value to evaluate.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {number} Returns the index at which `value` should be inserted
+     *  into `array`.
+     * @example
+     *
+     * _.sortedIndex([20, 30, 50], 40);
+     * // => 2
+     *
+     * // using "_.pluck" callback shorthand
+     * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
+     * // => 2
+     *
+     * var dict = {
+     *   'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
+     * };
+     *
+     * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
+     *   return dict.wordToNumber[word];
+     * });
+     * // => 2
+     *
+     * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
+     *   return this.wordToNumber[word];
+     * }, dict);
+     * // => 2
+     */
+    function sortedIndex(array, value, callback, thisArg) {
+      var low = 0,
+          high = array ? array.length : low;
+
+      // explicitly reference `identity` for better inlining in Firefox
+      callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
+      value = callback(value);
+
+      while (low < high) {
+        var mid = (low + high) >>> 1;
+        (callback(array[mid]) < value)
+          ? low = mid + 1
+          : high = mid;
+      }
+      return low;
+    }
+
+    /**
+     * Creates an array of unique values, in order, of the provided arrays using
+     * strict equality for comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {...Array} [array] The arrays to inspect.
+     * @returns {Array} Returns an array of composite values.
+     * @example
+     *
+     * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
+     * // => [1, 2, 3, 101, 10]
+     */
+    function union(array) {
+      return baseUniq(baseFlatten(arguments, true, true));
+    }
+
+    /**
+     * Creates a duplicate-value-free version of an array using strict equality
+     * for comparisons, i.e. `===`. If the array is sorted, providing
+     * `true` for `isSorted` will use a faster algorithm. If a callback is provided
+     * each element of `array` is passed through the callback before uniqueness
+     * is computed. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias unique
+     * @category Arrays
+     * @param {Array} array The array to process.
+     * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a duplicate-value-free array.
+     * @example
+     *
+     * _.uniq([1, 2, 1, 3, 1]);
+     * // => [1, 2, 3]
+     *
+     * _.uniq([1, 1, 2, 2, 3], true);
+     * // => [1, 2, 3]
+     *
+     * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
+     * // => ['A', 'b', 'C']
+     *
+     * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
+     * // => [1, 2.5, 3]
+     *
+     * // using "_.pluck" callback shorthand
+     * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
+     * // => [{ 'x': 1 }, { 'x': 2 }]
+     */
+    function uniq(array, isSorted, callback, thisArg) {
+      // juggle arguments
+      if (typeof isSorted != 'boolean' && isSorted != null) {
+        thisArg = callback;
+        callback = !(thisArg && thisArg[isSorted] === array) ? isSorted : null;
+        isSorted = false;
+      }
+      if (callback != null) {
+        callback = lodash.createCallback(callback, thisArg, 3);
+      }
+      return baseUniq(array, isSorted, callback);
+    }
+
+    /**
+     * Creates an array excluding all provided values using strict equality for
+     * comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to filter.
+     * @param {...*} [value] The values to exclude.
+     * @returns {Array} Returns a new array of filtered values.
+     * @example
+     *
+     * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
+     * // => [2, 3, 4]
+     */
+    function without(array) {
+      return difference(array, nativeSlice.call(arguments, 1));
+    }
+
+    /**
+     * Creates an array of grouped elements, the first of which contains the first
+     * elements of the given arrays, the second of which contains the second
+     * elements of the given arrays, and so on.
+     *
+     * @static
+     * @memberOf _
+     * @alias unzip
+     * @category Arrays
+     * @param {...Array} [array] Arrays to process.
+     * @returns {Array} Returns a new array of grouped elements.
+     * @example
+     *
+     * _.zip(['moe', 'larry'], [30, 40], [true, false]);
+     * // => [['moe', 30, true], ['larry', 40, false]]
+     */
+    function zip() {
+      var array = arguments.length > 1 ? arguments : arguments[0],
+          index = -1,
+          length = array ? max(pluck(array, 'length')) : 0,
+          result = Array(length < 0 ? 0 : length);
+
+      while (++index < length) {
+        result[index] = pluck(array, index);
+      }
+      return result;
+    }
+
+    /**
+     * Creates an object composed from arrays of `keys` and `values`. Provide
+     * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
+     * or two arrays, one of `keys` and one of corresponding `values`.
+     *
+     * @static
+     * @memberOf _
+     * @alias object
+     * @category Arrays
+     * @param {Array} keys The array of keys.
+     * @param {Array} [values=[]] The array of values.
+     * @returns {Object} Returns an object composed of the given keys and
+     *  corresponding values.
+     * @example
+     *
+     * _.zipObject(['moe', 'larry'], [30, 40]);
+     * // => { 'moe': 30, 'larry': 40 }
+     */
+    function zipObject(keys, values) {
+      var index = -1,
+          length = keys ? keys.length : 0,
+          result = {};
+
+      while (++index < length) {
+        var key = keys[index];
+        if (values) {
+          result[key] = values[index];
+        } else if (key) {
+          result[key[0]] = key[1];
+        }
+      }
+      return result;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates a function that executes `func`, with  the `this` binding and
+     * arguments of the created function, only after being called `n` times.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {number} n The number of times the function must be called before
+     *  `func` is executed.
+     * @param {Function} func The function to restrict.
+     * @returns {Function} Returns the new restricted function.
+     * @example
+     *
+     * var saves = ['profile', 'settings'];
+     *
+     * var done = _.after(saves.length, function() {
+     *   console.log('Done saving!');
+     * });
+     *
+     * _.forEach(saves, function(type) {
+     *   asyncSave({ 'type': type, 'complete': done });
+     * });
+     * // => logs 'Done saving!', after all saves have completed
+     */
+    function after(n, func) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      return function() {
+        if (--n < 1) {
+          return func.apply(this, arguments);
+        }
+      };
+    }
+
+    /**
+     * Creates a function that, when called, invokes `func` with the `this`
+     * binding of `thisArg` and prepends any additional `bind` arguments to those
+     * provided to the bound function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to bind.
+     * @param {*} [thisArg] The `this` binding of `func`.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new bound function.
+     * @example
+     *
+     * var func = function(greeting) {
+     *   return greeting + ' ' + this.name;
+     * };
+     *
+     * func = _.bind(func, { 'name': 'moe' }, 'hi');
+     * func();
+     * // => 'hi moe'
+     */
+    function bind(func, thisArg) {
+      return arguments.length > 2
+        ? createBound(func, 17, nativeSlice.call(arguments, 2), null, thisArg)
+        : createBound(func, 1, null, null, thisArg);
+    }
+
+    /**
+     * Binds methods of an object to the object itself, overwriting the existing
+     * method. Method names may be specified as individual arguments or as arrays
+     * of method names. If no method names are provided all the function properties
+     * of `object` will be bound.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Object} object The object to bind and assign the bound methods to.
+     * @param {...string} [methodName] The object method names to
+     *  bind, specified as individual method names or arrays of method names.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * var view = {
+     *  'label': 'docs',
+     *  'onClick': function() { console.log('clicked ' + this.label); }
+     * };
+     *
+     * _.bindAll(view);
+     * jQuery('#docs').on('click', view.onClick);
+     * // => logs 'clicked docs', when the button is clicked
+     */
+    function bindAll(object) {
+      var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
+          index = -1,
+          length = funcs.length;
+
+      while (++index < length) {
+        var key = funcs[index];
+        object[key] = createBound(object[key], 1, null, null, object);
+      }
+      return object;
+    }
+
+    /**
+     * Creates a function that, when called, invokes the method at `object[key]`
+     * and prepends any additional `bindKey` arguments to those provided to the bound
+     * function. This method differs from `_.bind` by allowing bound functions to
+     * reference methods that will be redefined or don't yet exist.
+     * See http://michaux.ca/articles/lazy-function-definition-pattern.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Object} object The object the method belongs to.
+     * @param {string} key The key of the method.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new bound function.
+     * @example
+     *
+     * var object = {
+     *   'name': 'moe',
+     *   'greet': function(greeting) {
+     *     return greeting + ' ' + this.name;
+     *   }
+     * };
+     *
+     * var func = _.bindKey(object, 'greet', 'hi');
+     * func();
+     * // => 'hi moe'
+     *
+     * object.greet = function(greeting) {
+     *   return greeting + ', ' + this.name + '!';
+     * };
+     *
+     * func();
+     * // => 'hi, moe!'
+     */
+    function bindKey(object, key) {
+      return arguments.length > 2
+        ? createBound(key, 19, nativeSlice.call(arguments, 2), null, object)
+        : createBound(key, 3, null, null, object);
+    }
+
+    /**
+     * Creates a function that is the composition of the provided functions,
+     * where each function consumes the return value of the function that follows.
+     * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
+     * Each function is executed with the `this` binding of the composed function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {...Function} [func] Functions to compose.
+     * @returns {Function} Returns the new composed function.
+     * @example
+     *
+     * var realNameMap = {
+     *   'curly': 'jerome'
+     * };
+     *
+     * var format = function(name) {
+     *   name = realNameMap[name.toLowerCase()] || name;
+     *   return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
+     * };
+     *
+     * var greet = function(formatted) {
+     *   return 'Hiya ' + formatted + '!';
+     * };
+     *
+     * var welcome = _.compose(greet, format);
+     * welcome('curly');
+     * // => 'Hiya Jerome!'
+     */
+    function compose() {
+      var funcs = arguments,
+          length = funcs.length;
+
+      while (length--) {
+        if (!isFunction(funcs[length])) {
+          throw new TypeError;
+        }
+      }
+      return function() {
+        var args = arguments,
+            length = funcs.length;
+
+        while (length--) {
+          args = [funcs[length].apply(this, args)];
+        }
+        return args[0];
+      };
+    }
+
+    /**
+     * Produces a callback bound to an optional `thisArg`. If `func` is a property
+     * name the created callback will return the property value for a given element.
+     * If `func` is an object the created callback will return `true` for elements
+     * that contain the equivalent object properties, otherwise it will return `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {*} [func=identity] The value to convert to a callback.
+     * @param {*} [thisArg] The `this` binding of the created callback.
+     * @param {number} [argCount] The number of arguments the callback accepts.
+     * @returns {Function} Returns a callback function.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // wrap to create custom callback shorthands
+     * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
+     *   var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
+     *   return !match ? func(callback, thisArg) : function(object) {
+     *     return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
+     *   };
+     * });
+     *
+     * _.filter(stooges, 'age__gt45');
+     * // => [{ 'name': 'larry', 'age': 50 }]
+     */
+    function createCallback(func, thisArg, argCount) {
+      var type = typeof func;
+      if (func == null || type == 'function') {
+        return baseCreateCallback(func, thisArg, argCount);
+      }
+      // handle "_.pluck" style callback shorthands
+      if (type != 'object') {
+        return function(object) {
+          return object[func];
+        };
+      }
+      var props = keys(func),
+          key = props[0],
+          a = func[key];
+
+      // handle "_.where" style callback shorthands
+      if (props.length == 1 && a === a && !isObject(a)) {
+        // fast path the common case of providing an object with a single
+        // property containing a primitive value
+        return function(object) {
+          var b = object[key];
+          return a === b && (a !== 0 || (1 / a == 1 / b));
+        };
+      }
+      return function(object) {
+        var length = props.length,
+            result = false;
+
+        while (length--) {
+          if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
+            break;
+          }
+        }
+        return result;
+      };
+    }
+
+    /**
+     * Creates a function which accepts one or more arguments of `func` that when
+     * invoked either executes `func` returning its result, if all `func` arguments
+     * have been provided, or returns a function that accepts one or more of the
+     * remaining `func` arguments, and so on. The arity of `func` can be specified
+     * if `func.length` is not sufficient.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to curry.
+     * @param {number} [arity=func.length] The arity of `func`.
+     * @returns {Function} Returns the new curried function.
+     * @example
+     *
+     * var curried = _.curry(function(a, b, c) {
+     *   console.log(a + b + c);
+     * });
+     *
+     * curried(1)(2)(3);
+     * // => 6
+     *
+     * curried(1, 2)(3);
+     * // => 6
+     *
+     * curried(1, 2, 3);
+     * // => 6
+     */
+    function curry(func, arity) {
+      arity = typeof arity == 'number' ? arity : (+arity || func.length);
+      return createBound(func, 4, null, null, null, arity);
+    }
+
+    /**
+     * Creates a function that will delay the execution of `func` until after
+     * `wait` milliseconds have elapsed since the last time it was invoked.
+     * Provide an options object to indicate that `func` should be invoked on
+     * the leading and/or trailing edge of the `wait` timeout. Subsequent calls
+     * to the debounced function will return the result of the last `func` call.
+     *
+     * Note: If `leading` and `trailing` options are `true` `func` will be called
+     * on the trailing edge of the timeout only if the the debounced function is
+     * invoked more than once during the `wait` timeout.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to debounce.
+     * @param {number} wait The number of milliseconds to delay.
+     * @param {Object} [options] The options object.
+     * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
+     * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
+     * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
+     * @returns {Function} Returns the new debounced function.
+     * @example
+     *
+     * // avoid costly calculations while the window size is in flux
+     * var lazyLayout = _.debounce(calculateLayout, 150);
+     * jQuery(window).on('resize', lazyLayout);
+     *
+     * // execute `sendMail` when the click event is fired, debouncing subsequent calls
+     * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
+     *   'leading': true,
+     *   'trailing': false
+     * });
+     *
+     * // ensure `batchLog` is executed once after 1 second of debounced calls
+     * var source = new EventSource('/stream');
+     * source.addEventListener('message', _.debounce(batchLog, 250, {
+     *   'maxWait': 1000
+     * }, false);
+     */
+    function debounce(func, wait, options) {
+      var args,
+          maxTimeoutId,
+          result,
+          stamp,
+          thisArg,
+          timeoutId,
+          trailingCall,
+          lastCalled = 0,
+          maxWait = false,
+          trailing = true;
+
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      wait = nativeMax(0, wait) || 0;
+      if (options === true) {
+        var leading = true;
+        trailing = false;
+      } else if (isObject(options)) {
+        leading = options.leading;
+        maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
+        trailing = 'trailing' in options ? options.trailing : trailing;
+      }
+      var delayed = function() {
+        var remaining = wait - (now() - stamp);
+        if (remaining <= 0) {
+          if (maxTimeoutId) {
+            clearTimeout(maxTimeoutId);
+          }
+          var isCalled = trailingCall;
+          maxTimeoutId = timeoutId = trailingCall = undefined;
+          if (isCalled) {
+            lastCalled = now();
+            result = func.apply(thisArg, args);
+          }
+        } else {
+          timeoutId = setTimeout(delayed, remaining);
+        }
+      };
+
+      var maxDelayed = function() {
+        if (timeoutId) {
+          clearTimeout(timeoutId);
+        }
+        maxTimeoutId = timeoutId = trailingCall = undefined;
+        if (trailing || (maxWait !== wait)) {
+          lastCalled = now();
+          result = func.apply(thisArg, args);
+        }
+      };
+
+      return function() {
+        args = arguments;
+        stamp = now();
+        thisArg = this;
+        trailingCall = trailing && (timeoutId || !leading);
+
+        if (maxWait === false) {
+          var leadingCall = leading && !timeoutId;
+        } else {
+          if (!maxTimeoutId && !leading) {
+            lastCalled = stamp;
+          }
+          var remaining = maxWait - (stamp - lastCalled);
+          if (remaining <= 0) {
+            if (maxTimeoutId) {
+              maxTimeoutId = clearTimeout(maxTimeoutId);
+            }
+            lastCalled = stamp;
+            result = func.apply(thisArg, args);
+          }
+          else if (!maxTimeoutId) {
+            maxTimeoutId = setTimeout(maxDelayed, remaining);
+          }
+        }
+        if (!timeoutId && wait !== maxWait) {
+          timeoutId = setTimeout(delayed, wait);
+        }
+        if (leadingCall) {
+          result = func.apply(thisArg, args);
+        }
+        return result;
+      };
+    }
+
+    /**
+     * Defers executing the `func` function until the current call stack has cleared.
+     * Additional arguments will be provided to `func` when it is invoked.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to defer.
+     * @param {...*} [arg] Arguments to invoke the function with.
+     * @returns {number} Returns the timer id.
+     * @example
+     *
+     * _.defer(function() { console.log('deferred'); });
+     * // returns from the function before 'deferred' is logged
+     */
+    function defer(func) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      var args = nativeSlice.call(arguments, 1);
+      return setTimeout(function() { func.apply(undefined, args); }, 1);
+    }
+    // use `setImmediate` if available in Node.js
+    if (isV8 && moduleExports && typeof setImmediate == 'function') {
+      defer = function(func) {
+        if (!isFunction(func)) {
+          throw new TypeError;
+        }
+        return setImmediate.apply(context, arguments);
+      };
+    }
+
+    /**
+     * Executes the `func` function after `wait` milliseconds. Additional arguments
+     * will be provided to `func` when it is invoked.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to delay.
+     * @param {number} wait The number of milliseconds to delay execution.
+     * @param {...*} [arg] Arguments to invoke the function with.
+     * @returns {number} Returns the timer id.
+     * @example
+     *
+     * var log = _.bind(console.log, console);
+     * _.delay(log, 1000, 'logged later');
+     * // => 'logged later' (Appears after one second.)
+     */
+    function delay(func, wait) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      var args = nativeSlice.call(arguments, 2);
+      return setTimeout(function() { func.apply(undefined, args); }, wait);
+    }
+
+    /**
+     * Creates a function that memoizes the result of `func`. If `resolver` is
+     * provided it will be used to determine the cache key for storing the result
+     * based on the arguments provided to the memoized function. By default, the
+     * first argument provided to the memoized function is used as the cache key.
+     * The `func` is executed with the `this` binding of the memoized function.
+     * The result cache is exposed as the `cache` property on the memoized function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to have its output memoized.
+     * @param {Function} [resolver] A function used to resolve the cache key.
+     * @returns {Function} Returns the new memoizing function.
+     * @example
+     *
+     * var fibonacci = _.memoize(function(n) {
+     *   return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
+     * });
+     *
+     * var data = {
+     *   'moe': { 'name': 'moe', 'age': 40 },
+     *   'curly': { 'name': 'curly', 'age': 60 }
+     * };
+     *
+     * // modifying the result cache
+     * var stooge = _.memoize(function(name) { return data[name]; }, _.identity);
+     * stooge('curly');
+     * // => { 'name': 'curly', 'age': 60 }
+     *
+     * stooge.cache.curly.name = 'jerome';
+     * stooge('curly');
+     * // => { 'name': 'jerome', 'age': 60 }
+     */
+    function memoize(func, resolver) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      var memoized = function() {
+        var cache = memoized.cache,
+            key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
+
+        return hasOwnProperty.call(cache, key)
+          ? cache[key]
+          : (cache[key] = func.apply(this, arguments));
+      }
+      memoized.cache = {};
+      return memoized;
+    }
+
+    /**
+     * Creates a function that is restricted to execute `func` once. Repeat calls to
+     * the function will return the value of the first call. The `func` is executed
+     * with the `this` binding of the created function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to restrict.
+     * @returns {Function} Returns the new restricted function.
+     * @example
+     *
+     * var initialize = _.once(createApplication);
+     * initialize();
+     * initialize();
+     * // `initialize` executes `createApplication` once
+     */
+    function once(func) {
+      var ran,
+          result;
+
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      return function() {
+        if (ran) {
+          return result;
+        }
+        ran = true;
+        result = func.apply(this, arguments);
+
+        // clear the `func` variable so the function may be garbage collected
+        func = null;
+        return result;
+      };
+    }
+
+    /**
+     * Creates a function that, when called, invokes `func` with any additional
+     * `partial` arguments prepended to those provided to the new function. This
+     * method is similar to `_.bind` except it does **not** alter the `this` binding.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to partially apply arguments to.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new partially applied function.
+     * @example
+     *
+     * var greet = function(greeting, name) { return greeting + ' ' + name; };
+     * var hi = _.partial(greet, 'hi');
+     * hi('moe');
+     * // => 'hi moe'
+     */
+    function partial(func) {
+      return createBound(func, 16, nativeSlice.call(arguments, 1));
+    }
+
+    /**
+     * This method is like `_.partial` except that `partial` arguments are
+     * appended to those provided to the new function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to partially apply arguments to.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new partially applied function.
+     * @example
+     *
+     * var defaultsDeep = _.partialRight(_.merge, _.defaults);
+     *
+     * var options = {
+     *   'variable': 'data',
+     *   'imports': { 'jq': $ }
+     * };
+     *
+     * defaultsDeep(options, _.templateSettings);
+     *
+     * options.variable
+     * // => 'data'
+     *
+     * options.imports
+     * // => { '_': _, 'jq': $ }
+     */
+    function partialRight(func) {
+      return createBound(func, 32, null, nativeSlice.call(arguments, 1));
+    }
+
+    /**
+     * Creates a function that, when executed, will only call the `func` function
+     * at most once per every `wait` milliseconds. Provide an options object to
+     * indicate that `func` should be invoked on the leading and/or trailing edge
+     * of the `wait` timeout. Subsequent calls to the throttled function will
+     * return the result of the last `func` call.
+     *
+     * Note: If `leading` and `trailing` options are `true` `func` will be called
+     * on the trailing edge of the timeout only if the the throttled function is
+     * invoked more than once during the `wait` timeout.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to throttle.
+     * @param {number} wait The number of milliseconds to throttle executions to.
+     * @param {Object} [options] The options object.
+     * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
+     * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
+     * @returns {Function} Returns the new throttled function.
+     * @example
+     *
+     * // avoid excessively updating the position while scrolling
+     * var throttled = _.throttle(updatePosition, 100);
+     * jQuery(window).on('scroll', throttled);
+     *
+     * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
+     * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
+     *   'trailing': false
+     * }));
+     */
+    function throttle(func, wait, options) {
+      var leading = true,
+          trailing = true;
+
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      if (options === false) {
+        leading = false;
+      } else if (isObject(options)) {
+        leading = 'leading' in options ? options.leading : leading;
+        trailing = 'trailing' in options ? options.trailing : trailing;
+      }
+      debounceOptions.leading = leading;
+      debounceOptions.maxWait = wait;
+      debounceOptions.trailing = trailing;
+
+      var result = debounce(func, wait, debounceOptions);
+      return result;
+    }
+
+    /**
+     * Creates a function that provides `value` to the wrapper function as its
+     * first argument. Additional arguments provided to the function are appended
+     * to those provided to the wrapper function. The wrapper is executed with
+     * the `this` binding of the created function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {*} value The value to wrap.
+     * @param {Function} wrapper The wrapper function.
+     * @returns {Function} Returns the new function.
+     * @example
+     *
+     * var hello = function(name) { return 'hello ' + name; };
+     * hello = _.wrap(hello, function(func) {
+     *   return 'before, ' + func('moe') + ', after';
+     * });
+     * hello();
+     * // => 'before, hello moe, after'
+     */
+    function wrap(value, wrapper) {
+      if (!isFunction(wrapper)) {
+        throw new TypeError;
+      }
+      return function() {
+        var args = [value];
+        push.apply(args, arguments);
+        return wrapper.apply(this, args);
+      };
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
+     * corresponding HTML entities.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} string The string to escape.
+     * @returns {string} Returns the escaped string.
+     * @example
+     *
+     * _.escape('Moe, Larry & Curly');
+     * // => 'Moe, Larry &amp; Curly'
+     */
+    function escape(string) {
+      return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
+    }
+
+    /**
+     * This method returns the first argument provided to it.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {*} value Any value.
+     * @returns {*} Returns `value`.
+     * @example
+     *
+     * var moe = { 'name': 'moe' };
+     * moe === _.identity(moe);
+     * // => true
+     */
+    function identity(value) {
+      return value;
+    }
+
+    /**
+     * Adds function properties of a source object to the `lodash` function and
+     * chainable wrapper.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {Object} object The object of function properties to add to `lodash`.
+     * @param {Object} object The object of function properties to add to `lodash`.
+     * @example
+     *
+     * _.mixin({
+     *   'capitalize': function(string) {
+     *     return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
+     *   }
+     * });
+     *
+     * _.capitalize('moe');
+     * // => 'Moe'
+     *
+     * _('moe').capitalize();
+     * // => 'Moe'
+     */
+    function mixin(object, source) {
+      var ctor = object,
+          isFunc = !source || isFunction(ctor);
+
+      if (!source) {
+        ctor = lodashWrapper;
+        source = object;
+        object = lodash;
+      }
+      forEach(functions(source), function(methodName) {
+        var func = object[methodName] = source[methodName];
+        if (isFunc) {
+          ctor.prototype[methodName] = function() {
+            var value = this.__wrapped__,
+                args = [value];
+
+            push.apply(args, arguments);
+            var result = func.apply(object, args);
+            if (value && typeof value == 'object' && value === result) {
+              return this;
+            }
+            result = new ctor(result);
+            result.__chain__ = this.__chain__;
+            return result;
+          };
+        }
+      });
+    }
+
+    /**
+     * Reverts the '_' variable to its previous value and returns a reference to
+     * the `lodash` function.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @returns {Function} Returns the `lodash` function.
+     * @example
+     *
+     * var lodash = _.noConflict();
+     */
+    function noConflict() {
+      context._ = oldDash;
+      return this;
+    }
+
+    /**
+     * Converts the given value into an integer of the specified radix.
+     * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
+     * `value` is a hexadecimal, in which case a `radix` of `16` is used.
+     *
+     * Note: This method avoids differences in native ES3 and ES5 `parseInt`
+     * implementations. See http://es5.github.io/#E.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} value The value to parse.
+     * @param {number} [radix] The radix used to interpret the value to parse.
+     * @returns {number} Returns the new integer value.
+     * @example
+     *
+     * _.parseInt('08');
+     * // => 8
+     */
+    var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
+      // Firefox and Opera still follow the ES3 specified implementation of `parseInt`
+      return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
+    };
+
+    /**
+     * Produces a random number between `min` and `max` (inclusive). If only one
+     * argument is provided a number between `0` and the given number will be
+     * returned. If `floating` is truey or either `min` or `max` are floats a
+     * floating-point number will be returned instead of an integer.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {number} [min=0] The minimum possible value.
+     * @param {number} [max=1] The maximum possible value.
+     * @param {boolean} [floating=false] Specify returning a floating-point number.
+     * @returns {number} Returns a random number.
+     * @example
+     *
+     * _.random(0, 5);
+     * // => an integer between 0 and 5
+     *
+     * _.random(5);
+     * // => also an integer between 0 and 5
+     *
+     * _.random(5, true);
+     * // => a floating-point number between 0 and 5
+     *
+     * _.random(1.2, 5.2);
+     * // => a floating-point number between 1.2 and 5.2
+     */
+    function random(min, max, floating) {
+      var noMin = min == null,
+          noMax = max == null;
+
+      if (floating == null) {
+        if (typeof min == 'boolean' && noMax) {
+          floating = min;
+          min = 1;
+        }
+        else if (!noMax && typeof max == 'boolean') {
+          floating = max;
+          noMax = true;
+        }
+      }
+      if (noMin && noMax) {
+        max = 1;
+      }
+      min = +min || 0;
+      if (noMax) {
+        max = min;
+        min = 0;
+      } else {
+        max = +max || 0;
+      }
+      var rand = nativeRandom();
+      return (floating || min % 1 || max % 1)
+        ? nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max)
+        : min + floor(rand * (max - min + 1));
+    }
+
+    /**
+     * Resolves the value of `property` on `object`. If `property` is a function
+     * it will be invoked with the `this` binding of `object` and its result returned,
+     * else the property value is returned. If `object` is falsey then `undefined`
+     * is returned.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {Object} object The object to inspect.
+     * @param {string} property The property to get the value of.
+     * @returns {*} Returns the resolved value.
+     * @example
+     *
+     * var object = {
+     *   'cheese': 'crumpets',
+     *   'stuff': function() {
+     *     return 'nonsense';
+     *   }
+     * };
+     *
+     * _.result(object, 'cheese');
+     * // => 'crumpets'
+     *
+     * _.result(object, 'stuff');
+     * // => 'nonsense'
+     */
+    function result(object, property) {
+      if (object) {
+        var value = object[property];
+        return isFunction(value) ? object[property]() : value;
+      }
+    }
+
+    /**
+     * A micro-templating method that handles arbitrary delimiters, preserves
+     * whitespace, and correctly escapes quotes within interpolated code.
+     *
+     * Note: In the development build, `_.template` utilizes sourceURLs for easier
+     * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
+     *
+     * For more information on precompiling templates see:
+     * http://lodash.com/#custom-builds
+     *
+     * For more information on Chrome extension sandboxes see:
+     * http://developer.chrome.com/stable/extensions/sandboxingEval.html
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} text The template text.
+     * @param {Object} data The data object used to populate the text.
+     * @param {Object} [options] The options object.
+     * @param {RegExp} [options.escape] The "escape" delimiter.
+     * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
+     * @param {Object} [options.imports] An object to import into the template as local variables.
+     * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
+     * @param {string} [sourceURL] The sourceURL of the template's compiled source.
+     * @param {string} [variable] The data object variable name.
+     * @returns {Function|string} Returns a compiled function when no `data` object
+     *  is given, else it returns the interpolated text.
+     * @example
+     *
+     * // using the "interpolate" delimiter to create a compiled template
+     * var compiled = _.template('hello <%= name %>');
+     * compiled({ 'name': 'moe' });
+     * // => 'hello moe'
+     *
+     * // using the "escape" delimiter to escape HTML in data property values
+     * _.template('<b><%- value %></b>', { 'value': '<script>' });
+     * // => '<b>&lt;script&gt;</b>'
+     *
+     * // using the "evaluate" delimiter to generate HTML
+     * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
+     * _.template(list, { 'people': ['moe', 'larry'] });
+     * // => '<li>moe</li><li>larry</li>'
+     *
+     * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
+     * _.template('hello ${ name }', { 'name': 'curly' });
+     * // => 'hello curly'
+     *
+     * // using the internal `print` function in "evaluate" delimiters
+     * _.template('<% print("hello " + name); %>!', { 'name': 'larry' });
+     * // => 'hello larry!'
+     *
+     * // using a custom template delimiters
+     * _.templateSettings = {
+     *   'interpolate': /{{([\s\S]+?)}}/g
+     * };
+     *
+     * _.template('hello {{ name }}!', { 'name': 'mustache' });
+     * // => 'hello mustache!'
+     *
+     * // using the `imports` option to import jQuery
+     * var list = '<% $.each(people, function(name) { %><li><%- name %></li><% }); %>';
+     * _.template(list, { 'people': ['moe', 'larry'] }, { 'imports': { '$': jQuery } });
+     * // => '<li>moe</li><li>larry</li>'
+     *
+     * // using the `sourceURL` option to specify a custom sourceURL for the template
+     * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
+     * compiled(data);
+     * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
+     *
+     * // using the `variable` option to ensure a with-statement isn't used in the compiled template
+     * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
+     * compiled.source;
+     * // => function(data) {
+     *   var __t, __p = '', __e = _.escape;
+     *   __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
+     *   return __p;
+     * }
+     *
+     * // using the `source` property to inline compiled templates for meaningful
+     * // line numbers in error messages and a stack trace
+     * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
+     *   var JST = {\
+     *     "main": ' + _.template(mainText).source + '\
+     *   };\
+     * ');
+     */
+    function template(text, data, options) {
+      // based on John Resig's `tmpl` implementation
+      // http://ejohn.org/blog/javascript-micro-templating/
+      // and Laura Doktorova's doT.js
+      // https://github.com/olado/doT
+      var settings = lodash.templateSettings;
+      text || (text = '');
+
+      // avoid missing dependencies when `iteratorTemplate` is not defined
+      options = defaults({}, options, settings);
+
+      var imports = defaults({}, options.imports, settings.imports),
+          importsKeys = keys(imports),
+          importsValues = values(imports);
+
+      var isEvaluating,
+          index = 0,
+          interpolate = options.interpolate || reNoMatch,
+          source = "__p += '";
+
+      // compile the regexp to match each delimiter
+      var reDelimiters = RegExp(
+        (options.escape || reNoMatch).source + '|' +
+        interpolate.source + '|' +
+        (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
+        (options.evaluate || reNoMatch).source + '|$'
+      , 'g');
+
+      text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
+        interpolateValue || (interpolateValue = esTemplateValue);
+
+        // escape characters that cannot be included in string literals
+        source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
+
+        // replace delimiters with snippets
+        if (escapeValue) {
+          source += "' +\n__e(" + escapeValue + ") +\n'";
+        }
+        if (evaluateValue) {
+          isEvaluating = true;
+          source += "';\n" + evaluateValue + ";\n__p += '";
+        }
+        if (interpolateValue) {
+          source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
+        }
+        index = offset + match.length;
+
+        // the JS engine embedded in Adobe products requires returning the `match`
+        // string in order to produce the correct `offset` value
+        return match;
+      });
+
+      source += "';\n";
+
+      // if `variable` is not specified, wrap a with-statement around the generated
+      // code to add the data object to the top of the scope chain
+      var variable = options.variable,
+          hasVariable = variable;
+
+      if (!hasVariable) {
+        variable = 'obj';
+        source = 'with (' + variable + ') {\n' + source + '\n}\n';
+      }
+      // cleanup code by stripping empty strings
+      source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
+        .replace(reEmptyStringMiddle, '$1')
+        .replace(reEmptyStringTrailing, '$1;');
+
+      // frame code as the function body
+      source = 'function(' + variable + ') {\n' +
+        (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
+        "var __t, __p = '', __e = _.escape" +
+        (isEvaluating
+          ? ', __j = Array.prototype.join;\n' +
+            "function print() { __p += __j.call(arguments, '') }\n"
+          : ';\n'
+        ) +
+        source +
+        'return __p\n}';
+
+      // Use a sourceURL for easier debugging.
+      // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
+      var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
+
+      try {
+        var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
+      } catch(e) {
+        e.source = source;
+        throw e;
+      }
+      if (data) {
+        return result(data);
+      }
+      // provide the compiled function's source by its `toString` method, in
+      // supported environments, or the `source` property as a convenience for
+      // inlining compiled templates during the build process
+      result.source = source;
+      return result;
+    }
+
+    /**
+     * Executes the callback `n` times, returning an array of the results
+     * of each callback execution. The callback is bound to `thisArg` and invoked
+     * with one argument; (index).
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {number} n The number of times to execute the callback.
+     * @param {Function} callback The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns an array of the results of each `callback` execution.
+     * @example
+     *
+     * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
+     * // => [3, 6, 4]
+     *
+     * _.times(3, function(n) { mage.castSpell(n); });
+     * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
+     *
+     * _.times(3, function(n) { this.cast(n); }, mage);
+     * // => also calls `mage.castSpell(n)` three times
+     */
+    function times(n, callback, thisArg) {
+      n = (n = +n) > -1 ? n : 0;
+      var index = -1,
+          result = Array(n);
+
+      callback = baseCreateCallback(callback, thisArg, 1);
+      while (++index < n) {
+        result[index] = callback(index);
+      }
+      return result;
+    }
+
+    /**
+     * The inverse of `_.escape` this method converts the HTML entities
+     * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their
+     * corresponding characters.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} string The string to unescape.
+     * @returns {string} Returns the unescaped string.
+     * @example
+     *
+     * _.unescape('Moe, Larry &amp; Curly');
+     * // => 'Moe, Larry & Curly'
+     */
+    function unescape(string) {
+      return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
+    }
+
+    /**
+     * Generates a unique ID. If `prefix` is provided the ID will be appended to it.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} [prefix] The value to prefix the ID with.
+     * @returns {string} Returns the unique ID.
+     * @example
+     *
+     * _.uniqueId('contact_');
+     * // => 'contact_104'
+     *
+     * _.uniqueId();
+     * // => '105'
+     */
+    function uniqueId(prefix) {
+      var id = ++idCounter;
+      return String(prefix == null ? '' : prefix) + id;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates a `lodash` object that wraps the given value with explicit
+     * method chaining enabled.
+     *
+     * @static
+     * @memberOf _
+     * @category Chaining
+     * @param {*} value The value to wrap.
+     * @returns {Object} Returns the wrapper object.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 },
+     *   { 'name': 'curly', 'age': 60 }
+     * ];
+     *
+     * var youngest = _.chain(stooges)
+     *     .sortBy('age')
+     *     .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
+     *     .first()
+     *     .value();
+     * // => 'moe is 40'
+     */
+    function chain(value) {
+      value = new lodashWrapper(value);
+      value.__chain__ = true;
+      return value;
+    }
+
+    /**
+     * Invokes `interceptor` with the `value` as the first argument and then
+     * returns `value`. The purpose of this method is to "tap into" a method
+     * chain in order to perform operations on intermediate results within
+     * the chain.
+     *
+     * @static
+     * @memberOf _
+     * @category Chaining
+     * @param {*} value The value to provide to `interceptor`.
+     * @param {Function} interceptor The function to invoke.
+     * @returns {*} Returns `value`.
+     * @example
+     *
+     * _([1, 2, 3, 4])
+     *  .filter(function(num) { return num % 2 == 0; })
+     *  .tap(function(array) { console.log(array); })
+     *  .map(function(num) { return num * num; })
+     *  .value();
+     * // => // [2, 4] (logged)
+     * // => [4, 16]
+     */
+    function tap(value, interceptor) {
+      interceptor(value);
+      return value;
+    }
+
+    /**
+     * Enables explicit method chaining on the wrapper object.
+     *
+     * @name chain
+     * @memberOf _
+     * @category Chaining
+     * @returns {*} Returns the wrapper object.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // without explicit chaining
+     * _(stooges).first();
+     * // => { 'name': 'moe', 'age': 40 }
+     *
+     * // with explicit chaining
+     * _(stooges).chain()
+     *   .first()
+     *   .pick('age')
+     *   .value()
+     * // => { 'age': 40 }
+     */
+    function wrapperChain() {
+      this.__chain__ = true;
+      return this;
+    }
+
+    /**
+     * Produces the `toString` result of the wrapped value.
+     *
+     * @name toString
+     * @memberOf _
+     * @category Chaining
+     * @returns {string} Returns the string result.
+     * @example
+     *
+     * _([1, 2, 3]).toString();
+     * // => '1,2,3'
+     */
+    function wrapperToString() {
+      return String(this.__wrapped__);
+    }
+
+    /**
+     * Extracts the wrapped value.
+     *
+     * @name valueOf
+     * @memberOf _
+     * @alias value
+     * @category Chaining
+     * @returns {*} Returns the wrapped value.
+     * @example
+     *
+     * _([1, 2, 3]).valueOf();
+     * // => [1, 2, 3]
+     */
+    function wrapperValueOf() {
+      return this.__wrapped__;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    // add functions that return wrapped values when chaining
+    lodash.after = after;
+    lodash.assign = assign;
+    lodash.at = at;
+    lodash.bind = bind;
+    lodash.bindAll = bindAll;
+    lodash.bindKey = bindKey;
+    lodash.chain = chain;
+    lodash.compact = compact;
+    lodash.compose = compose;
+    lodash.countBy = countBy;
+    lodash.createCallback = createCallback;
+    lodash.curry = curry;
+    lodash.debounce = debounce;
+    lodash.defaults = defaults;
+    lodash.defer = defer;
+    lodash.delay = delay;
+    lodash.difference = difference;
+    lodash.filter = filter;
+    lodash.flatten = flatten;
+    lodash.forEach = forEach;
+    lodash.forEachRight = forEachRight;
+    lodash.forIn = forIn;
+    lodash.forInRight = forInRight;
+    lodash.forOwn = forOwn;
+    lodash.forOwnRight = forOwnRight;
+    lodash.functions = functions;
+    lodash.groupBy = groupBy;
+    lodash.indexBy = indexBy;
+    lodash.initial = initial;
+    lodash.intersection = intersection;
+    lodash.invert = invert;
+    lodash.invoke = invoke;
+    lodash.keys = keys;
+    lodash.map = map;
+    lodash.max = max;
+    lodash.memoize = memoize;
+    lodash.merge = merge;
+    lodash.min = min;
+    lodash.omit = omit;
+    lodash.once = once;
+    lodash.pairs = pairs;
+    lodash.partial = partial;
+    lodash.partialRight = partialRight;
+    lodash.pick = pick;
+    lodash.pluck = pluck;
+    lodash.pull = pull;
+    lodash.range = range;
+    lodash.reject = reject;
+    lodash.remove = remove;
+    lodash.rest = rest;
+    lodash.shuffle = shuffle;
+    lodash.sortBy = sortBy;
+    lodash.tap = tap;
+    lodash.throttle = throttle;
+    lodash.times = times;
+    lodash.toArray = toArray;
+    lodash.transform = transform;
+    lodash.union = union;
+    lodash.uniq = uniq;
+    lodash.values = values;
+    lodash.where = where;
+    lodash.without = without;
+    lodash.wrap = wrap;
+    lodash.zip = zip;
+    lodash.zipObject = zipObject;
+
+    // add aliases
+    lodash.collect = map;
+    lodash.drop = rest;
+    lodash.each = forEach;
+    lodash.eachRight = forEachRight;
+    lodash.extend = assign;
+    lodash.methods = functions;
+    lodash.object = zipObject;
+    lodash.select = filter;
+    lodash.tail = rest;
+    lodash.unique = uniq;
+    lodash.unzip = zip;
+
+    // add functions to `lodash.prototype`
+    mixin(lodash);
+
+    /*--------------------------------------------------------------------------*/
+
+    // add functions that return unwrapped values when chaining
+    lodash.clone = clone;
+    lodash.cloneDeep = cloneDeep;
+    lodash.contains = contains;
+    lodash.escape = escape;
+    lodash.every = every;
+    lodash.find = find;
+    lodash.findIndex = findIndex;
+    lodash.findKey = findKey;
+    lodash.findLast = findLast;
+    lodash.findLastIndex = findLastIndex;
+    lodash.findLastKey = findLastKey;
+    lodash.has = has;
+    lodash.identity = identity;
+    lodash.indexOf = indexOf;
+    lodash.isArguments = isArguments;
+    lodash.isArray = isArray;
+    lodash.isBoolean = isBoolean;
+    lodash.isDate = isDate;
+    lodash.isElement = isElement;
+    lodash.isEmpty = isEmpty;
+    lodash.isEqual = isEqual;
+    lodash.isFinite = isFinite;
+    lodash.isFunction = isFunction;
+    lodash.isNaN = isNaN;
+    lodash.isNull = isNull;
+    lodash.isNumber = isNumber;
+    lodash.isObject = isObject;
+    lodash.isPlainObject = isPlainObject;
+    lodash.isRegExp = isRegExp;
+    lodash.isString = isString;
+    lodash.isUndefined = isUndefined;
+    lodash.lastIndexOf = lastIndexOf;
+    lodash.mixin = mixin;
+    lodash.noConflict = noConflict;
+    lodash.parseInt = parseInt;
+    lodash.random = random;
+    lodash.reduce = reduce;
+    lodash.reduceRight = reduceRight;
+    lodash.result = result;
+    lodash.runInContext = runInContext;
+    lodash.size = size;
+    lodash.some = some;
+    lodash.sortedIndex = sortedIndex;
+    lodash.template = template;
+    lodash.unescape = unescape;
+    lodash.uniqueId = uniqueId;
+
+    // add aliases
+    lodash.all = every;
+    lodash.any = some;
+    lodash.detect = find;
+    lodash.findWhere = find;
+    lodash.foldl = reduce;
+    lodash.foldr = reduceRight;
+    lodash.include = contains;
+    lodash.inject = reduce;
+
+    forOwn(lodash, function(func, methodName) {
+      if (!lodash.prototype[methodName]) {
+        lodash.prototype[methodName] = function() {
+          var args = [this.__wrapped__],
+              chainAll = this.__chain__;
+
+          push.apply(args, arguments);
+          var result = func.apply(lodash, args);
+          return chainAll
+            ? new lodashWrapper(result, chainAll)
+            : result;
+        };
+      }
+    });
+
+    /*--------------------------------------------------------------------------*/
+
+    // add functions capable of returning wrapped and unwrapped values when chaining
+    lodash.first = first;
+    lodash.last = last;
+    lodash.sample = sample;
+
+    // add aliases
+    lodash.take = first;
+    lodash.head = first;
+
+    forOwn(lodash, function(func, methodName) {
+      var callbackable = methodName !== 'sample';
+      if (!lodash.prototype[methodName]) {
+        lodash.prototype[methodName]= function(n, guard) {
+          var chainAll = this.__chain__,
+              result = func(this.__wrapped__, n, guard);
+
+          return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
+            ? result
+            : new lodashWrapper(result, chainAll);
+        };
+      }
+    });
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * The semantic version number.
+     *
+     * @static
+     * @memberOf _
+     * @type string
+     */
+    lodash.VERSION = '2.2.1';
+
+    // add "Chaining" functions to the wrapper
+    lodash.prototype.chain = wrapperChain;
+    lodash.prototype.toString = wrapperToString;
+    lodash.prototype.value = wrapperValueOf;
+    lodash.prototype.valueOf = wrapperValueOf;
+
+    // add `Array` functions that return unwrapped values
+    forEach(['join', 'pop', 'shift'], function(methodName) {
+      var func = arrayRef[methodName];
+      lodash.prototype[methodName] = function() {
+        var chainAll = this.__chain__,
+            result = func.apply(this.__wrapped__, arguments);
+
+        return chainAll
+          ? new lodashWrapper(result, chainAll)
+          : result;
+      };
+    });
+
+    // add `Array` functions that return the wrapped value
+    forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
+      var func = arrayRef[methodName];
+      lodash.prototype[methodName] = function() {
+        func.apply(this.__wrapped__, arguments);
+        return this;
+      };
+    });
+
+    // add `Array` functions that return new wrapped values
+    forEach(['concat', 'slice', 'splice'], function(methodName) {
+      var func = arrayRef[methodName];
+      lodash.prototype[methodName] = function() {
+        return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
+      };
+    });
+
+    return lodash;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  // expose Lo-Dash
+  var _ = runInContext();
+
+  // some AMD build optimizers, like r.js, check for condition patterns like the following:
+  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
+    // Expose Lo-Dash to the global object even when an AMD loader is present in
+    // case Lo-Dash was injected by a third-party script and not intended to be
+    // loaded as a module. The global assignment can be reverted in the Lo-Dash
+    // module by its `noConflict()` method.
+    root._ = _;
+
+    // define as an anonymous module so, through path mapping, it can be
+    // referenced as the "underscore" module
+    define(function() {
+      return _;
+    });
+  }
+  // check for `exports` after `define` in case a build optimizer adds an `exports` object
+  else if (freeExports && freeModule) {
+    // in Node.js or RingoJS
+    if (moduleExports) {
+      (freeModule.exports = _)._ = _;
+    }
+    // in Narwhal or Rhino -require
+    else {
+      freeExports._ = _;
+    }
+  }
+  else {
+    // in a browser or Rhino
+    root._ = _;
+  }
+}.call(this));
+
+//     Backbone.js 1.0.0
+
+//     (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
+//     Backbone may be freely distributed under the MIT license.
+//     For all details and documentation:
+//     http://backbonejs.org
+
+(function(){
+
+  // Initial Setup
+  // -------------
+
+  // Save a reference to the global object (`window` in the browser, `exports`
+  // on the server).
+  var root = this;
+
+  // Save the previous value of the `Backbone` variable, so that it can be
+  // restored later on, if `noConflict` is used.
+  var previousBackbone = root.Backbone;
+
+  // Create local references to array methods we'll want to use later.
+  var array = [];
+  var push = array.push;
+  var slice = array.slice;
+  var splice = array.splice;
+
+  // The top-level namespace. All public Backbone classes and modules will
+  // be attached to this. Exported for both the browser and the server.
+  var Backbone;
+  if (typeof exports !== 'undefined') {
+    Backbone = exports;
+  } else {
+    Backbone = root.Backbone = {};
+  }
+
+  // Current version of the library. Keep in sync with `package.json`.
+  Backbone.VERSION = '1.0.0';
+
+  // Require Underscore, if we're on the server, and it's not already present.
+  var _ = root._;
+  if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
+
+  // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
+  // the `$` variable.
+  Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
+
+  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
+  // to its previous owner. Returns a reference to this Backbone object.
+  Backbone.noConflict = function() {
+    root.Backbone = previousBackbone;
+    return this;
+  };
+
+  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
+  // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
+  // set a `X-Http-Method-Override` header.
+  Backbone.emulateHTTP = false;
+
+  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
+  // `application/json` requests ... will encode the body as
+  // `application/x-www-form-urlencoded` instead and will send the model in a
+  // form param named `model`.
+  Backbone.emulateJSON = false;
+
+  // Backbone.Events
+  // ---------------
+
+  // A module that can be mixed in to *any object* in order to provide it with
+  // custom events. You may bind with `on` or remove with `off` callback
+  // functions to an event; `trigger`-ing an event fires all callbacks in
+  // succession.
+  //
+  //     var object = {};
+  //     _.extend(object, Backbone.Events);
+  //     object.on('expand', function(){ alert('expanded'); });
+  //     object.trigger('expand');
+  //
+  var Events = Backbone.Events = {
+
+    // Bind an event to a `callback` function. Passing `"all"` will bind
+    // the callback to all events fired.
+    on: function(name, callback, context) {
+      if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
+      this._events || (this._events = {});
+      var events = this._events[name] || (this._events[name] = []);
+      events.push({callback: callback, context: context, ctx: context || this});
+      return this;
+    },
+
+    // Bind an event to only be triggered a single time. After the first time
+    // the callback is invoked, it will be removed.
+    once: function(name, callback, context) {
+      if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
+      var self = this;
+      var once = _.once(function() {
+        self.off(name, once);
+        callback.apply(this, arguments);
+      });
+      once._callback = callback;
+      return this.on(name, once, context);
+    },
+
+    // Remove one or many callbacks. If `context` is null, removes all
+    // callbacks with that function. If `callback` is null, removes all
+    // callbacks for the event. If `name` is null, removes all bound
+    // callbacks for all events.
+    off: function(name, callback, context) {
+      var retain, ev, events, names, i, l, j, k;
+      if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
+      if (!name && !callback && !context) {
+        this._events = {};
+        return this;
+      }
+
+      names = name ? [name] : _.keys(this._events);
+      for (i = 0, l = names.length; i < l; i++) {
+        name = names[i];
+        if (events = this._events[name]) {
+          this._events[name] = retain = [];
+          if (callback || context) {
+            for (j = 0, k = events.length; j < k; j++) {
+              ev = events[j];
+              if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
+                  (context && context !== ev.context)) {
+                retain.push(ev);
+              }
+            }
+          }
+          if (!retain.length) delete this._events[name];
+        }
+      }
+
+      return this;
+    },
+
+    // Trigger one or many events, firing all bound callbacks. Callbacks are
+    // passed the same arguments as `trigger` is, apart from the event name
+    // (unless you're listening on `"all"`, which will cause your callback to
+    // receive the true name of the event as the first argument).
+    trigger: function(name) {
+      if (!this._events) return this;
+      var args = slice.call(arguments, 1);
+      if (!eventsApi(this, 'trigger', name, args)) return this;
+      var events = this._events[name];
+      var allEvents = this._events.all;
+      if (events) triggerEvents(events, args);
+      if (allEvents) triggerEvents(allEvents, arguments);
+      return this;
+    },
+
+    // Tell this object to stop listening to either specific events ... or
+    // to every object it's currently listening to.
+    stopListening: function(obj, name, callback) {
+      var listeners = this._listeners;
+      if (!listeners) return this;
+      var deleteListener = !name && !callback;
+      if (typeof name === 'object') callback = this;
+      if (obj) (listeners = {})[obj._listenerId] = obj;
+      for (var id in listeners) {
+        listeners[id].off(name, callback, this);
+        if (deleteListener) delete this._listeners[id];
+      }
+      return this;
+    }
+
+  };
+
+  // Regular expression used to split event strings.
+  var eventSplitter = /\s+/;
+
+  // Implement fancy features of the Events API such as multiple event
+  // names `"change blur"` and jQuery-style event maps `{change: action}`
+  // in terms of the existing API.
+  var eventsApi = function(obj, action, name, rest) {
+    if (!name) return true;
+
+    // Handle event maps.
+    if (typeof name === 'object') {
+      for (var key in name) {
+        obj[action].apply(obj, [key, name[key]].concat(rest));
+      }
+      return false;
+    }
+
+    // Handle space separated event names.
+    if (eventSplitter.test(name)) {
+      var names = name.split(eventSplitter);
+      for (var i = 0, l = names.length; i < l; i++) {
+        obj[action].apply(obj, [names[i]].concat(rest));
+      }
+      return false;
+    }
+
+    return true;
+  };
+
+  // A difficult-to-believe, but optimized internal dispatch function for
+  // triggering events. Tries to keep the usual cases speedy (most internal
+  // Backbone events have 3 arguments).
+  var triggerEvents = function(events, args) {
+    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
+    switch (args.length) {
+      case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
+      case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
+      case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
+      case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
+      default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
+    }
+  };
+
+  var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
+
+  // Inversion-of-control versions of `on` and `once`. Tell *this* object to
+  // listen to an event in another object ... keeping track of what it's
+  // listening to.
+  _.each(listenMethods, function(implementation, method) {
+    Events[method] = function(obj, name, callback) {
+      var listeners = this._listeners || (this._listeners = {});
+      var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
+      listeners[id] = obj;
+      if (typeof name === 'object') callback = this;
+      obj[implementation](name, callback, this);
+      return this;
+    };
+  });
+
+  // Aliases for backwards compatibility.
+  Events.bind   = Events.on;
+  Events.unbind = Events.off;
+
+  // Allow the `Backbone` object to serve as a global event bus, for folks who
+  // want global "pubsub" in a convenient place.
+  _.extend(Backbone, Events);
+
+  // Backbone.Model
+  // --------------
+
+  // Backbone **Models** are the basic data object in the framework --
+  // frequently representing a row in a table in a database on your server.
+  // A discrete chunk of data and a bunch of useful, related methods for
+  // performing computations and transformations on that data.
+
+  // Create a new model with the specified attributes. A client id (`cid`)
+  // is automatically generated and assigned for you.
+  var Model = Backbone.Model = function(attributes, options) {
+    var defaults;
+    var attrs = attributes || {};
+    options || (options = {});
+    this.cid = _.uniqueId('c');
+    this.attributes = {};
+    _.extend(this, _.pick(options, modelOptions));
+    if (options.parse) attrs = this.parse(attrs, options) || {};
+    if (defaults = _.result(this, 'defaults')) {
+      attrs = _.defaults({}, attrs, defaults);
+    }
+    this.set(attrs, options);
+    this.changed = {};
+    this.initialize.apply(this, arguments);
+  };
+
+  // A list of options to be attached directly to the model, if provided.
+  var modelOptions = ['url', 'urlRoot', 'collection'];
+
+  // Attach all inheritable methods to the Model prototype.
+  _.extend(Model.prototype, Events, {
+
+    // A hash of attributes whose current and previous value differ.
+    changed: null,
+
+    // The value returned during the last failed validation.
+    validationError: null,
+
+    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
+    // CouchDB users may want to set this to `"_id"`.
+    idAttribute: 'id',
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // Return a copy of the model's `attributes` object.
+    toJSON: function(options) {
+      return _.clone(this.attributes);
+    },
+
+    // Proxy `Backbone.sync` by default -- but override this if you need
+    // custom syncing semantics for *this* particular model.
+    sync: function() {
+      return Backbone.sync.apply(this, arguments);
+    },
+
+    // Get the value of an attribute.
+    get: function(attr) {
+      return this.attributes[attr];
+    },
+
+    // Get the HTML-escaped value of an attribute.
+    escape: function(attr) {
+      return _.escape(this.get(attr));
+    },
+
+    // Returns `true` if the attribute contains a value that is not null
+    // or undefined.
+    has: function(attr) {
+      return this.get(attr) != null;
+    },
+
+    // Set a hash of model attributes on the object, firing `"change"`. This is
+    // the core primitive operation of a model, updating the data and notifying
+    // anyone who needs to know about the change in state. The heart of the beast.
+    set: function(key, val, options) {
+      var attr, attrs, unset, changes, silent, changing, prev, current;
+      if (key == null) return this;
+
+      // Handle both `"key", value` and `{key: value}` -style arguments.
+      if (typeof key === 'object') {
+        attrs = key;
+        options = val;
+      } else {
+        (attrs = {})[key] = val;
+      }
+
+      options || (options = {});
+
+      // Run validation.
+      if (!this._validate(attrs, options)) return false;
+
+      // Extract attributes and options.
+      unset           = options.unset;
+      silent          = options.silent;
+      changes         = [];
+      changing        = this._changing;
+      this._changing  = true;
+
+      if (!changing) {
+        this._previousAttributes = _.clone(this.attributes);
+        this.changed = {};
+      }
+      current = this.attributes, prev = this._previousAttributes;
+
+      // Check for changes of `id`.
+      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
+
+      // For each `set` attribute, update or delete the current value.
+      for (attr in attrs) {
+        val = attrs[attr];
+        if (!_.isEqual(current[attr], val)) changes.push(attr);
+        if (!_.isEqual(prev[attr], val)) {
+          this.changed[attr] = val;
+        } else {
+          delete this.changed[attr];
+        }
+        unset ? delete current[attr] : current[attr] = val;
+      }
+
+      // Trigger all relevant attribute changes.
+      if (!silent) {
+        if (changes.length) this._pending = true;
+        for (var i = 0, l = changes.length; i < l; i++) {
+          this.trigger('change:' + changes[i], this, current[changes[i]], options);
+        }
+      }
+
+      // You might be wondering why there's a `while` loop here. Changes can
+      // be recursively nested within `"change"` events.
+      if (changing) return this;
+      if (!silent) {
+        while (this._pending) {
+          this._pending = false;
+          this.trigger('change', this, options);
+        }
+      }
+      this._pending = false;
+      this._changing = false;
+      return this;
+    },
+
+    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
+    // if the attribute doesn't exist.
+    unset: function(attr, options) {
+      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
+    },
+
+    // Clear all attributes on the model, firing `"change"`.
+    clear: function(options) {
+      var attrs = {};
+      for (var key in this.attributes) attrs[key] = void 0;
+      return this.set(attrs, _.extend({}, options, {unset: true}));
+    },
+
+    // Determine if the model has changed since the last `"change"` event.
+    // If you specify an attribute name, determine if that attribute has changed.
+    hasChanged: function(attr) {
+      if (attr == null) return !_.isEmpty(this.changed);
+      return _.has(this.changed, attr);
+    },
+
+    // Return an object containing all the attributes that have changed, or
+    // false if there are no changed attributes. Useful for determining what
+    // parts of a view need to be updated and/or what attributes need to be
+    // persisted to the server. Unset attributes will be set to undefined.
+    // You can also pass an attributes object to diff against the model,
+    // determining if there *would be* a change.
+    changedAttributes: function(diff) {
+      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
+      var val, changed = false;
+      var old = this._changing ? this._previousAttributes : this.attributes;
+      for (var attr in diff) {
+        if (_.isEqual(old[attr], (val = diff[attr]))) continue;
+        (changed || (changed = {}))[attr] = val;
+      }
+      return changed;
+    },
+
+    // Get the previous value of an attribute, recorded at the time the last
+    // `"change"` event was fired.
+    previous: function(attr) {
+      if (attr == null || !this._previousAttributes) return null;
+      return this._previousAttributes[attr];
+    },
+
+    // Get all of the attributes of the model at the time of the previous
+    // `"change"` event.
+    previousAttributes: function() {
+      return _.clone(this._previousAttributes);
+    },
+
+    // Fetch the model from the server. If the server's representation of the
+    // model differs from its current attributes, they will be overridden,
+    // triggering a `"change"` event.
+    fetch: function(options) {
+      options = options ? _.clone(options) : {};
+      if (options.parse === void 0) options.parse = true;
+      var model = this;
+      var success = options.success;
+      options.success = function(resp) {
+        if (!model.set(model.parse(resp, options), options)) return false;
+        if (success) success(model, resp, options);
+        model.trigger('sync', model, resp, options);
+      };
+      wrapError(this, options);
+      return this.sync('read', this, options);
+    },
+
+    // Set a hash of model attributes, and sync the model to the server.
+    // If the server returns an attributes hash that differs, the model's
+    // state will be `set` again.
+    save: function(key, val, options) {
+      var attrs, method, xhr, attributes = this.attributes;
+
+      // Handle both `"key", value` and `{key: value}` -style arguments.
+      if (key == null || typeof key === 'object') {
+        attrs = key;
+        options = val;
+      } else {
+        (attrs = {})[key] = val;
+      }
+
+      // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
+      if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
+
+      options = _.extend({validate: true}, options);
+
+      // Do not persist invalid models.
+      if (!this._validate(attrs, options)) return false;
+
+      // Set temporary attributes if `{wait: true}`.
+      if (attrs && options.wait) {
+        this.attributes = _.extend({}, attributes, attrs);
+      }
+
+      // After a successful server-side save, the client is (optionally)
+      // updated with the server-side state.
+      if (options.parse === void 0) options.parse = true;
+      var model = this;
+      var success = options.success;
+      options.success = function(resp) {
+        // Ensure attributes are restored during synchronous saves.
+        model.attributes = attributes;
+        var serverAttrs = model.parse(resp, options);
+        if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
+        if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
+          return false;
+        }
+        if (success) success(model, resp, options);
+        model.trigger('sync', model, resp, options);
+      };
+      wrapError(this, options);
+
+      method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
+      if (method === 'patch') options.attrs = attrs;
+      xhr = this.sync(method, this, options);
+
+      // Restore attributes.
+      if (attrs && options.wait) this.attributes = attributes;
+
+      return xhr;
+    },
+
+    // Destroy this model on the server if it was already persisted.
+    // Optimistically removes the model from its collection, if it has one.
+    // If `wait: true` is passed, waits for the server to respond before removal.
+    destroy: function(options) {
+      options = options ? _.clone(options) : {};
+      var model = this;
+      var success = options.success;
+
+      var destroy = function() {
+        model.trigger('destroy', model, model.collection, options);
+      };
+
+      options.success = function(resp) {
+        if (options.wait || model.isNew()) destroy();
+        if (success) success(model, resp, options);
+        if (!model.isNew()) model.trigger('sync', model, resp, options);
+      };
+
+      if (this.isNew()) {
+        options.success();
+        return false;
+      }
+      wrapError(this, options);
+
+      var xhr = this.sync('delete', this, options);
+      if (!options.wait) destroy();
+      return xhr;
+    },
+
+    // Default URL for the model's representation on the server -- if you're
+    // using Backbone's restful methods, override this to change the endpoint
+    // that will be called.
+    url: function() {
+      var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
+      if (this.isNew()) return base;
+      return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
+    },
+
+    // **parse** converts a response into the hash of attributes to be `set` on
+    // the model. The default implementation is just to pass the response along.
+    parse: function(resp, options) {
+      return resp;
+    },
+
+    // Create a new model with identical attributes to this one.
+    clone: function() {
+      return new this.constructor(this.attributes);
+    },
+
+    // A model is new if it has never been saved to the server, and lacks an id.
+    isNew: function() {
+      return this.id == null;
+    },
+
+    // Check if the model is currently in a valid state.
+    isValid: function(options) {
+      return this._validate({}, _.extend(options || {}, { validate: true }));
+    },
+
+    // Run validation against the next complete set of model attributes,
+    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
+    _validate: function(attrs, options) {
+      if (!options.validate || !this.validate) return true;
+      attrs = _.extend({}, this.attributes, attrs);
+      var error = this.validationError = this.validate(attrs, options) || null;
+      if (!error) return true;
+      this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
+      return false;
+    }
+
+  });
+
+  // Underscore methods that we want to implement on the Model.
+  var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
+
+  // Mix in each Underscore method as a proxy to `Model#attributes`.
+  _.each(modelMethods, function(method) {
+    Model.prototype[method] = function() {
+      var args = slice.call(arguments);
+      args.unshift(this.attributes);
+      return _[method].apply(_, args);
+    };
+  });
+
+  // Backbone.Collection
+  // -------------------
+
+  // If models tend to represent a single row of data, a Backbone Collection is
+  // more analagous to a table full of data ... or a small slice or page of that
+  // table, or a collection of rows that belong together for a particular reason
+  // -- all of the messages in this particular folder, all of the documents
+  // belonging to this particular author, and so on. Collections maintain
+  // indexes of their models, both in order, and for lookup by `id`.
+
+  // Create a new **Collection**, perhaps to contain a specific type of `model`.
+  // If a `comparator` is specified, the Collection will maintain
+  // its models in sort order, as they're added and removed.
+  var Collection = Backbone.Collection = function(models, options) {
+    options || (options = {});
+    if (options.url) this.url = options.url;
+    if (options.model) this.model = options.model;
+    if (options.comparator !== void 0) this.comparator = options.comparator;
+    this._reset();
+    this.initialize.apply(this, arguments);
+    if (models) this.reset(models, _.extend({silent: true}, options));
+  };
+
+  // Default options for `Collection#set`.
+  var setOptions = {add: true, remove: true, merge: true};
+  var addOptions = {add: true, merge: false, remove: false};
+
+  // Define the Collection's inheritable methods.
+  _.extend(Collection.prototype, Events, {
+
+    // The default model for a collection is just a **Backbone.Model**.
+    // This should be overridden in most cases.
+    model: Model,
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // The JSON representation of a Collection is an array of the
+    // models' attributes.
+    toJSON: function(options) {
+      return this.map(function(model){ return model.toJSON(options); });
+    },
+
+    // Proxy `Backbone.sync` by default.
+    sync: function() {
+      return Backbone.sync.apply(this, arguments);
+    },
+
+    // Add a model, or list of models to the set.
+    add: function(models, options) {
+      return this.set(models, _.defaults(options || {}, addOptions));
+    },
+
+    // Remove a model, or a list of models from the set.
+    remove: function(models, options) {
+      models = _.isArray(models) ? models.slice() : [models];
+      options || (options = {});
+      var i, l, index, model;
+      for (i = 0, l = models.length; i < l; i++) {
+        model = this.get(models[i]);
+        if (!model) continue;
+        delete this._byId[model.id];
+        delete this._byId[model.cid];
+        index = this.indexOf(model);
+        this.models.splice(index, 1);
+        this.length--;
+        if (!options.silent) {
+          options.index = index;
+          model.trigger('remove', model, this, options);
+        }
+        this._removeReference(model);
+      }
+      return this;
+    },
+
+    // Update a collection by `set`-ing a new list of models, adding new ones,
+    // removing models that are no longer present, and merging models that
+    // already exist in the collection, as necessary. Similar to **Model#set**,
+    // the core operation for updating the data contained by the collection.
+    set: function(models, options) {
+      options = _.defaults(options || {}, setOptions);
+      if (options.parse) models = this.parse(models, options);
+      if (!_.isArray(models)) models = models ? [models] : [];
+      var i, l, model, attrs, existing, sort;
+      var at = options.at;
+      var sortable = this.comparator && (at == null) && options.sort !== false;
+      var sortAttr = _.isString(this.comparator) ? this.comparator : null;
+      var toAdd = [], toRemove = [], modelMap = {};
+
+      // Turn bare objects into model references, and prevent invalid models
+      // from being added.
+      for (i = 0, l = models.length; i < l; i++) {
+        if (!(model = this._prepareModel(models[i], options))) continue;
+
+        // If a duplicate is found, prevent it from being added and
+        // optionally merge it into the existing model.
+        if (existing = this.get(model)) {
+          if (options.remove) modelMap[existing.cid] = true;
+          if (options.merge) {
+            existing.set(model.attributes, options);
+            if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
+          }
+
+        // This is a new model, push it to the `toAdd` list.
+        } else if (options.add) {
+          toAdd.push(model);
+
+          // Listen to added models' events, and index models for lookup by
+          // `id` and by `cid`.
+          model.on('all', this._onModelEvent, this);
+          this._byId[model.cid] = model;
+          if (model.id != null) this._byId[model.id] = model;
+        }
+      }
+
+      // Remove nonexistent models if appropriate.
+      if (options.remove) {
+        for (i = 0, l = this.length; i < l; ++i) {
+          if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
+        }
+        if (toRemove.length) this.remove(toRemove, options);
+      }
+
+      // See if sorting is needed, update `length` and splice in new models.
+      if (toAdd.length) {
+        if (sortable) sort = true;
+        this.length += toAdd.length;
+        if (at != null) {
+          splice.apply(this.models, [at, 0].concat(toAdd));
+        } else {
+          push.apply(this.models, toAdd);
+        }
+      }
+
+      // Silently sort the collection if appropriate.
+      if (sort) this.sort({silent: true});
+
+      if (options.silent) return this;
+
+      // Trigger `add` events.
+      for (i = 0, l = toAdd.length; i < l; i++) {
+        (model = toAdd[i]).trigger('add', model, this, options);
+      }
+
+      // Trigger `sort` if the collection was sorted.
+      if (sort) this.trigger('sort', this, options);
+      return this;
+    },
+
+    // When you have more items than you want to add or remove individually,
+    // you can reset the entire set with a new list of models, without firing
+    // any granular `add` or `remove` events. Fires `reset` when finished.
+    // Useful for bulk operations and optimizations.
+    reset: function(models, options) {
+      options || (options = {});
+      for (var i = 0, l = this.models.length; i < l; i++) {
+        this._removeReference(this.models[i]);
+      }
+      options.previousModels = this.models;
+      this._reset();
+      this.add(models, _.extend({silent: true}, options));
+      if (!options.silent) this.trigger('reset', this, options);
+      return this;
+    },
+
+    // Add a model to the end of the collection.
+    push: function(model, options) {
+      model = this._prepareModel(model, options);
+      this.add(model, _.extend({at: this.length}, options));
+      return model;
+    },
+
+    // Remove a model from the end of the collection.
+    pop: function(options) {
+      var model = this.at(this.length - 1);
+      this.remove(model, options);
+      return model;
+    },
+
+    // Add a model to the beginning of the collection.
+    unshift: function(model, options) {
+      model = this._prepareModel(model, options);
+      this.add(model, _.extend({at: 0}, options));
+      return model;
+    },
+
+    // Remove a model from the beginning of the collection.
+    shift: function(options) {
+      var model = this.at(0);
+      this.remove(model, options);
+      return model;
+    },
+
+    // Slice out a sub-array of models from the collection.
+    slice: function(begin, end) {
+      return this.models.slice(begin, end);
+    },
+
+    // Get a model from the set by id.
+    get: function(obj) {
+      if (obj == null) return void 0;
+      return this._byId[obj.id != null ? obj.id : obj.cid || obj];
+    },
+
+    // Get the model at the given index.
+    at: function(index) {
+      return this.models[index];
+    },
+
+    // Return models with matching attributes. Useful for simple cases of
+    // `filter`.
+    where: function(attrs, first) {
+      if (_.isEmpty(attrs)) return first ? void 0 : [];
+      return this[first ? 'find' : 'filter'](function(model) {
+        for (var key in attrs) {
+          if (attrs[key] !== model.get(key)) return false;
+        }
+        return true;
+      });
+    },
+
+    // Return the first model with matching attributes. Useful for simple cases
+    // of `find`.
+    findWhere: function(attrs) {
+      return this.where(attrs, true);
+    },
+
+    // Force the collection to re-sort itself. You don't need to call this under
+    // normal circumstances, as the set will maintain sort order as each item
+    // is added.
+    sort: function(options) {
+      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
+      options || (options = {});
+
+      // Run sort based on type of `comparator`.
+      if (_.isString(this.comparator) || this.comparator.length === 1) {
+        this.models = this.sortBy(this.comparator, this);
+      } else {
+        this.models.sort(_.bind(this.comparator, this));
+      }
+
+      if (!options.silent) this.trigger('sort', this, options);
+      return this;
+    },
+
+    // Figure out the smallest index at which a model should be inserted so as
+    // to maintain order.
+    sortedIndex: function(model, value, context) {
+      value || (value = this.comparator);
+      var iterator = _.isFunction(value) ? value : function(model) {
+        return model.get(value);
+      };
+      return _.sortedIndex(this.models, model, iterator, context);
+    },
+
+    // Pluck an attribute from each model in the collection.
+    pluck: function(attr) {
+      return _.invoke(this.models, 'get', attr);
+    },
+
+    // Fetch the default set of models for this collection, resetting the
+    // collection when they arrive. If `reset: true` is passed, the response
+    // data will be passed through the `reset` method instead of `set`.
+    fetch: function(options) {
+      options = options ? _.clone(options) : {};
+      if (options.parse === void 0) options.parse = true;
+      var success = options.success;
+      var collection = this;
+      options.success = function(resp) {
+        var method = options.reset ? 'reset' : 'set';
+        collection[method](resp, options);
+        if (success) success(collection, resp, options);
+        collection.trigger('sync', collection, resp, options);
+      };
+      wrapError(this, options);
+      return this.sync('read', this, options);
+    },
+
+    // Create a new instance of a model in this collection. Add the model to the
+    // collection immediately, unless `wait: true` is passed, in which case we
+    // wait for the server to agree.
+    create: function(model, options) {
+      options = options ? _.clone(options) : {};
+      if (!(model = this._prepareModel(model, options))) return false;
+      if (!options.wait) this.add(model, options);
+      var collection = this;
+      var success = options.success;
+      options.success = function(resp) {
+        if (options.wait) collection.add(model, options);
+        if (success) success(model, resp, options);
+      };
+      model.save(null, options);
+      return model;
+    },
+
+    // **parse** converts a response into a list of models to be added to the
+    // collection. The default implementation is just to pass it through.
+    parse: function(resp, options) {
+      return resp;
+    },
+
+    // Create a new collection with an identical list of models as this one.
+    clone: function() {
+      return new this.constructor(this.models);
+    },
+
+    // Private method to reset all internal state. Called when the collection
+    // is first initialized or reset.
+    _reset: function() {
+      this.length = 0;
+      this.models = [];
+      this._byId  = {};
+    },
+
+    // Prepare a hash of attributes (or other model) to be added to this
+    // collection.
+    _prepareModel: function(attrs, options) {
+      if (attrs instanceof Model) {
+        if (!attrs.collection) attrs.collection = this;
+        return attrs;
+      }
+      options || (options = {});
+      options.collection = this;
+      var model = new this.model(attrs, options);
+      if (!model._validate(attrs, options)) {
+        this.trigger('invalid', this, attrs, options);
+        return false;
+      }
+      return model;
+    },
+
+    // Internal method to sever a model's ties to a collection.
+    _removeReference: function(model) {
+      if (this === model.collection) delete model.collection;
+      model.off('all', this._onModelEvent, this);
+    },
+
+    // Internal method called every time a model in the set fires an event.
+    // Sets need to update their indexes when models change ids. All other
+    // events simply proxy through. "add" and "remove" events that originate
+    // in other collections are ignored.
+    _onModelEvent: function(event, model, collection, options) {
+      if ((event === 'add' || event === 'remove') && collection !== this) return;
+      if (event === 'destroy') this.remove(model, options);
+      if (model && event === 'change:' + model.idAttribute) {
+        delete this._byId[model.previous(model.idAttribute)];
+        if (model.id != null) this._byId[model.id] = model;
+      }
+      this.trigger.apply(this, arguments);
+    }
+
+  });
+
+  // Underscore methods that we want to implement on the Collection.
+  // 90% of the core usefulness of Backbone Collections is actually implemented
+  // right here:
+  var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
+    'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
+    'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
+    'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
+    'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
+    'isEmpty', 'chain'];
+
+  // Mix in each Underscore method as a proxy to `Collection#models`.
+  _.each(methods, function(method) {
+    Collection.prototype[method] = function() {
+      var args = slice.call(arguments);
+      args.unshift(this.models);
+      return _[method].apply(_, args);
+    };
+  });
+
+  // Underscore methods that take a property name as an argument.
+  var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
+
+  // Use attributes instead of properties.
+  _.each(attributeMethods, function(method) {
+    Collection.prototype[method] = function(value, context) {
+      var iterator = _.isFunction(value) ? value : function(model) {
+        return model.get(value);
+      };
+      return _[method](this.models, iterator, context);
+    };
+  });
+
+  // Backbone.View
+  // -------------
+
+  // Backbone Views are almost more convention than they are actual code. A View
+  // is simply a JavaScript object that represents a logical chunk of UI in the
+  // DOM. This might be a single item, an entire list, a sidebar or panel, or
+  // even the surrounding frame which wraps your whole app. Defining a chunk of
+  // UI as a **View** allows you to define your DOM events declaratively, without
+  // having to worry about render order ... and makes it easy for the view to
+  // react to specific changes in the state of your models.
+
+  // Creating a Backbone.View creates its initial element outside of the DOM,
+  // if an existing element is not provided...
+  var View = Backbone.View = function(options) {
+    this.cid = _.uniqueId('view');
+    this._configure(options || {});
+    this._ensureElement();
+    this.initialize.apply(this, arguments);
+    this.delegateEvents();
+  };
+
+  // Cached regex to split keys for `delegate`.
+  var delegateEventSplitter = /^(\S+)\s*(.*)$/;
+
+  // List of view options to be merged as properties.
+  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
+
+  // Set up all inheritable **Backbone.View** properties and methods.
+  _.extend(View.prototype, Events, {
+
+    // The default `tagName` of a View's element is `"div"`.
+    tagName: 'div',
+
+    // jQuery delegate for element lookup, scoped to DOM elements within the
+    // current view. This should be prefered to global lookups where possible.
+    $: function(selector) {
+      return this.$el.find(selector);
+    },
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // **render** is the core function that your view should override, in order
+    // to populate its element (`this.el`), with the appropriate HTML. The
+    // convention is for **render** to always return `this`.
+    render: function() {
+      return this;
+    },
+
+    // Remove this view by taking the element out of the DOM, and removing any
+    // applicable Backbone.Events listeners.
+    remove: function() {
+      this.$el.remove();
+      this.stopListening();
+      return this;
+    },
+
+    // Change the view's element (`this.el` property), including event
+    // re-delegation.
+    setElement: function(element, delegate) {
+      if (this.$el) this.undelegateEvents();
+      this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
+      this.el = this.$el[0];
+      if (delegate !== false) this.delegateEvents();
+      return this;
+    },
+
+    // Set callbacks, where `this.events` is a hash of
+    //
+    // *{"event selector": "callback"}*
+    //
+    //     {
+    //       'mousedown .title':  'edit',
+    //       'click .button':     'save'
+    //       'click .open':       function(e) { ... }
+    //     }
+    //
+    // pairs. Callbacks will be bound to the view, with `this` set properly.
+    // Uses event delegation for efficiency.
+    // Omitting the selector binds the event to `this.el`.
+    // This only works for delegate-able events: not `focus`, `blur`, and
+    // not `change`, `submit`, and `reset` in Internet Explorer.
+    delegateEvents: function(events) {
+      if (!(events || (events = _.result(this, 'events')))) return this;
+      this.undelegateEvents();
+      for (var key in events) {
+        var method = events[key];
+        if (!_.isFunction(method)) method = this[events[key]];
+        if (!method) continue;
+
+        var match = key.match(delegateEventSplitter);
+        var eventName = match[1], selector = match[2];
+        method = _.bind(method, this);
+        eventName += '.delegateEvents' + this.cid;
+        if (selector === '') {
+          this.$el.on(eventName, method);
+        } else {
+          this.$el.on(eventName, selector, method);
+        }
+      }
+      return this;
+    },
+
+    // Clears all callbacks previously bound to the view with `delegateEvents`.
+    // You usually don't need to use this, but may wish to if you have multiple
+    // Backbone views attached to the same DOM element.
+    undelegateEvents: function() {
+      this.$el.off('.delegateEvents' + this.cid);
+      return this;
+    },
+
+    // Performs the initial configuration of a View with a set of options.
+    // Keys with special meaning *(e.g. model, collection, id, className)* are
+    // attached directly to the view.  See `viewOptions` for an exhaustive
+    // list.
+    _configure: function(options) {
+      if (this.options) options = _.extend({}, _.result(this, 'options'), options);
+      _.extend(this, _.pick(options, viewOptions));
+      this.options = options;
+    },
+
+    // Ensure that the View has a DOM element to render into.
+    // If `this.el` is a string, pass it through `$()`, take the first
+    // matching element, and re-assign it to `el`. Otherwise, create
+    // an element from the `id`, `className` and `tagName` properties.
+    _ensureElement: function() {
+      if (!this.el) {
+        var attrs = _.extend({}, _.result(this, 'attributes'));
+        if (this.id) attrs.id = _.result(this, 'id');
+        if (this.className) attrs['class'] = _.result(this, 'className');
+        var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
+        this.setElement($el, false);
+      } else {
+        this.setElement(_.result(this, 'el'), false);
+      }
+    }
+
+  });
+
+  // Backbone.sync
+  // -------------
+
+  // Override this function to change the manner in which Backbone persists
+  // models to the server. You will be passed the type of request, and the
+  // model in question. By default, makes a RESTful Ajax request
+  // to the model's `url()`. Some possible customizations could be:
+  //
+  // * Use `setTimeout` to batch rapid-fire updates into a single request.
+  // * Send up the models as XML instead of JSON.
+  // * Persist models via WebSockets instead of Ajax.
+  //
+  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
+  // as `POST`, with a `_method` parameter containing the true HTTP method,
+  // as well as all requests with the body as `application/x-www-form-urlencoded`
+  // instead of `application/json` with the model in a param named `model`.
+  // Useful when interfacing with server-side languages like **PHP** that make
+  // it difficult to read the body of `PUT` requests.
+  Backbone.sync = function(method, model, options) {
+    var type = methodMap[method];
+
+    // Default options, unless specified.
+    _.defaults(options || (options = {}), {
+      emulateHTTP: Backbone.emulateHTTP,
+      emulateJSON: Backbone.emulateJSON
+    });
+
+    // Default JSON-request options.
+    var params = {type: type, dataType: 'json'};
+
+    // Ensure that we have a URL.
+    if (!options.url) {
+      params.url = _.result(model, 'url') || urlError();
+    }
+
+    // Ensure that we have the appropriate request data.
+    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
+      params.contentType = 'application/json';
+      params.data = JSON.stringify(options.attrs || model.toJSON(options));
+    }
+
+    // For older servers, emulate JSON by encoding the request into an HTML-form.
+    if (options.emulateJSON) {
+      params.contentType = 'application/x-www-form-urlencoded';
+      params.data = params.data ? {model: params.data} : {};
+    }
+
+    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
+    // And an `X-HTTP-Method-Override` header.
+    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
+      params.type = 'POST';
+      if (options.emulateJSON) params.data._method = type;
+      var beforeSend = options.beforeSend;
+      options.beforeSend = function(xhr) {
+        xhr.setRequestHeader('X-HTTP-Method-Override', type);
+        if (beforeSend) return beforeSend.apply(this, arguments);
+      };
+    }
+
+    // Don't process data on a non-GET request.
+    if (params.type !== 'GET' && !options.emulateJSON) {
+      params.processData = false;
+    }
+
+    // If we're sending a `PATCH` request, and we're in an old Internet Explorer
+    // that still has ActiveX enabled by default, override jQuery to use that
+    // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
+    if (params.type === 'PATCH' && window.ActiveXObject &&
+          !(window.external && window.external.msActiveXFilteringEnabled)) {
+      params.xhr = function() {
+        return new ActiveXObject("Microsoft.XMLHTTP");
+      };
+    }
+
+    // Make the request, allowing the user to override any Ajax options.
+    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
+    model.trigger('request', model, xhr, options);
+    return xhr;
+  };
+
+  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
+  var methodMap = {
+    'create': 'POST',
+    'update': 'PUT',
+    'patch':  'PATCH',
+    'delete': 'DELETE',
+    'read':   'GET'
+  };
+
+  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
+  // Override this if you'd like to use a different library.
+  Backbone.ajax = function() {
+    return Backbone.$.ajax.apply(Backbone.$, arguments);
+  };
+
+  // Backbone.Router
+  // ---------------
+
+  // Routers map faux-URLs to actions, and fire events when routes are
+  // matched. Creating a new one sets its `routes` hash, if not set statically.
+  var Router = Backbone.Router = function(options) {
+    options || (options = {});
+    if (options.routes) this.routes = options.routes;
+    this._bindRoutes();
+    this.initialize.apply(this, arguments);
+  };
+
+  // Cached regular expressions for matching named param parts and splatted
+  // parts of route strings.
+  var optionalParam = /\((.*?)\)/g;
+  var namedParam    = /(\(\?)?:\w+/g;
+  var splatParam    = /\*\w+/g;
+  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
+
+  // Set up all inheritable **Backbone.Router** properties and methods.
+  _.extend(Router.prototype, Events, {
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // Manually bind a single named route to a callback. For example:
+    //
+    //     this.route('search/:query/p:num', 'search', function(query, num) {
+    //       ...
+    //     });
+    //
+    route: function(route, name, callback) {
+      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
+      if (_.isFunction(name)) {
+        callback = name;
+        name = '';
+      }
+      if (!callback) callback = this[name];
+      var router = this;
+      Backbone.history.route(route, function(fragment) {
+        var args = router._extractParameters(route, fragment);
+        callback && callback.apply(router, args);
+        router.trigger.apply(router, ['route:' + name].concat(args));
+        router.trigger('route', name, args);
+        Backbone.history.trigger('route', router, name, args);
+      });
+      return this;
+    },
+
+    // Simple proxy to `Backbone.history` to save a fragment into the history.
+    navigate: function(fragment, options) {
+      Backbone.history.navigate(fragment, options);
+      return this;
+    },
+
+    // Bind all defined routes to `Backbone.history`. We have to reverse the
+    // order of the routes here to support behavior where the most general
+    // routes can be defined at the bottom of the route map.
+    _bindRoutes: function() {
+      if (!this.routes) return;
+      this.routes = _.result(this, 'routes');
+      var route, routes = _.keys(this.routes);
+      while ((route = routes.pop()) != null) {
+        this.route(route, this.routes[route]);
+      }
+    },
+
+    // Convert a route string into a regular expression, suitable for matching
+    // against the current location hash.
+    _routeToRegExp: function(route) {
+      route = route.replace(escapeRegExp, '\\$&')
+                   .replace(optionalParam, '(?:$1)?')
+                   .replace(namedParam, function(match, optional){
+                     return optional ? match : '([^\/]+)';
+                   })
+                   .replace(splatParam, '(.*?)');
+      return new RegExp('^' + route + '$');
+    },
+
+    // Given a route, and a URL fragment that it matches, return the array of
+    // extracted decoded parameters. Empty or unmatched parameters will be
+    // treated as `null` to normalize cross-browser behavior.
+    _extractParameters: function(route, fragment) {
+      var params = route.exec(fragment).slice(1);
+      return _.map(params, function(param) {
+        return param ? decodeURIComponent(param) : null;
+      });
+    }
+
+  });
+
+  // Backbone.History
+  // ----------------
+
+  // Handles cross-browser history management, based on either
+  // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
+  // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
+  // and URL fragments. If the browser supports neither (old IE, natch),
+  // falls back to polling.
+  var History = Backbone.History = function() {
+    this.handlers = [];
+    _.bindAll(this, 'checkUrl');
+
+    // Ensure that `History` can be used outside of the browser.
+    if (typeof window !== 'undefined') {
+      this.location = window.location;
+      this.history = window.history;
+    }
+  };
+
+  // Cached regex for stripping a leading hash/slash and trailing space.
+  var routeStripper = /^[#\/]|\s+$/g;
+
+  // Cached regex for stripping leading and trailing slashes.
+  var rootStripper = /^\/+|\/+$/g;
+
+  // Cached regex for detecting MSIE.
+  var isExplorer = /msie [\w.]+/;
+
+  // Cached regex for removing a trailing slash.
+  var trailingSlash = /\/$/;
+
+  // Has the history handling already been started?
+  History.started = false;
+
+  // Set up all inheritable **Backbone.History** properties and methods.
+  _.extend(History.prototype, Events, {
+
+    // The default interval to poll for hash changes, if necessary, is
+    // twenty times a second.
+    interval: 50,
+
+    // Gets the true hash value. Cannot use location.hash directly due to bug
+    // in Firefox where location.hash will always be decoded.
+    getHash: function(window) {
+      var match = (window || this).location.href.match(/#(.*)$/);
+      return match ? match[1] : '';
+    },
+
+    // Get the cross-browser normalized URL fragment, either from the URL,
+    // the hash, or the override.
+    getFragment: function(fragment, forcePushState) {
+      if (fragment == null) {
+        if (this._hasPushState || !this._wantsHashChange || forcePushState) {
+          fragment = this.location.pathname;
+          var root = this.root.replace(trailingSlash, '');
+          if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
+        } else {
+          fragment = this.getHash();
+        }
+      }
+      return fragment.replace(routeStripper, '');
+    },
+
+    // Start the hash change handling, returning `true` if the current URL matches
+    // an existing route, and `false` otherwise.
+    start: function(options) {
+      if (History.started) throw new Error("Backbone.history has already been started");
+      History.started = true;
+
+      // Figure out the initial configuration. Do we need an iframe?
+      // Is pushState desired ... is it available?
+      this.options          = _.extend({}, {root: '/'}, this.options, options);
+      this.root             = this.options.root;
+      this._wantsHashChange = this.options.hashChange !== false;
+      this._wantsPushState  = !!this.options.pushState;
+      this._hasPushState    = !!(this.options.pushState && this.history && this.history.pushState);
+      var fragment          = this.getFragment();
+      var docMode           = document.documentMode;
+      var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
+
+      // Normalize root to always include a leading and trailing slash.
+      this.root = ('/' + this.root + '/').replace(rootStripper, '/');
+
+      if (oldIE && this._wantsHashChange) {
+        this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
+        this.navigate(fragment);
+      }
+
+      // Depending on whether we're using pushState or hashes, and whether
+      // 'onhashchange' is supported, determine how we check the URL state.
+      if (this._hasPushState) {
+        Backbone.$(window).on('popstate', this.checkUrl);
+      } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
+        Backbone.$(window).on('hashchange', this.checkUrl);
+      } else if (this._wantsHashChange) {
+        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
+      }
+
+      // Determine if we need to change the base url, for a pushState link
+      // opened by a non-pushState browser.
+      this.fragment = fragment;
+      var loc = this.location;
+      var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
+
+      // If we've started off with a route from a `pushState`-enabled browser,
+      // but we're currently in a browser that doesn't support it...
+      if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
+        this.fragment = this.getFragment(null, true);
+        this.location.replace(this.root + this.location.search + '#' + this.fragment);
+        // Return immediately as browser will do redirect to new url
+        return true;
+
+      // Or if we've started out with a hash-based route, but we're currently
+      // in a browser where it could be `pushState`-based instead...
+      } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
+        this.fragment = this.getHash().replace(routeStripper, '');
+        this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
+      }
+
+      if (!this.options.silent) return this.loadUrl();
+    },
+
+    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
+    // but possibly useful for unit testing Routers.
+    stop: function() {
+      Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
+      clearInterval(this._checkUrlInterval);
+      History.started = false;
+    },
+
+    // Add a route to be tested when the fragment changes. Routes added later
+    // may override previous routes.
+    route: function(route, callback) {
+      this.handlers.unshift({route: route, callback: callback});
+    },
+
+    // Checks the current URL to see if it has changed, and if it has,
+    // calls `loadUrl`, normalizing across the hidden iframe.
+    checkUrl: function(e) {
+      var current = this.getFragment();
+      if (current === this.fragment && this.iframe) {
+        current = this.getFragment(this.getHash(this.iframe));
+      }
+      if (current === this.fragment) return false;
+      if (this.iframe) this.navigate(current);
+      this.loadUrl() || this.loadUrl(this.getHash());
+    },
+
+    // Attempt to load the current URL fragment. If a route succeeds with a
+    // match, returns `true`. If no defined routes matches the fragment,
+    // returns `false`.
+    loadUrl: function(fragmentOverride) {
+      var fragment = this.fragment = this.getFragment(fragmentOverride);
+      var matched = _.any(this.handlers, function(handler) {
+        if (handler.route.test(fragment)) {
+          handler.callback(fragment);
+          return true;
+        }
+      });
+      return matched;
+    },
+
+    // Save a fragment into the hash history, or replace the URL state if the
+    // 'replace' option is passed. You are responsible for properly URL-encoding
+    // the fragment in advance.
+    //
+    // The options object can contain `trigger: true` if you wish to have the
+    // route callback be fired (not usually desirable), or `replace: true`, if
+    // you wish to modify the current URL without adding an entry to the history.
+    navigate: function(fragment, options) {
+      if (!History.started) return false;
+      if (!options || options === true) options = {trigger: options};
+      fragment = this.getFragment(fragment || '');
+      if (this.fragment === fragment) return;
+      this.fragment = fragment;
+      var url = this.root + fragment;
+
+      // If pushState is available, we use it to set the fragment as a real URL.
+      if (this._hasPushState) {
+        this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
+
+      // If hash changes haven't been explicitly disabled, update the hash
+      // fragment to store history.
+      } else if (this._wantsHashChange) {
+        this._updateHash(this.location, fragment, options.replace);
+        if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
+          // Opening and closing the iframe tricks IE7 and earlier to push a
+          // history entry on hash-tag change.  When replace is true, we don't
+          // want this.
+          if(!options.replace) this.iframe.document.open().close();
+          this._updateHash(this.iframe.location, fragment, options.replace);
+        }
+
+      // If you've told us that you explicitly don't want fallback hashchange-
+      // based history, then `navigate` becomes a page refresh.
+      } else {
+        return this.location.assign(url);
+      }
+      if (options.trigger) this.loadUrl(fragment);
+    },
+
+    // Update the hash location, either replacing the current entry, or adding
+    // a new one to the browser history.
+    _updateHash: function(location, fragment, replace) {
+      if (replace) {
+        var href = location.href.replace(/(javascript:|#).*$/, '');
+        location.replace(href + '#' + fragment);
+      } else {
+        // Some browsers require that `hash` contains a leading #.
+        location.hash = '#' + fragment;
+      }
+    }
+
+  });
+
+  // Create the default Backbone.history.
+  Backbone.history = new History;
+
+  // Helpers
+  // -------
+
+  // Helper function to correctly set up the prototype chain, for subclasses.
+  // Similar to `goog.inherits`, but uses a hash of prototype properties and
+  // class properties to be extended.
+  var extend = function(protoProps, staticProps) {
+    var parent = this;
+    var child;
+
+    // The constructor function for the new subclass is either defined by you
+    // (the "constructor" property in your `extend` definition), or defaulted
+    // by us to simply call the parent's constructor.
+    if (protoProps && _.has(protoProps, 'constructor')) {
+      child = protoProps.constructor;
+    } else {
+      child = function(){ return parent.apply(this, arguments); };
+    }
+
+    // Add static properties to the constructor function, if supplied.
+    _.extend(child, parent, staticProps);
+
+    // Set the prototype chain to inherit from `parent`, without calling
+    // `parent`'s constructor function.
+    var Surrogate = function(){ this.constructor = child; };
+    Surrogate.prototype = parent.prototype;
+    child.prototype = new Surrogate;
+
+    // Add prototype properties (instance properties) to the subclass,
+    // if supplied.
+    if (protoProps) _.extend(child.prototype, protoProps);
+
+    // Set a convenience property in case the parent's prototype is needed
+    // later.
+    child.__super__ = parent.prototype;
+
+    return child;
+  };
+
+  // Set up inheritance for the model, collection, router, view and history.
+  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
+
+  // Throw an error when a URL is needed, and none is supplied.
+  var urlError = function() {
+    throw new Error('A "url" property or function must be specified');
+  };
+
+  // Wrap an optional error callback with a fallback error event.
+  var wrapError = function (model, options) {
+    var error = options.error;
+    options.error = function(resp) {
+      if (error) error(model, resp, options);
+      model.trigger('error', model, resp, options);
+    };
+  };
+
+}).call(this);
+
+// Vectorizer.
+// -----------
+
+// A tiny library for making your live easier when dealing with SVG.
+
+// Copyright © 2012 - 2014 client IO (http://client.io)
+
+(function(root, factory) {
+
+    if (typeof define === 'function' && define.amd) {
+        // AMD. Register as an anonymous module.
+        define([], factory);
+        
+    } else {
+        // Browser globals.
+        root.Vectorizer = root.V = factory();
+    }
+
+}(this, function() {
+
+    // Well, if SVG is not supported, this library is useless.
+    var SVGsupported = !!(window.SVGAngle || document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'));
+
+    // XML namespaces.
+    var ns = {
+        xmlns: 'http://www.w3.org/2000/svg',
+        xlink: 'http://www.w3.org/1999/xlink'
+    };
+    // SVG version.
+    var SVGversion = '1.1';
+
+    // A function returning a unique identifier for this client session with every call.
+    var idCounter = 0;
+    function uniqueId() {
+        var id = ++idCounter + '';
+        return 'v-' + id;
+    }
+
+    // Create SVG element.
+    // -------------------
+
+    function createElement(el, attrs, children) {
+
+        if (!el) return undefined;
+        
+        // If `el` is an object, it is probably a native SVG element. Wrap it to VElement.
+        if (typeof el === 'object') {
+            return new VElement(el);
+        }
+        attrs = attrs || {};
+
+        // If `el` is a `'svg'` or `'SVG'` string, create a new SVG canvas.
+        if (el.toLowerCase() === 'svg') {
+            
+            attrs.xmlns = ns.xmlns;
+            attrs['xmlns:xlink'] = ns.xlink;
+            attrs.version = SVGversion;
+            
+        } else if (el[0] === '<') {
+            // Create element from an SVG string.
+            // Allows constructs of type: `document.appendChild(Vectorizer('<rect></rect>').node)`.
+            
+            var svg = '<svg xmlns="' + ns.xmlns + '" xmlns:xlink="' + ns.xlink + '" version="' + SVGversion + '">' + el + '</svg>';
+            var parser = new DOMParser();
+            parser.async = false;
+            var svgDoc = parser.parseFromString(svg, 'text/xml').documentElement;
+
+            // Note that `createElement()` might also return an array should the SVG string passed as
+            // the first argument contain more then one root element.
+            if (svgDoc.childNodes.length > 1) {
+
+                // Map child nodes to `VElement`s.
+                var ret = [];
+                for (var i = 0, len = svgDoc.childNodes.length; i < len; i++) {
+
+                    var childNode = svgDoc.childNodes[i];
+                    ret.push(new VElement(document.importNode(childNode, true)));
+                }
+                return ret;
+            }
+            
+            return new VElement(document.importNode(svgDoc.firstChild, true));
+        }
+        
+        el = document.createElementNS(ns.xmlns, el);
+
+        // Set attributes.
+        for (var key in attrs) {
+
+            setAttribute(el, key, attrs[key]);
+        }
+        
+        // Normalize `children` array.
+        if (Object.prototype.toString.call(children) != '[object Array]') children = [children];
+
+        // Append children if they are specified.
+        var i = 0, len = (children[0] && children.length) || 0, child;
+        for (; i < len; i++) {
+            child = children[i];
+            el.appendChild(child instanceof VElement ? child.node : child);
+        }
+        
+        return new VElement(el);
+    }
+
+    function setAttribute(el, name, value) {
+        
+        if (name.indexOf(':') > -1) {
+            // Attribute names can be namespaced. E.g. `image` elements
+            // have a `xlink:href` attribute to set the source of the image.
+            var combinedKey = name.split(':');
+            el.setAttributeNS(ns[combinedKey[0]], combinedKey[1], value);
+        } else if (name === 'id') {
+            el.id = value;
+        } else {
+            el.setAttribute(name, value);
+        }
+    }
+
+    function parseTransformString(transform) {
+        var translate,
+            rotate,
+            scale;
+        
+        if (transform) {
+            var translateMatch = transform.match(/translate\((.*)\)/);
+            if (translateMatch) {
+                translate = translateMatch[1].split(',');
+            }
+            var rotateMatch = transform.match(/rotate\((.*)\)/);
+            if (rotateMatch) {
+                rotate = rotateMatch[1].split(',');
+            }
+            var scaleMatch = transform.match(/scale\((.*)\)/);
+            if (scaleMatch) {
+                scale = scaleMatch[1].split(',');
+            }
+        }
+
+        var sx = (scale && scale[0]) ? parseFloat(scale[0]) : 1;
+        
+        return {
+            translate: {
+                tx: (translate && translate[0]) ? parseInt(translate[0], 10) : 0,
+                ty: (translate && translate[1]) ? parseInt(translate[1], 10) : 0
+            },
+            rotate: {
+                angle: (rotate && rotate[0]) ? parseInt(rotate[0], 10) : 0,
+                cx: (rotate && rotate[1]) ? parseInt(rotate[1], 10) : undefined,
+                cy: (rotate && rotate[2]) ? parseInt(rotate[2], 10) : undefined
+            },
+            scale: {
+                sx: sx,
+                sy: (scale && scale[1]) ? parseFloat(scale[1]) : sx
+            }
+        };
+    }
+
+
+    // Matrix decomposition.
+    // ---------------------
+
+    function deltaTransformPoint(matrix, point)  {
+        
+       var dx = point.x * matrix.a + point.y * matrix.c + 0;
+       var dy = point.x * matrix.b + point.y * matrix.d + 0;
+       return { x: dx, y: dy };
+    }
+
+    function decomposeMatrix(matrix) {
+
+        // @see https://gist.github.com/2052247
+        
+        // calculate delta transform point
+       var px = deltaTransformPoint(matrix, { x: 0, y: 1 });
+       var py = deltaTransformPoint(matrix, { x: 1, y: 0 });
+        
+       // calculate skew
+       var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90);
+       var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x));
+        
+       return {
+            
+           translateX: matrix.e,
+           translateY: matrix.f,
+           scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b),
+           scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d),
+           skewX: skewX,
+           skewY: skewY,
+           rotation: skewX // rotation is the same as skew x
+       };
+    }
+    
+    // VElement.
+    // ---------
+
+    function VElement(el) {
+        this.node = el;
+        if (!this.node.id) {
+            this.node.id = uniqueId();
+        }
+    }
+
+    // VElement public API.
+    // --------------------
+
+    VElement.prototype = {
+        
+        translate: function(tx, ty) {
+            ty = ty || 0;
+            
+            var transformAttr = this.attr('transform') || '',
+                transform = parseTransformString(transformAttr);
+
+            // Is it a getter?
+            if (typeof tx === 'undefined') {
+                return transform.translate;
+            }
+            
+            transformAttr = transformAttr.replace(/translate\([^\)]*\)/g, '').trim();
+
+            var newTx = transform.translate.tx + tx,
+                newTy = transform.translate.ty + ty;
+
+            // Note that `translate()` is always the first transformation. This is
+            // usually the desired case.
+            this.attr('transform', 'translate(' + newTx + ',' + newTy + ') ' + transformAttr);
+            return this;
+        },
+
+        rotate: function(angle, cx, cy) {
+            var transformAttr = this.attr('transform') || '',
+                transform = parseTransformString(transformAttr);
+
+            // Is it a getter?
+            if (typeof angle === 'undefined') {
+                return transform.rotate;
+            }
+            
+            transformAttr = transformAttr.replace(/rotate\([^\)]*\)/g, '').trim();
+
+            var newAngle = transform.rotate.angle + angle % 360,
+                newOrigin = (cx !== undefined && cy !== undefined) ? ',' + cx + ',' + cy : '';
+            
+            this.attr('transform', transformAttr + ' rotate(' + newAngle + newOrigin + ')');
+            return this;
+        },
+
+        // Note that `scale` as the only transformation does not combine with previous values.
+        scale: function(sx, sy) {
+            sy = (typeof sy === 'undefined') ? sx : sy;
+            
+            var transformAttr = this.attr('transform') || '',
+                transform = parseTransformString(transformAttr);
+
+            // Is it a getter?
+            if (typeof sx === 'undefined') {
+                return transform.scale;
+            }
+            
+            transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim();
+
+            this.attr('transform', transformAttr + ' scale(' + sx + ',' + sy + ')');
+            return this;
+        },
+
+        // Get SVGRect that contains coordinates and dimension of the real bounding box,
+        // i.e. after transformations are applied.
+        // If `target` is specified, bounding box will be computed relatively to `target` element.
+        bbox: function(withoutTransformations, target) {
+
+            // If the element is not in the live DOM, it does not have a bounding box defined and
+            // so fall back to 'zero' dimension element.
+            if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 };
+            
+            var box;
+            try {
+
+                box = this.node.getBBox();
+
+               // Opera returns infinite values in some cases.
+               // Note that Infinity | 0 produces 0 as opposed to Infinity || 0.
+               // We also have to create new object as the standard says that you can't
+               // modify the attributes of a bbox.
+               box = { x: box.x | 0, y: box.y | 0, width: box.width | 0, height: box.height | 0};
+
+            } catch (e) {
+
+                // Fallback for IE.
+                box = {
+                    x: this.node.clientLeft,
+                    y: this.node.clientTop,
+                    width: this.node.clientWidth,
+                    height: this.node.clientHeight
+                };
+            }
+
+            if (withoutTransformations) {
+
+                return box;
+            }
+
+            var matrix = this.node.getTransformToElement(target || this.node.ownerSVGElement);
+            var corners = [];
+            var point = this.node.ownerSVGElement.createSVGPoint();
+
+
+            point.x = box.x;
+            point.y = box.y;
+            corners.push(point.matrixTransform(matrix));
+            
+            point.x = box.x + box.width;
+            point.y = box.y;
+            corners.push(point.matrixTransform(matrix));
+            
+            point.x = box.x + box.width;
+            point.y = box.y + box.height;
+            corners.push(point.matrixTransform(matrix));
+            
+            point.x = box.x;
+            point.y = box.y + box.height;
+            corners.push(point.matrixTransform(matrix));
+
+            var minX = corners[0].x;
+            var maxX = minX;
+            var minY = corners[0].y;
+            var maxY = minY;
+            
+            for (var i = 1, len = corners.length; i < len; i++) {
+                
+                var x = corners[i].x;
+                var y = corners[i].y;
+
+                if (x < minX) {
+                    minX = x;
+                } else if (x > maxX) {
+                    maxX = x;
+                }
+                
+                if (y < minY) {
+                    minY = y;
+                } else if (y > maxY) {
+                    maxY = y;
+                }
+            }
+
+            return {
+                x: minX,
+                y: minY,
+                width: maxX - minX,
+                height: maxY - minY
+            };
+        },
+
+        text: function(content) {
+            var lines = content.split('\n'), i = 0,
+                tspan;
+
+            // `alignment-baseline` does not work in Firefox.
+           // Setting `dominant-baseline` on the `<text>` element doesn't work in IE9.
+            // In order to have the 0,0 coordinate of the `<text>` element (or the first `<tspan>`)
+           // in the top left corner we translate the `<text>` element by `0.8em`.
+           // See `http://www.w3.org/Graphics/SVG/WG/wiki/How_to_determine_dominant_baseline`.
+           // See also `http://apike.ca/prog_svg_text_style.html`.
+           this.attr('y', '0.8em');
+
+            // An empty text gets rendered into the DOM in webkit-based browsers.
+            // In order to unify this behaviour across all browsers
+            // we rather hide the text element when it's empty.
+            this.attr('display', content ? null : 'none');
+            
+            if (lines.length === 1) {
+                this.node.textContent = content;
+                return this;
+            }
+            // Easy way to erase all `<tspan>` children;
+            this.node.textContent = '';
+            
+            for (; i < lines.length; i++) {
+
+                // Shift all the <tspan> but first by one line (`1em`)
+                tspan = V('tspan', { dy: (i == 0 ? '0em' : '1em'), x: this.attr('x') || 0});
+                tspan.node.textContent = lines[i];
+                
+                this.append(tspan);
+            }
+            return this;
+        },
+        
+        attr: function(name, value) {
+            
+            if (typeof name === 'string' && typeof value === 'undefined') {
+                return this.node.getAttribute(name);
+            }
+            
+            if (typeof name === 'object') {
+
+                for (var attrName in name) {
+                    if (name.hasOwnProperty(attrName)) {
+                        setAttribute(this.node, attrName, name[attrName]);
+                    }
+                }
+                
+            } else {
+
+                setAttribute(this.node, name, value);
+            }
+
+            return this;
+        },
+
+        remove: function() {
+            if (this.node.parentNode) {
+                this.node.parentNode.removeChild(this.node);
+            }
+        },
+
+        append: function(el) {
+
+            var els = el;
+            
+            if (Object.prototype.toString.call(el) !== '[object Array]') {
+                
+                els = [el];
+            }
+
+            for (var i = 0, len = els.length; i < len; i++) {
+                el = els[i];
+                this.node.appendChild(el instanceof VElement ? el.node : el);
+            }
+            
+            return this;
+        },
+
+        prepend: function(el) {
+            this.node.insertBefore(el instanceof VElement ? el.node : el, this.node.firstChild);
+        },
+
+        svg: function() {
+
+            return this.node instanceof window.SVGSVGElement ? this : V(this.node.ownerSVGElement);
+        },
+
+        defs: function() {
+
+            var defs = this.svg().node.getElementsByTagName('defs');
+            
+            return (defs && defs.length) ? V(defs[0]) : undefined;
+        },
+
+        clone: function() {
+            var clone = V(this.node.cloneNode(true));
+            // Note that clone inherits also ID. Therefore, we need to change it here.
+            clone.node.id = uniqueId();
+            return clone;
+        },
+
+        findOne: function(selector) {
+
+            var found = this.node.querySelector(selector);
+            return found ? V(found) : undefined;
+        },
+
+        find: function(selector) {
+
+            var nodes = this.node.querySelectorAll(selector);
+
+            // Map DOM elements to `VElement`s.
+            for (var i = 0, len = nodes.length; i < len; i++) {
+                nodes[i] = V(nodes[i]);
+            }
+            return nodes;
+        },
+        
+        // Convert global point into the coordinate space of this element.
+        toLocalPoint: function(x, y) {
+
+            var svg = this.svg().node;
+            
+            var p = svg.createSVGPoint();
+            p.x = x;
+            p.y = y;
+
+           try {
+
+               var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse());
+               var globalToLocalMatrix = this.node.getTransformToElement(svg).inverse();
+
+           } catch(e) {
+               // IE9 throws an exception in odd cases. (`Unexpected call to method or property access`)
+               // We have to make do with the original coordianates.
+               return p;
+           }
+
+            return globalPoint.matrixTransform(globalToLocalMatrix);
+        },
+
+        translateCenterToPoint: function(p) {
+
+            var bbox = this.bbox();
+            var center = g.rect(bbox).center();
+
+            this.translate(p.x - center.x, p.y - center.y);
+        },
+
+        // Efficiently auto-orient an element. This basically implements the orient=auto attribute
+        // of markers. The easiest way of understanding on what this does is to imagine the element is an
+        // arrowhead. Calling this method on the arrowhead makes it point to the `position` point while
+        // being auto-oriented (properly rotated) towards the `reference` point.
+        // `target` is the element relative to which the transformations are applied. Usually a viewport.
+        translateAndAutoOrient: function(position, reference, target) {
+
+            // Clean-up previously set transformations except the scale. If we didn't clean up the
+            // previous transformations then they'd add up with the old ones. Scale is an exception as
+            // it doesn't add up, consider: `this.scale(2).scale(2).scale(2)`. The result is that the
+            // element is scaled by the factor 2, not 8.
+
+            var s = this.scale();
+            this.attr('transform', '');
+            this.scale(s.sx, s.sy);
+
+            var svg = this.svg().node;
+            var bbox = this.bbox(false, target);
+
+            // 1. Translate to origin.
+            var translateToOrigin = svg.createSVGTransform();
+            translateToOrigin.setTranslate(-bbox.x - bbox.width/2, -bbox.y - bbox.height/2);
+
+            // 2. Rotate around origin.
+            var rotateAroundOrigin = svg.createSVGTransform();
+            var angle = g.point(position).changeInAngle(position.x - reference.x, position.y - reference.y, reference);
+            rotateAroundOrigin.setRotate(angle, 0, 0);
+
+            // 3. Translate to the `position` + the offset (half my width) towards the `reference` point.
+            var translateFinal = svg.createSVGTransform();
+            var finalPosition = g.point(position).move(reference, bbox.width/2);
+            translateFinal.setTranslate(position.x + (position.x - finalPosition.x), position.y + (position.y - finalPosition.y));
+
+            // 4. Apply transformations.
+            var ctm = this.node.getTransformToElement(target);
+            var transform = svg.createSVGTransform();
+            transform.setMatrix(
+                translateFinal.matrix.multiply(
+                    rotateAroundOrigin.matrix.multiply(
+                        translateToOrigin.matrix.multiply(
+                            ctm)))
+            );
+
+            // Instead of directly setting the `matrix()` transform on the element, first, decompose
+            // the matrix into separate transforms. This allows us to use normal Vectorizer methods
+            // as they don't work on matrices. An example of this is to retrieve a scale of an element.
+            // this.node.transform.baseVal.initialize(transform);
+
+            var decomposition = decomposeMatrix(transform.matrix);
+
+            this.translate(decomposition.translateX, decomposition.translateY);
+            this.rotate(decomposition.rotation);
+            // Note that scale has been already applied, hence the following line stays commented. (it's here just for reference).
+            //this.scale(decomposition.scaleX, decomposition.scaleY);
+
+            return this;
+        },
+
+        animateAlongPath: function(attrs, path) {
+
+            var animateMotion = V('animateMotion', attrs);
+            var mpath = V('mpath', { 'xlink:href': '#' + V(path).node.id });
+
+            animateMotion.append(mpath);
+
+            this.append(animateMotion);
+            try {
+                animateMotion.node.beginElement();
+            } catch (e) {
+                // Fallback for IE 9.
+               // Run the animation programatically if FakeSmile (`http://leunen.me/fakesmile/`) present 
+               if (document.documentElement.getAttribute('smiling') === 'fake') {
+
+                   // Register the animation. (See `https://answers.launchpad.net/smil/+question/203333`)
+                   var animation = animateMotion.node;
+                   animation.animators = [];
+
+                   var animationID = animation.getAttribute('id');
+                   if (animationID) id2anim[animationID] = animation;
+
+                    var targets = getTargets(animation);
+                    for (var i = 0, len = targets.length; i < len; i++) {
+                        var target = targets[i];
+                       var animator = new Animator(animation, target, i);
+                       animators.push(animator);
+                       animation.animators[i] = animator;
+                        animator.register();
+                    }
+               }
+            }
+        },
+
+        hasClass: function(className) {
+
+            return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.node.getAttribute('class'));
+        },
+
+        addClass: function(className) {
+
+            if (!this.hasClass(className)) {
+                this.node.setAttribute('class', this.node.getAttribute('class') + ' ' + className);
+            }
+
+            return this;
+        },
+
+        removeClass: function(className) {
+
+            var removedClass = this.node.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
+
+            if (this.hasClass(className)) {
+                this.node.setAttribute('class', removedClass);
+            }
+
+            return this;
+        },
+
+        toggleClass: function(className, toAdd) {
+
+            var toRemove = typeof toAdd === 'undefined' ? this.hasClass(className) : !toAdd;
+
+            if (toRemove) {
+                this.removeClass(className);
+            } else {
+                this.addClass(className);
+            }
+
+            return this;
+        }
+    };
+
+    // Convert a rectangle to SVG path commands. `r` is an object of the form:
+    // `{ x: [number], y: [number], width: [number], height: [number], top-ry: [number], top-ry: [number], bottom-rx: [number], bottom-ry: [number] }`,
+    // where `x, y, width, height` are the usual rectangle attributes and [top-/bottom-]rx/ry allows for
+    // specifying radius of the rectangle for all its sides (as opposed to the built-in SVG rectangle
+    // that has only `rx` and `ry` attributes).
+    function rectToPath(r) {
+
+        var topRx = r.rx || r['top-rx'] || 0;
+        var bottomRx = r.rx || r['bottom-rx'] || 0;
+        var topRy = r.ry || r['top-ry'] || 0;
+        var bottomRy = r.ry || r['bottom-ry'] || 0;
+
+        return [
+            'M', r.x, r.y + topRy,
+            'v', r.height - topRy - bottomRy,
+            'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, bottomRy,
+            'h', r.width - 2 * bottomRx,
+            'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, -bottomRy,
+            'v', -(r.height - bottomRy - topRy),
+            'a', topRx, topRy, 0, 0, 0, -topRx, -topRy,
+            'h', -(r.width - 2 * topRx),
+            'a', topRx, topRy, 0, 0, 0, -topRx, topRy
+        ].join(' ');
+    }
+
+    var V = createElement;
+
+    V.decomposeMatrix = decomposeMatrix;
+    V.rectToPath = rectToPath;
+
+    var svgDocument = V('svg').node;
+    
+    V.createSVGMatrix = function(m) {
+
+        var svgMatrix = svgDocument.createSVGMatrix();
+        for (var component in m) {
+            svgMatrix[component] = m[component];
+        }
+        
+        return svgMatrix;
+    };
+
+    V.createSVGTransform = function() {
+
+        return svgDocument.createSVGTransform();
+    };
+
+    V.createSVGPoint = function(x, y) {
+
+        var p = svgDocument.createSVGPoint();
+        p.x = x;
+        p.y = y;
+        return p;
+    };
+
+    return V;
+
+}));
+
+
+//      Geometry library.
+//      (c) 2011-2013 client IO
+
+
+(function(root, factory) {
+
+    if (typeof define === 'function' && define.amd) {
+        // AMD. Register as an anonymous module.
+        define([], factory);
+        
+    } else if (typeof exports === 'object') {
+        // Node. Does not work with strict CommonJS, but
+        // only CommonJS-like environments that support module.exports,
+        // like Node.
+        module.exports = factory();
+        
+    } else {
+        // Browser globals.
+        root.g = factory();
+    }
+
+}(this, function() {
+
+
+    // Declare shorthands to the most used math functions.
+    var math = Math;
+    var abs = math.abs;
+    var cos = math.cos;
+    var sin = math.sin;
+    var sqrt = math.sqrt;
+    var mmin = math.min;
+    var mmax = math.max;
+    var atan = math.atan;
+    var atan2 = math.atan2;
+    var acos = math.acos;
+    var round = math.round;
+    var floor = math.floor;
+    var PI = math.PI;
+    var random = math.random;
+    var toDeg = function(rad) { return (180*rad / PI) % 360; };
+    var toRad = function(deg) { return (deg % 360) * PI / 180; };
+    var snapToGrid = function(val, gridSize) { return gridSize * Math.round(val/gridSize); };
+    var normalizeAngle = function(angle) { return (angle % 360) + (angle < 0 ? 360 : 0); };
+
+    // Point
+    // -----
+
+    // Point is the most basic object consisting of x/y coordinate,.
+
+    // Possible instantiations are:
+
+    // * `point(10, 20)`
+    // * `new point(10, 20)`
+    // * `point('10 20')`
+    // * `point(point(10, 20))`
+    function point(x, y) {
+        if (!(this instanceof point))
+            return new point(x, y);
+        var xy;
+        if (y === undefined && Object(x) !== x) {
+            xy = x.split(x.indexOf('@') === -1 ? ' ' : '@');
+            this.x = parseInt(xy[0], 10);
+            this.y = parseInt(xy[1], 10);
+        } else if (Object(x) === x) {
+            this.x = x.x;
+            this.y = x.y;
+        } else {
+            this.x = x;
+            this.y = y;
+        }
+    }
+
+    point.prototype = {
+        toString: function() {
+            return this.x + "@" + this.y;
+        },
+        // If point lies outside rectangle `r`, return the nearest point on the boundary of rect `r`,
+        // otherwise return point itself.
+        // (see Squeak Smalltalk, Point>>adhereTo:)
+        adhereToRect: function(r) {
+           if (r.containsPoint(this)){
+               return this;
+           }
+           this.x = mmin(mmax(this.x, r.x), r.x + r.width);
+           this.y = mmin(mmax(this.y, r.y), r.y + r.height);
+           return this;
+        },
+        // Compute the angle between me and `p` and the x axis.
+        // (cartesian-to-polar coordinates conversion)
+        // Return theta angle in degrees.
+        theta: function(p) {
+            p = point(p);
+            // Invert the y-axis.
+           var y = -(p.y - this.y);
+           var x = p.x - this.x;
+            // Makes sure that the comparison with zero takes rounding errors into account.
+            var PRECISION = 10;
+            // Note that `atan2` is not defined for `x`, `y` both equal zero.
+           var rad = (y.toFixed(PRECISION) == 0 && x.toFixed(PRECISION) == 0) ? 0 : atan2(y, x); 
+
+            // Correction for III. and IV. quadrant.
+           if (rad < 0) { 
+               rad = 2*PI + rad;
+           }
+           return 180*rad / PI;
+        },
+        // Returns distance between me and point `p`.
+        distance: function(p) {
+           return line(this, p).length();
+        },
+        // Returns a manhattan (taxi-cab) distance between me and point `p`.
+        manhattanDistance: function(p) {
+            return abs(p.x - this.x) + abs(p.y - this.y);
+        },
+        // Offset me by the specified amount.
+        offset: function(dx, dy) {
+           this.x += dx || 0;
+           this.y += dy || 0;
+           return this;
+        },
+        magnitude: function() {
+            return sqrt((this.x*this.x) + (this.y*this.y)) || 0.01;
+        },
+        update: function(x, y) {
+            this.x = x || 0;
+            this.y = y || 0;
+            return this;
+        },
+        round: function(decimals) {
+            this.x = decimals ? this.x.toFixed(decimals) : round(this.x);
+            this.y = decimals ? this.y.toFixed(decimals) : round(this.y);
+            return this;
+        },
+        // Scale the line segment between (0,0) and me to have a length of len.
+        normalize: function(len) {
+           var s = (len || 1) / this.magnitude();
+           this.x = s * this.x;
+           this.y = s * this.y;
+           return this;
+        },
+        difference: function(p) {
+            return point(this.x - p.x, this.y - p.y);
+        },
+        // Return the bearing between me and point `p`.
+        bearing: function(p) {
+            return line(this, p).bearing();
+        },        
+        // Converts rectangular to polar coordinates.
+        // An origin can be specified, otherwise it's 0@0.
+        toPolar: function(o) {
+            o = (o && point(o)) || point(0,0);
+            var x = this.x;
+            var y = this.y;
+            this.x = sqrt((x-o.x)*(x-o.x) + (y-o.y)*(y-o.y));   // r
+            this.y = toRad(o.theta(point(x,y)));
+            return this;
+        },
+        // Rotate point by angle around origin o.
+        rotate: function(o, angle) {
+            angle = (angle + 360) % 360;
+            this.toPolar(o);
+            this.y += toRad(angle);
+            var p = point.fromPolar(this.x, this.y, o);
+            this.x = p.x;
+            this.y = p.y;
+            return this;
+        },
+        // Move point on line starting from ref ending at me by
+        // distance distance.
+        move: function(ref, distance) {
+            var theta = toRad(point(ref).theta(this));
+            return this.offset(cos(theta) * distance, -sin(theta) * distance);
+        },
+        // Returns change in angle from my previous position (-dx, -dy) to my new position
+        // relative to ref point.
+        changeInAngle: function(dx, dy, ref) {
+            // Revert the translation and measure the change in angle around x-axis.
+            return point(this).offset(-dx, -dy).theta(ref) - this.theta(ref);
+        },
+        equals: function(p) {
+            return this.x === p.x && this.y === p.y;
+        },
+        snapToGrid: function(gx, gy) {
+            this.x = snapToGrid(this.x, gx)
+            this.y = snapToGrid(this.y, gy || gx)
+            return this;
+        }
+    };
+    // Alternative constructor, from polar coordinates.
+    // @param {number} r Distance.
+    // @param {number} angle Angle in radians.
+    // @param {point} [optional] o Origin.
+    point.fromPolar = function(r, angle, o) {
+        o = (o && point(o)) || point(0,0);
+        var x = abs(r * cos(angle));
+        var y = abs(r * sin(angle));
+        var deg = normalizeAngle(toDeg(angle));
+
+        if (deg < 90) y = -y;
+        else if (deg < 180) { x = -x; y = -y; }
+        else if (deg < 270) x = -x;
+        
+        return point(o.x + x, o.y + y);
+    };
+
+    // Create a point with random coordinates that fall into the range `[x1, x2]` and `[y1, y2]`.
+    point.random = function(x1, x2, y1, y2) {
+        return point(floor(random() * (x2 - x1 + 1) + x1), floor(random() * (y2 - y1 + 1) + y1));
+    };
+
+    // Line.
+    // -----
+    function line(p1, p2) {
+        if (!(this instanceof line))
+            return new line(p1, p2);
+        this.start = point(p1);
+        this.end = point(p2);
+    }
+    
+    line.prototype = {
+        toString: function() {
+           return this.start.toString() + ' ' + this.end.toString();
+        },
+        // @return {double} length of the line
+        length: function() {
+            return sqrt(this.squaredLength());
+        },
+        // @return {integer} length without sqrt
+        // @note for applications where the exact length is not necessary (e.g. compare only)
+        squaredLength: function() {
+           var x0 = this.start.x;
+            var y0 = this.start.y;
+           var x1 = this.end.x;
+            var y1 = this.end.y;
+           return (x0 -= x1)*x0 + (y0 -= y1)*y0;
+        },
+        // @return {point} my midpoint
+        midpoint: function() {
+           return point((this.start.x + this.end.x) / 2,
+                        (this.start.y + this.end.y) / 2);
+        },
+        // @return {point} Point where I'm intersecting l.
+        // @see Squeak Smalltalk, LineSegment>>intersectionWith:
+        intersection: function(l) {
+           var pt1Dir = point(this.end.x - this.start.x, this.end.y - this.start.y);
+           var pt2Dir = point(l.end.x - l.start.x, l.end.y - l.start.y);
+           var det = (pt1Dir.x * pt2Dir.y) - (pt1Dir.y * pt2Dir.x);
+           var deltaPt = point(l.start.x - this.start.x, l.start.y - this.start.y);
+           var alpha = (deltaPt.x * pt2Dir.y) - (deltaPt.y * pt2Dir.x);
+           var beta = (deltaPt.x * pt1Dir.y) - (deltaPt.y * pt1Dir.x);
+
+           if (det === 0 ||
+               alpha * det < 0 ||
+               beta * det < 0) {
+                // No intersection found.
+               return null;    
+           }
+           if (det > 0){
+               if (alpha > det || beta > det){
+                   return null;
+               }
+           } else {
+               if (alpha < det || beta < det){
+                   return null;
+               }
+           }
+           return point(this.start.x + (alpha * pt1Dir.x / det),
+                        this.start.y + (alpha * pt1Dir.y / det));
+        },
+        
+        // @return the bearing (cardinal direction) of the line. For example N, W, or SE.
+        // @returns {String} One of the following bearings : NE, E, SE, S, SW, W, NW, N.
+        bearing: function() {
+            
+            var lat1 = toRad(this.start.y);
+            var lat2 = toRad(this.end.y);
+            var lon1 = this.start.x;
+            var lon2 = this.end.x;
+            var dLon = toRad(lon2 - lon1);
+            var y = sin(dLon) * cos(lat2);
+            var x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
+            var brng = toDeg(atan2(y, x));
+
+            var bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'];
+
+            var index = brng - 22.5;
+            if (index < 0)
+                index += 360;
+            index = parseInt(index / 45);
+
+            return bearings[index];
+        }
+    };
+
+    // Rectangle.
+    // ----------
+    function rect(x, y, w, h) {
+        if (!(this instanceof rect))
+            return new rect(x, y, w, h);
+        if (y === undefined) {
+            y = x.y;
+            w = x.width;
+            h = x.height;
+            x = x.x;        
+        }
+        this.x = x;
+        this.y = y;
+        this.width = w;
+        this.height = h;
+    }
+    
+    rect.prototype = {
+        toString: function() {
+           return this.origin().toString() + ' ' + this.corner().toString();
+        },
+        origin: function() {
+            return point(this.x, this.y);
+        },
+        corner: function() {
+            return point(this.x + this.width, this.y + this.height);
+        },
+        topRight: function() {
+            return point(this.x + this.width, this.y);
+        },
+        bottomLeft: function() {
+            return point(this.x, this.y + this.height);
+        },
+        center: function() {
+            return point(this.x + this.width/2, this.y + this.height/2);
+        },
+        // @return {boolean} true if rectangles intersect
+        intersect: function(r) {
+           var myOrigin = this.origin();
+           var myCorner = this.corner();
+           var rOrigin = r.origin();
+           var rCorner = r.corner();
+            
+           if (rCorner.x <= myOrigin.x ||
+               rCorner.y <= myOrigin.y ||
+               rOrigin.x >= myCorner.x ||
+               rOrigin.y >= myCorner.y) return false;
+           return true;
+        },
+        // @return {string} (left|right|top|bottom) side which is nearest to point
+        // @see Squeak Smalltalk, Rectangle>>sideNearestTo:
+        sideNearestToPoint: function(p) {
+            p = point(p);
+           var distToLeft = p.x - this.x;
+           var distToRight = (this.x + this.width) - p.x;
+           var distToTop = p.y - this.y;
+           var distToBottom = (this.y + this.height) - p.y;
+           var closest = distToLeft;
+           var side = 'left';
+            
+           if (distToRight < closest) {
+               closest = distToRight;
+               side = 'right';
+           }
+           if (distToTop < closest) {
+               closest = distToTop;
+               side = 'top';
+           }
+           if (distToBottom < closest) {
+               closest = distToBottom;
+               side = 'bottom';
+           }
+           return side;
+        },
+        // @return {bool} true if point p is insight me
+        containsPoint: function(p) {
+            p = point(p);
+           if (p.x >= this.x && p.x <= this.x + this.width &&
+               p.y >= this.y && p.y <= this.y + this.height) {
+               return true;
+           }
+           return false;
+        },
+        // Algorithm ported from java.awt.Rectangle from OpenJDK.
+        // @return {bool} true if rectangle `r` is inside me.
+        containsRect: function(r) {
+            var nr = rect(r).normalize();
+            var W = nr.width;
+            var H = nr.height;
+            var X = nr.x;
+            var Y = nr.y;
+            var w = this.width;
+            var h = this.height;
+            if ((w | h | W | H) < 0) {
+                // At least one of the dimensions is negative...
+                return false;
+            }
+            // Note: if any dimension is zero, tests below must return false...
+            var x = this.x;
+            var y = this.y;
+            if (X < x || Y < y) {
+                return false;
+            }
+            w += x;
+            W += X;
+            if (W <= X) {
+                // X+W overflowed or W was zero, return false if...
+                // either original w or W was zero or
+                // x+w did not overflow or
+                // the overflowed x+w is smaller than the overflowed X+W
+                if (w >= x || W > w) return false;
+            } else {
+                // X+W did not overflow and W was not zero, return false if...
+                // original w was zero or
+                // x+w did not overflow and x+w is smaller than X+W
+                if (w >= x && W > w) return false;
+            }
+            h += y;
+            H += Y;
+            if (H <= Y) {
+                if (h >= y || H > h) return false;
+            } else {
+                if (h >= y && H > h) return false;
+            }
+            return true;
+        },        
+        // @return {point} a point on my boundary nearest to p
+        // @see Squeak Smalltalk, Rectangle>>pointNearestTo:
+        pointNearestToPoint: function(p) {
+            p = point(p);
+           if (this.containsPoint(p)) {
+               var side = this.sideNearestToPoint(p);
+               switch (side){
+                 case "right": return point(this.x + this.width, p.y);
+                 case "left": return point(this.x, p.y);
+                 case "bottom": return point(p.x, this.y + this.height);
+                 case "top": return point(p.x, this.y);
+               }
+           }
+           return p.adhereToRect(this);
+        },
+        // Find point on my boundary where line starting
+        // from my center ending in point p intersects me.
+        // @param {number} angle If angle is specified, intersection with rotated rectangle is computed.
+        intersectionWithLineFromCenterToPoint: function(p, angle) {
+            p = point(p);
+           var center = point(this.x + this.width/2, this.y + this.height/2);
+            var result;
+            if (angle) p.rotate(center, angle);
+            
+           // (clockwise, starting from the top side)
+           var sides = [
+               line(this.origin(), this.topRight()),
+               line(this.topRight(), this.corner()),
+               line(this.corner(), this.bottomLeft()),
+               line(this.bottomLeft(), this.origin())
+           ];
+           var connector = line(center, p);
+            
+           for (var i = sides.length - 1; i >= 0; --i){
+               var intersection = sides[i].intersection(connector);
+               if (intersection !== null){
+                   result = intersection;
+                    break;
+               }
+           }
+            if (result && angle) result.rotate(center, -angle);
+            return result;
+        },
+        // Move and expand me.
+        // @param r {rectangle} representing deltas
+        moveAndExpand: function(r) {
+           this.x += r.x;
+           this.y += r.y;
+           this.width += r.width;
+           this.height += r.height;
+           return this;
+        },
+        round: function(decimals) {
+            this.x = decimals ? this.x.toFixed(decimals) : round(this.x);
+            this.y = decimals ? this.y.toFixed(decimals) : round(this.y);
+            this.width = decimals ? this.width.toFixed(decimals) : round(this.width);
+            this.height = decimals ? this.height.toFixed(decimals) : round(this.height);
+            return this;
+        },
+        // Normalize the rectangle; i.e., make it so that it has a non-negative width and height.
+        // If width < 0 the function swaps the left and right corners,
+        // and it swaps the top and bottom corners if height < 0
+        // like in http://qt-project.org/doc/qt-4.8/qrectf.html#normalized
+        normalize: function() {
+            var newx = this.x;
+            var newy = this.y;
+            var newwidth = this.width;
+            var newheight = this.height;
+            if (this.width < 0) {
+                newx = this.x + this.width;
+                newwidth = -this.width;
+            }
+            if (this.height < 0) {
+                newy = this.y + this.height;
+                newheight = -this.height;
+            }
+            this.x = newx;
+            this.y = newy;
+            this.width = newwidth;
+            this.height = newheight;
+            return this;
+        }        
+    };
+
+    // Ellipse.
+    // --------
+    function ellipse(c, a, b) {
+        if (!(this instanceof ellipse))
+            return new ellipse(c, a, b);
+        c = point(c);
+        this.x = c.x;
+        this.y = c.y;
+        this.a = a;
+        this.b = b;
+    }
+
+    ellipse.prototype = {
+        toString: function() {
+            return point(this.x, this.y).toString() + ' ' + this.a + ' ' + this.b;
+        },
+        bbox: function() {
+               return rect(this.x - this.a, this.y - this.b, 2*this.a, 2*this.b);
+        },
+        // Find point on me where line from my center to
+        // point p intersects my boundary.
+        // @param {number} angle If angle is specified, intersection with rotated ellipse is computed.
+        intersectionWithLineFromCenterToPoint: function(p, angle) {
+           p = point(p);
+            if (angle) p.rotate(point(this.x, this.y), angle);
+            var dx = p.x - this.x;
+           var dy = p.y - this.y;
+            var result;
+           if (dx === 0) {
+               result = this.bbox().pointNearestToPoint(p);
+                if (angle) return result.rotate(point(this.x, this.y), -angle);
+                return result;
+           }
+           var m = dy / dx;
+           var mSquared = m * m;
+           var aSquared = this.a * this.a;
+           var bSquared = this.b * this.b;
+           var x = sqrt(1 / ((1 / aSquared) + (mSquared / bSquared)));
+
+            x = dx < 0 ? -x : x;
+           var y = m * x;
+           result = point(this.x + x, this.y + y);
+            if (angle) return result.rotate(point(this.x, this.y), -angle);
+            return result;
+        }
+    };
+
+    // Bezier curve.
+    // -------------
+    var bezier = {
+        // Cubic Bezier curve path through points.
+        // Ported from C# implementation by Oleg V. Polikarpotchkin and Peter Lee (http://www.codeproject.com/KB/graphics/BezierSpline.aspx).
+        // @param {array} points Array of points through which the smooth line will go.
+        // @return {array} SVG Path commands as an array
+        curveThroughPoints: function(points) {
+            var controlPoints = this.getCurveControlPoints(points);
+            var path = ['M', points[0].x, points[0].y];
+
+            for (var i = 0; i < controlPoints[0].length; i++) {
+                path.push('C', controlPoints[0][i].x, controlPoints[0][i].y, controlPoints[1][i].x, controlPoints[1][i].y, points[i+1].x, points[i+1].y);        
+            }
+            return path;
+        },
+        
+        // Get open-ended Bezier Spline Control Points.
+        // @param knots Input Knot Bezier spline points (At least two points!).
+        // @param firstControlPoints Output First Control points. Array of knots.length - 1 length.
+        //  @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
+        getCurveControlPoints: function(knots) {
+            var firstControlPoints = [];
+            var secondControlPoints = [];
+            var n = knots.length - 1;
+            var i;
+
+            // Special case: Bezier curve should be a straight line.
+            if (n == 1) { 
+               // 3P1 = 2P0 + P3
+               firstControlPoints[0] = point((2 * knots[0].x + knots[1].x) / 3,
+                                             (2 * knots[0].y + knots[1].y) / 3);
+               // P2 = 2P1 – P0
+               secondControlPoints[0] = point(2 * firstControlPoints[0].x - knots[0].x,
+                                              2 * firstControlPoints[0].y - knots[0].y);
+               return [firstControlPoints, secondControlPoints];
+            }
+            
+                // Calculate first Bezier control points.
+            // Right hand side vector.
+            var rhs = [];
+            
+            // Set right hand side X values.
+            for (i = 1; i < n - 1; i++) {
+                rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
+            }
+            rhs[0] = knots[0].x + 2 * knots[1].x;
+            rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;
+            // Get first control points X-values.
+            var x = this.getFirstControlPoints(rhs);
+            
+            // Set right hand side Y values.
+            for (i = 1; i < n - 1; ++i) {
+               rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
+            }
+            rhs[0] = knots[0].y + 2 * knots[1].y;
+            rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;
+            // Get first control points Y-values.
+            var y = this.getFirstControlPoints(rhs);
+            
+            // Fill output arrays.
+            for (i = 0; i < n; i++) {
+               // First control point.
+               firstControlPoints.push(point(x[i], y[i]));
+               // Second control point.
+               if (i < n - 1) {
+                   secondControlPoints.push(point(2 * knots [i + 1].x - x[i + 1],
+                                                   2 * knots[i + 1].y - y[i + 1]));
+               } else {
+                   secondControlPoints.push(point((knots[n].x + x[n - 1]) / 2,
+                                                  (knots[n].y + y[n - 1]) / 2));
+               }
+            }
+            return [firstControlPoints, secondControlPoints];
+        },
+
+        // Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points.
+        // @param rhs Right hand side vector.
+        // @return Solution vector.
+        getFirstControlPoints: function(rhs) {
+            var n = rhs.length;
+            // `x` is a solution vector.
+            var x = [];
+            var tmp = [];
+            var b = 2.0;
+            
+            x[0] = rhs[0] / b;
+            // Decomposition and forward substitution.
+            for (var i = 1; i < n; i++) { 
+               tmp[i] = 1 / b;
+               b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
+               x[i] = (rhs[i] - x[i - 1]) / b;
+            }
+            for (i = 1; i < n; i++) {
+                // Backsubstitution.
+               x[n - i - 1] -= tmp[n - i] * x[n - i]; 
+            }
+            return x;
+        }
+    };
+
+    // Scale.
+    var scale = {
+
+        // Return the `value` from the `domain` interval scaled to the `range` interval.
+        linear: function(domain, range, value) {
+
+            var domainSpan = domain[1] - domain[0];
+            var rangeSpan = range[1] - range[0];
+            return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0;
+        }
+    };
+
+    return {
+
+        toDeg: toDeg,
+        toRad: toRad,
+        snapToGrid: snapToGrid,
+       normalizeAngle: normalizeAngle,
+        point: point,
+        line: line,
+        rect: rect,
+        ellipse: ellipse,
+        bezier: bezier,
+        scale: scale
+    }
+}));
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+if (typeof exports === 'object') {
+
+    var _ = require('lodash');
+}
+
+
+// Global namespace.
+
+var joint = {
+
+    // `joint.dia` namespace.
+    dia: {},
+
+    // `joint.ui` namespace.
+    ui: {},
+
+    // `joint.layout` namespace.
+    layout: {},
+
+    // `joint.shapes` namespace.
+    shapes: {},
+
+    // `joint.format` namespace.
+    format: {},
+
+    // `joint.connectors` namespace.
+    connectors: {},
+
+    // `joint.routers` namespace.
+    routers: {},
+
+    util: {
+
+        // Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/.
+        hashCode: function(str) {
+
+            var hash = 0;
+            if (str.length == 0) return hash;
+            for (var i = 0; i < str.length; i++) {
+                var c = str.charCodeAt(i);
+                hash = ((hash << 5) - hash) + c;
+                hash = hash & hash; // Convert to 32bit integer
+            }
+            return hash;
+        },
+
+        getByPath: function(obj, path, delim) {
+            
+            delim = delim || '.';
+            var keys = path.split(delim);
+            var key;
+            
+            while (keys.length) {
+                key = keys.shift();
+                if (key in obj) {
+                    obj = obj[key];
+                } else {
+                    return undefined;
+                }
+            }
+            return obj;
+        },
+
+        setByPath: function(obj, path, value, delim) {
+
+            delim = delim || '.';
+
+            var keys = path.split(delim);
+            var diver = obj;
+            var i = 0;
+
+            if (path.indexOf(delim) > -1) {
+
+                for (var len = keys.length; i < len - 1; i++) {
+                    // diver creates an empty object if there is no nested object under such a key.
+                    // This means that one can populate an empty nested object with setByPath().
+                    diver = diver[keys[i]] || (diver[keys[i]] = {});
+                }
+                diver[keys[len - 1]] = value;
+            } else {
+                obj[path] = value;
+            }
+            return obj;
+        },
+
+        unsetByPath: function(obj, path, delim) {
+
+            delim = delim || '.';
+
+            // index of the last delimiter
+            var i = path.lastIndexOf(delim);
+
+            if (i > -1) {
+
+                // unsetting a nested attribute
+                var parent = joint.util.getByPath(obj, path.substr(0, i), delim);
+
+                if (parent) {
+
+                    delete parent[path.slice(i + 1)];
+                }
+
+            } else {
+
+                // unsetting a primitive attribute
+                delete obj[path];
+            }
+
+            return obj;
+        },
+
+        flattenObject: function(obj, delim, stop) {
+            
+            delim = delim || '.';
+            var ret = {};
+           
+           for (var key in obj) {
+               if (!obj.hasOwnProperty(key)) continue;
+
+                var shouldGoDeeper = typeof obj[key] === 'object';
+                if (shouldGoDeeper && stop && stop(obj[key])) {
+                    shouldGoDeeper = false;
+                }
+                
+               if (shouldGoDeeper) {
+                   var flatObject = this.flattenObject(obj[key], delim, stop);
+                   for (var flatKey in flatObject) {
+                       if (!flatObject.hasOwnProperty(flatKey)) continue;
+                       
+                       ret[key + delim + flatKey] = flatObject[flatKey];
+                   }
+               } else {
+                   ret[key] = obj[key];
+               }
+           }
+           return ret;
+        },
+
+        uuid: function() {
+
+            // credit: http://stackoverflow.com/posts/2117523/revisions
+            
+            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
+                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
+                return v.toString(16);
+            });
+        },
+
+        // Generate global unique id for obj and store it as a property of the object.
+        guid: function(obj) {
+            
+            this.guid.id = this.guid.id || 1;
+            obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id);
+            return obj.id;
+        },
+
+        // Copy all the properties to the first argument from the following arguments.
+        // All the properties will be overwritten by the properties from the following
+        // arguments. Inherited properties are ignored.
+        mixin: function() {
+            
+            var target = arguments[0];
+            
+            for (var i = 1, l = arguments.length; i < l; i++) {
+                
+                var extension = arguments[i];
+                
+                // Only functions and objects can be mixined.
+
+                if ((Object(extension) !== extension) &&
+                    !_.isFunction(extension) &&
+                    (extension === null || extension === undefined)) {
+
+                    continue;
+                }
+
+                _.each(extension, function(copy, key) {
+                    
+                    if (this.mixin.deep && (Object(copy) === copy)) {
+
+                        if (!target[key]) {
+
+                            target[key] = _.isArray(copy) ? [] : {};
+                        }
+                        
+                        this.mixin(target[key], copy);
+                        return;
+                    }
+                    
+                    if (target[key] !== copy) {
+                        
+                        if (!this.mixin.supplement || !target.hasOwnProperty(key)) {
+                            
+                           target[key] = copy;
+                        }
+
+                    }
+                    
+                }, this);
+            }
+            
+            return target;
+        },
+
+        // Copy all properties to the first argument from the following
+        // arguments only in case if they don't exists in the first argument.
+        // All the function propererties in the first argument will get
+        // additional property base pointing to the extenders same named
+        // property function's call method.
+        supplement: function() {
+
+            this.mixin.supplement = true;
+            var ret = this.mixin.apply(this, arguments);
+            this.mixin.supplement = false;
+            return ret;
+        },
+
+        // Same as `mixin()` but deep version.
+        deepMixin: function() {
+            
+            this.mixin.deep = true;
+            var ret = this.mixin.apply(this, arguments);
+            this.mixin.deep = false;
+            return ret;
+        },
+
+        // Same as `supplement()` but deep version.
+        deepSupplement: function() {
+            
+            this.mixin.deep = this.mixin.supplement = true;
+            var ret = this.mixin.apply(this, arguments);
+            this.mixin.deep = this.mixin.supplement = false;
+            return ret;
+        },
+
+        normalizeEvent: function(evt) {
+
+            return (evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches.length) ? evt.originalEvent.changedTouches[0] : evt;
+        },
+
+       nextFrame:(function() {
+
+           var raf;
+           var client = typeof window != 'undefined';
+
+           if (client) {
+
+               raf = window.requestAnimationFrame       ||
+                     window.webkitRequestAnimationFrame ||
+                     window.mozRequestAnimationFrame    ||
+                     window.oRequestAnimationFrame      ||
+                     window.msRequestAnimationFrame;
+
+           }
+
+           if (!raf) {
+
+               var lastTime = 0;
+
+               raf = function(callback) {
+
+                   var currTime = new Date().getTime();
+                   var timeToCall = Math.max(0, 16 - (currTime - lastTime));
+                   var id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
+                   lastTime = currTime + timeToCall;
+                   return id;
+
+               };
+           }
+
+           return client ? _.bind(raf, window) : raf;
+       })(),
+
+       cancelFrame: (function() {
+
+           var caf;
+           var client = typeof window != 'undefined';
+
+           if (client) {
+
+               caf = window.cancelAnimationFrame              ||
+                     window.webkitCancelAnimationFrame        ||
+                     window.webkitCancelRequestAnimationFrame ||
+                     window.msCancelAnimationFrame            ||
+                     window.msCancelRequestAnimationFrame     ||
+                     window.oCancelAnimationFrame             ||
+                     window.oCancelRequestAnimationFrame      ||
+                     window.mozCancelAnimationFrame           ||
+                     window.mozCancelRequestAnimationFrame;
+
+           }
+
+           caf = caf || clearTimeout;
+
+           return client ? _.bind(caf, window) : caf;
+       })(),
+
+        breakText: function(text, size, styles, opt) {
+
+            opt = opt || {};
+
+            var width = size.width;
+            var height = size.height;
+
+            var svgDocument = opt.svgDocument || V('svg').node;
+            var textElement = V('<text><tspan></tspan></text>').attr(styles || {}).node;
+            var textSpan = textElement.firstChild;
+            var textNode = document.createTextNode('');
+
+            textSpan.appendChild(textNode);
+
+            svgDocument.appendChild(textElement);
+
+            if (!opt.svgDocument) {
+
+                document.body.appendChild(svgDocument);
+            }
+
+            var words = text.split(' ');
+            var full = [];
+            var lines = [];
+            var p;
+
+            for (var i = 0, l = 0, len = words.length; i < len; i++) {
+
+                var word = words[i];
+
+                textNode.data = lines[l] ? lines[l] + ' ' + word : word;
+
+                if (textSpan.getComputedTextLength() <= width) {
+
+                    // the current line fits
+                    lines[l] = textNode.data;
+
+                    if (p) {
+                        // We were partitioning. Put rest of the word onto next line
+                        full[l++] = true;
+
+                        // cancel partitioning
+                        p = 0;
+                    }
+
+                } else {
+
+                    if (!lines[l] || p) {
+
+                        var partition = !!p;
+
+                        p = word.length - 1;
+
+                        if (partition || !p) {
+
+                            // word has only one character.
+                            if (!p) {
+
+                                if (!lines[l]) {
+
+                                    // we won't fit this text within our rect
+                                    lines = [];
+
+                                    break;
+                                }
+
+                                // partitioning didn't help on the non-empty line
+                                // try again, but this time start with a new line
+
+                                // cancel partitions created
+                                words.splice(i,2, word + words[i+1]);
+
+                                // adjust word length
+                                len--;
+
+                                full[l++] = true;
+                                i--;
+
+                                continue;
+                            }
+
+                            // move last letter to the beginning of the next word
+                            words[i] = word.substring(0,p);
+                            words[i+1] = word.substring(p) + words[i+1];
+
+                        } else {
+
+                            // We initiate partitioning
+                            // split the long word into two words
+                            words.splice(i, 1, word.substring(0,p), word.substring(p));
+
+                            // adjust words length
+                            len++;
+
+                            if (l && !full[l-1]) {
+                                // if the previous line is not full, try to fit max part of
+                                // the current word there
+                                l--;
+                            }
+                        }
+
+                        i--;
+
+                        continue;
+                    }
+
+                    l++;
+                    i--;
+                }
+
+                // if size.height is defined we have to check whether the height of the entire
+                // text exceeds the rect height
+                if (typeof height !== 'undefined') {
+
+                    // get line height as text height / 0.8 (as text height is approx. 0.8em
+                    // and line height is 1em. See vectorizer.text())
+                    var lh = lh || textElement.getBBox().height * 1.25;
+
+                    if (lh * lines.length > height) {
+
+                        // remove overflowing lines
+                        lines.splice(Math.floor(height / lh));
+
+                        break;
+                    }
+                }
+            }
+
+            if (opt.svgDocument) {
+
+                // svg document was provided, remove the text element only
+                svgDocument.removeChild(textElement);
+
+            } else {
+
+                // clean svg document
+                document.body.removeChild(svgDocument);
+            }
+
+            return lines.join('\n');
+        },
+
+       timing: {
+
+           linear: function(t) {
+               return t;
+           },
+
+           quad: function(t) {
+               return t * t;
+           },
+
+           cubic: function(t) {
+               return t * t * t;
+           },
+
+           inout: function(t) {
+               if (t <= 0) return 0;
+               if (t >= 1) return 1;
+               var t2 = t * t, t3 = t2 * t;
+               return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
+           },
+
+           exponential: function(t) {
+               return Math.pow(2, 10 * (t - 1));
+           },
+
+           bounce: function(t) {
+               for(var a = 0, b = 1; 1; a += b, b /= 2) {
+                   if (t >= (7 - 4 * a) / 11) {
+                       var q = (11 - 6 * a - 11 * t) / 4;
+                       return -q * q + b * b;
+                   }
+               }
+           },
+
+           reverse: function(f) {
+               return function(t) {
+                   return 1 - f(1 - t)
+               }
+           },
+
+           reflect: function(f) {
+               return function(t) {
+                   return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t)));
+               };
+           },
+
+           clamp: function(f,n,x) {
+               n = n || 0;
+               x = x || 1;
+               return function(t) {
+                   var r = f(t);
+                   return r < n ? n : r > x ? x : r;
+               }
+           },
+
+           back: function(s) {
+               if (!s) s = 1.70158;
+               return function(t) {
+                   return t * t * ((s + 1) * t - s);
+               };
+           },
+
+           elastic: function(x) {
+               if (!x) x = 1.5;
+               return function(t) {
+                   return Math.pow(2, 10 * (t - 1)) * Math.cos(20*Math.PI*x/3*t);
+               }
+           }
+
+       },
+
+       interpolate: {
+
+           number: function(a, b) {
+               var d = b - a;
+               return function(t) { return a + d * t; };
+           },
+
+           object: function(a, b) {
+               var s = _.keys(a);
+               return function(t) {
+                   var i, p, r = {};
+                   for (i = s.length - 1; i != -1; i--) {
+                       p = s[i];
+                       r[p] = a[p] + (b[p] - a[p]) * t;
+                   }
+                   return  r;
+               }
+           },
+
+           hexColor: function(a, b) {
+
+               var ca = parseInt(a.slice(1), 16), cb = parseInt(b.slice(1), 16);
+
+               var ra = ca & 0x0000ff, rd = (cb & 0x0000ff) - ra;
+               var ga = ca & 0x00ff00, gd = (cb & 0x00ff00) - ga;
+               var ba = ca & 0xff0000, bd = (cb & 0xff0000) - ba;
+
+               return function(t) {
+                    var r = (ra + rd * t) & 0x000000ff;
+                    var g = (ga + gd * t) & 0x0000ff00;
+                    var b = (ba + bd * t) & 0x00ff0000;
+                   return '#' + (1 << 24 | r | g | b ).toString(16).slice(1);
+               };
+           },
+
+           unit: function(a, b) {
+
+               var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/;
+
+               var ma = r.exec(a), mb = r.exec(b);
+               var p = mb[1].indexOf('.'), f = p > 0 ? mb[1].length - p - 1 : 0;
+               var a = +ma[1], d = +mb[1] - a, u = ma[2];
+
+               return function(t) {
+                   return (a + d * t).toFixed(f) + u;
+               }
+           }
+       },
+
+        // SVG filters.
+        filter: {
+
+            // `x` ... horizontal blur
+            // `y` ... vertical blur (optional)
+            blur: function(args) {
+                
+                var x = _.isFinite(args.x) ? args.x : 2;
+
+                return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>', {
+                    stdDeviation: _.isFinite(args.y) ? [x, args.y] : x
+                });
+            },
+
+            // `dx` ... horizontal shift
+            // `dy` ... vertical shift
+            // `blur` ... blur
+            // `color` ... color
+            // `opacity` ... opacity
+            dropShadow: function(args) {
+
+                var tpl = 'SVGFEDropShadowElement' in window
+                    ? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>'
+                    : '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>';
+
+                return _.template(tpl, {
+                    dx: args.dx || 0,
+                    dy: args.dy || 0,
+                    opacity: _.isFinite(args.opacity) ? args.opacity : 1,
+                    color: args.color || 'black',
+                    blur: _.isFinite(args.blur) ? args.blur : 4
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged.
+            grayscale: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+                
+                return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>', {
+                    a: 0.2126 + 0.7874 * (1 - amount),
+                    b: 0.7152 - 0.7152 * (1 - amount),
+                    c: 0.0722 - 0.0722 * (1 - amount),
+                    d: 0.2126 - 0.2126 * (1 - amount),
+                    e: 0.7152 + 0.2848 * (1 - amount),
+                    f: 0.0722 - 0.0722 * (1 - amount),
+                    g: 0.2126 - 0.2126 * (1 - amount),
+                    h: 0.0722 + 0.9278 * (1 - amount)
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 1 is completely sepia. A value of 0 leaves the input unchanged.
+            sepia: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+
+                return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>', {
+                    a: 0.393 + 0.607 * (1 - amount),
+                    b: 0.769 - 0.769 * (1 - amount),
+                    c: 0.189 - 0.189 * (1 - amount),
+                    d: 0.349 - 0.349 * (1 - amount),
+                    e: 0.686 + 0.314 * (1 - amount),
+                    f: 0.168 - 0.168 * (1 - amount),
+                    g: 0.272 - 0.272 * (1 - amount),
+                    h: 0.534 - 0.534 * (1 - amount),
+                    i: 0.131 + 0.869 * (1 - amount)
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged.
+            saturate: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+
+                return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', {
+                    amount: 1 - amount
+                });
+            },
+
+            // `angle` ...  the number of degrees around the color circle the input samples will be adjusted.
+            hueRotate: function(args) {
+
+                return _.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>', {
+                    angle: args.angle || 0
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 1 is completely inverted. A value of 0 leaves the input unchanged.
+            invert: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+                
+                return _.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>', {
+                    amount: amount,
+                    amount2: 1 - amount
+                });
+            },
+
+            // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
+            brightness: function(args) {
+
+                return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>', {
+                    amount: _.isFinite(args.amount) ? args.amount : 1
+                });
+            },
+
+            // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
+            contrast: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+                
+                return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>', {
+                    amount: amount,
+                    amount2: .5 - amount / 2
+                });
+            }
+        },
+
+        format: {
+
+            // Formatting numbers via the Python Format Specification Mini-language.
+            // See http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
+            // Heavilly inspired by the D3.js library implementation.
+            number: function(specifier, value, locale) {
+
+                locale = locale || {
+
+                    currency: ['$', ''],
+                    decimal: '.',
+                    thousands: ',',
+                    grouping: [3]
+                };
+                
+                // See Python format specification mini-language: http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
+                // [[fill]align][sign][symbol][0][width][,][.precision][type]
+                var re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
+
+                var match = re.exec(specifier);
+                var fill = match[1] || ' ';
+                var align = match[2] || '>';
+                var sign = match[3] || '';
+                var symbol = match[4] || '';
+                var zfill = match[5];
+                var width = +match[6];
+                var comma = match[7];
+                var precision = match[8];
+                var type = match[9];
+                var scale = 1;
+                var prefix = '';
+                var suffix = '';
+                var integer = false;
+
+                if (precision) precision = +precision.substring(1);
+                
+                if (zfill || fill === '0' && align === '=') {
+                    zfill = fill = '0';
+                    align = '=';
+                    if (comma) width -= Math.floor((width - 1) / 4);
+                }
+
+                switch (type) {
+                  case 'n': comma = true; type = 'g'; break;
+                  case '%': scale = 100; suffix = '%'; type = 'f'; break;
+                  case 'p': scale = 100; suffix = '%'; type = 'r'; break;
+                  case 'b':
+                  case 'o':
+                  case 'x':
+                  case 'X': if (symbol === '#') prefix = '0' + type.toLowerCase();
+                  case 'c':
+                  case 'd': integer = true; precision = 0; break;
+                  case 's': scale = -1; type = 'r'; break;
+                }
+
+                if (symbol === '$') {
+                    prefix = locale.currency[0];
+                    suffix = locale.currency[1];
+                }
+
+                // If no precision is specified for `'r'`, fallback to general notation.
+                if (type == 'r' && !precision) type = 'g';
+
+                // Ensure that the requested precision is in the supported range.
+                if (precision != null) {
+                    if (type == 'g') precision = Math.max(1, Math.min(21, precision));
+                    else if (type == 'e' || type == 'f') precision = Math.max(0, Math.min(20, precision));
+                }
+
+                var zcomma = zfill && comma;
+
+                // Return the empty string for floats formatted as ints.
+                if (integer && (value % 1)) return '';
+
+                // Convert negative to positive, and record the sign prefix.
+                var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, '-') : sign;
+
+                var fullSuffix = suffix;
+                
+                // Apply the scale, computing it from the value's exponent for si format.
+                // Preserve the existing suffix, if any, such as the currency symbol.
+                if (scale < 0) {
+                    var unit = this.prefix(value, precision);
+                    value = unit.scale(value);
+                    fullSuffix = unit.symbol + suffix;
+                } else {
+                    value *= scale;
+                }
+
+                // Convert to the desired precision.
+                value = this.convert(type, value, precision);
+
+                // Break the value into the integer part (before) and decimal part (after).
+                var i = value.lastIndexOf('.');
+                var before = i < 0 ? value : value.substring(0, i);
+                var after = i < 0 ? '' : locale.decimal + value.substring(i + 1);
+
+                function formatGroup(value) {
+                    
+                    var i = value.length;
+                    var t = [];
+                    var j = 0;
+                    var g = locale.grouping[0];
+                    while (i > 0 && g > 0) {
+                        t.push(value.substring(i -= g, i + g));
+                        g = locale.grouping[j = (j + 1) % locale.grouping.length];
+                    }
+                    return t.reverse().join(locale.thousands);
+                }
+                
+                // If the fill character is not `'0'`, grouping is applied before padding.
+                if (!zfill && comma && locale.grouping) {
+
+                    before = formatGroup(before);
+                }
+
+                var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length);
+                var padding = length < width ? new Array(length = width - length + 1).join(fill) : '';
+
+                // If the fill character is `'0'`, grouping is applied after padding.
+                if (zcomma) before = formatGroup(padding + before);
+
+                // Apply prefix.
+                negative += prefix;
+
+                // Rejoin integer and decimal parts.
+                value = before + after;
+
+                return (align === '<' ? negative + value + padding
+                        : align === '>' ? padding + negative + value
+                        : align === '^' ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length)
+                        : negative + (zcomma ? value : padding + value)) + fullSuffix;
+            },
+
+            convert: function(type, value, precision) {
+
+                switch (type) {
+                  case 'b': return value.toString(2);
+                  case 'c': return String.fromCharCode(value);
+                  case 'o': return value.toString(8);
+                  case 'x': return value.toString(16);
+                  case 'X': return value.toString(16).toUpperCase();
+                  case 'g': return value.toPrecision(precision);
+                  case 'e': return value.toExponential(precision);
+                  case 'f': return value.toFixed(precision);
+                  case 'r': return (value = this.round(value, this.precision(value, precision))).toFixed(Math.max(0, Math.min(20, this.precision(value * (1 + 1e-15), precision))));
+                default: return value + '';
+                }
+            },
+
+            round: function(value, precision) {
+
+                return precision
+                    ? Math.round(value * (precision = Math.pow(10, precision))) / precision
+                    : Math.round(value);
+            },
+
+            precision: function(value, precision) {
+                
+                return precision - (value ? Math.ceil(Math.log(value) / Math.LN10) : 1);
+            },
+
+            prefix: function(value, precision) {
+
+                var prefixes = _.map(['y','z','a','f','p','n','µ','m','','k','M','G','T','P','E','Z','Y'], function(d, i) {
+                    var k = Math.pow(10, abs(8 - i) * 3);
+                    return {
+                        scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; },
+                        symbol: d
+                    };
+                });
+                
+                var i = 0;
+                if (value) {
+                    if (value < 0) value *= -1;
+                    if (precision) value = d3.round(value, this.precision(value, precision));
+                    i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
+                    i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3));
+                }
+                return prefixes[8 + i / 3];
+            }
+        }
+    }
+};
+
+if (typeof exports === 'object') {
+
+    module.exports = joint;
+}
+
+//      JointJS, the JavaScript diagramming library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        dia: {
+            Link: require('./joint.dia.link').Link,
+            Element: require('./joint.dia.element').Element
+        },
+        shapes: require('../plugins/shapes')
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+    var g = require('./geometry');
+}
+
+
+
+joint.dia.GraphCells = Backbone.Collection.extend({
+
+    initialize: function() {
+        
+        // Backbone automatically doesn't trigger re-sort if models attributes are changed later when
+        // they're already in the collection. Therefore, we're triggering sort manually here.
+        this.on('change:z', this.sort, this);
+    },
+
+    model: function(attrs, options) {
+
+        if (attrs.type === 'link') {
+
+            return new joint.dia.Link(attrs, options);
+        }
+
+        var module = attrs.type.split('.')[0];
+        var entity = attrs.type.split('.')[1];
+
+        if (joint.shapes[module] && joint.shapes[module][entity]) {
+
+            return new joint.shapes[module][entity](attrs, options);
+        }
+        
+        return new joint.dia.Element(attrs, options);
+    },
+
+    // `comparator` makes it easy to sort cells based on their `z` index.
+    comparator: function(model) {
+
+        return model.get('z') || 0;
+    },
+
+    // Get all inbound and outbound links connected to the cell `model`.
+    getConnectedLinks: function(model, opt) {
+
+        opt = opt || {};
+
+        if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) {
+            opt.inbound = opt.outbound = true;
+        }
+
+        var links = [];
+        
+        this.each(function(cell) {
+
+            var source = cell.get('source');
+            var target = cell.get('target');
+
+            if (source && source.id === model.id && opt.outbound) {
+                
+                links.push(cell);
+            }
+
+            if (target && target.id === model.id && opt.inbound) {
+
+                links.push(cell);
+            }
+        });
+
+        return links;
+    }
+});
+
+
+joint.dia.Graph = Backbone.Model.extend({
+
+    initialize: function() {
+
+        this.set('cells', new joint.dia.GraphCells);
+
+        // Make all the events fired in the `cells` collection available.
+        // to the outside world.
+        this.get('cells').on('all', this.trigger, this);
+        
+        this.get('cells').on('remove', this.removeCell, this);
+    },
+
+    toJSON: function() {
+
+        // Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections.
+        // It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitely.
+        var json = Backbone.Model.prototype.toJSON.apply(this, arguments);
+        json.cells = this.get('cells').toJSON();
+        return json;
+    },
+
+    fromJSON: function(json) {
+
+        if (!json.cells) {
+
+            throw new Error('Graph JSON must contain cells array.');
+        }
+
+        var attrs = json;
+
+        // Cells are the only attribute that is being set differently, using `cells.add()`.
+        var cells = json.cells;
+        delete attrs.cells;
+        
+        this.set(attrs);
+        
+        this.resetCells(cells);
+    },
+
+    clear: function() {
+
+        this.trigger('batch:start');
+        this.get('cells').remove(this.get('cells').models);
+        this.trigger('batch:stop');
+    },
+
+    _prepareCell: function(cell) {
+
+        if (cell instanceof Backbone.Model && _.isUndefined(cell.get('z'))) {
+
+            cell.set('z', this.maxZIndex() + 1, { silent: true });
+            
+        } else if (_.isUndefined(cell.z)) {
+
+            cell.z = this.maxZIndex() + 1;
+        }
+
+        return cell;
+    },
+
+    maxZIndex: function() {
+
+        var lastCell = this.get('cells').last();
+        return lastCell ? (lastCell.get('z') || 0) : 0;
+    },
+
+    addCell: function(cell, options) {
+
+        if (_.isArray(cell)) {
+
+            return this.addCells(cell, options);
+        }
+
+        this.get('cells').add(this._prepareCell(cell), options || {});
+
+        return this;
+    },
+
+    addCells: function(cells, options) {
+
+        _.each(cells, function(cell) { this.addCell(cell, options); }, this);
+
+        return this;
+    },
+
+    // When adding a lot of cells, it is much more efficient to
+    // reset the entire cells collection in one go.
+    // Useful for bulk operations and optimizations.
+    resetCells: function(cells) {
+        
+        this.get('cells').reset(_.map(cells, this._prepareCell, this));
+
+        return this;
+    },
+
+    removeCell: function(cell, collection, options) {
+
+        // Applications might provide a `disconnectLinks` option set to `true` in order to
+        // disconnect links when a cell is removed rather then removing them. The default
+        // is to remove all the associated links.
+        if (options && options.disconnectLinks) {
+            
+            this.disconnectLinks(cell);
+
+        } else {
+
+            this.removeLinks(cell);
+        }
+
+        // Silently remove the cell from the cells collection. Silently, because
+        // `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is
+        // then propagated to the graph model. If we didn't remove the cell silently, two `remove` events
+        // would be triggered on the graph model.
+        this.get('cells').remove(cell, { silent: true });
+    },
+
+    // Get a cell by `id`.
+    getCell: function(id) {
+
+        return this.get('cells').get(id);
+    },
+
+    getElements: function() {
+
+        return this.get('cells').filter(function(cell) {
+
+            return cell instanceof joint.dia.Element;
+        });
+    },
+    
+    getLinks: function() {
+
+        return this.get('cells').filter(function(cell) {
+
+            return cell instanceof joint.dia.Link;
+        });
+    },
+
+    // Get all inbound and outbound links connected to the cell `model`.
+    getConnectedLinks: function(model, opt) {
+
+        return this.get('cells').getConnectedLinks(model, opt);
+    },
+
+    getNeighbors: function(el) {
+
+        var links = this.getConnectedLinks(el);
+        var neighbors = [];
+        var cells = this.get('cells');
+        
+        _.each(links, function(link) {
+
+            var source = link.get('source');
+            var target = link.get('target');
+
+            // Discard if it is a point.
+            if (!source.x) {
+                var sourceElement = cells.get(source.id);
+                if (sourceElement !== el) {
+
+                    neighbors.push(sourceElement);
+                }
+            }
+            if (!target.x) {
+                var targetElement = cells.get(target.id);
+                if (targetElement !== el) {
+
+                    neighbors.push(targetElement);
+                }
+            }
+        });
+
+        return neighbors;
+    },
+    
+    // Disconnect links connected to the cell `model`.
+    disconnectLinks: function(model) {
+
+        _.each(this.getConnectedLinks(model), function(link) {
+
+            link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0));
+        });
+    },
+
+    // Remove links connected to the cell `model` completely.
+    removeLinks: function(model) {
+
+        _.invoke(this.getConnectedLinks(model), 'remove');
+    },
+
+    // Find all views at given point
+    findModelsFromPoint: function(p) {
+
+       return _.filter(this.getElements(), function(el) {
+           return el.getBBox().containsPoint(p);
+       });
+    },
+
+
+    // Find all views in given area
+    findModelsInArea: function(r) {
+
+       return _.filter(this.getElements(), function(el) {
+           return el.getBBox().intersect(r);
+       });
+    }
+
+});
+
+
+if (typeof exports === 'object') {
+
+    module.exports.Graph = joint.dia.Graph;
+}
+//      JointJS.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('./core').util,
+        dia: {
+            Link: require('./joint.dia.link').Link
+        }
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+}
+
+
+// joint.dia.Cell base model.
+// --------------------------
+
+joint.dia.Cell = Backbone.Model.extend({
+
+    // This is the same as Backbone.Model with the only difference that is uses _.merge
+    // instead of just _.extend. The reason is that we want to mixin attributes set in upper classes.
+    constructor: function(attributes, options) {
+
+        var defaults;
+        var attrs = attributes || {};
+        this.cid = _.uniqueId('c');
+        this.attributes = {};
+        if (options && options.collection) this.collection = options.collection;
+        if (options && options.parse) attrs = this.parse(attrs, options) || {};
+        if (defaults = _.result(this, 'defaults')) {
+            //<custom code>
+            // Replaced the call to _.defaults with _.merge.
+            attrs = _.merge({}, defaults, attrs);
+            //</custom code>
+        }
+        this.set(attrs, options);
+        this.changed = {};
+        this.initialize.apply(this, arguments);
+    },
+
+    toJSON: function() {
+
+        var defaultAttrs = this.constructor.prototype.defaults.attrs || {};
+        var attrs = this.attributes.attrs;
+        var finalAttrs = {};
+
+        // Loop through all the attributes and
+        // omit the default attributes as they are implicitly reconstructable by the cell 'type'.
+        _.each(attrs, function(attr, selector) {
+
+            var defaultAttr = defaultAttrs[selector];
+
+            _.each(attr, function(value, name) {
+                
+                // attr is mainly flat though it might have one more level (consider the `style` attribute).
+                // Check if the `value` is object and if yes, go one level deep.
+                if (_.isObject(value) && !_.isArray(value)) {
+                    
+                    _.each(value, function(value2, name2) {
+
+                        if (!defaultAttr || !defaultAttr[name] || !_.isEqual(defaultAttr[name][name2], value2)) {
+
+                            finalAttrs[selector] = finalAttrs[selector] || {};
+                            (finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2;
+                        }
+                    });
+
+                } else if (!defaultAttr || !_.isEqual(defaultAttr[name], value)) {
+                    // `value` is not an object, default attribute for such a selector does not exist
+                    // or it is different than the attribute value set on the model.
+
+                    finalAttrs[selector] = finalAttrs[selector] || {};
+                    finalAttrs[selector][name] = value;
+                }
+            });
+        });
+
+        var attributes = _.cloneDeep(_.omit(this.attributes, 'attrs'));
+        //var attributes = JSON.parse(JSON.stringify(_.omit(this.attributes, 'attrs')));
+        attributes.attrs = finalAttrs;
+
+        return attributes;
+    },
+
+    initialize: function(options) {
+
+        if (!options || !options.id) {
+
+            this.set('id', joint.util.uuid(), { silent: true });
+        }
+
+       this._transitionIds = {};
+
+        // Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes.
+        this.processPorts();
+        this.on('change:attrs', this.processPorts, this);
+    },
+
+    processPorts: function() {
+
+        // Whenever `attrs` changes, we extract ports from the `attrs` object and store it
+        // in a more accessible way. Also, if any port got removed and there were links that had `target`/`source`
+        // set to that port, we remove those links as well (to follow the same behaviour as
+        // with a removed element).
+
+        var previousPorts = this.ports;
+
+        // Collect ports from the `attrs` object.
+        var ports = {};
+        _.each(this.get('attrs'), function(attrs, selector) {
+
+            if (attrs && attrs.port) {
+
+                // `port` can either be directly an `id` or an object containing an `id` (and potentially other data).
+                if (!_.isUndefined(attrs.port.id)) {
+                    ports[attrs.port.id] = attrs.port;
+                } else {
+                    ports[attrs.port] = { id: attrs.port };
+                }
+            }
+        });
+
+        // Collect ports that have been removed (compared to the previous ports) - if any.
+        // Use hash table for quick lookup.
+        var removedPorts = {};
+        _.each(previousPorts, function(port, id) {
+
+            if (!ports[id]) removedPorts[id] = true;
+        });
+
+        // Remove all the incoming/outgoing links that have source/target port set to any of the removed ports.
+        if (this.collection && !_.isEmpty(removedPorts)) {
+            
+            var inboundLinks = this.collection.getConnectedLinks(this, { inbound: true });
+            _.each(inboundLinks, function(link) {
+
+                if (removedPorts[link.get('target').port]) link.remove();
+            });
+
+            var outboundLinks = this.collection.getConnectedLinks(this, { outbound: true });
+            _.each(outboundLinks, function(link) {
+
+                if (removedPorts[link.get('source').port]) link.remove();
+            });
+        }
+
+        // Update the `ports` object.
+        this.ports = ports;
+    },
+
+    remove: function(options) {
+
+       var collection = this.collection;
+
+       if (collection) {
+           collection.trigger('batch:start');
+       }
+
+        // First, unembed this cell from its parent cell if there is one.
+        var parentCellId = this.get('parent');
+        if (parentCellId) {
+            
+            var parentCell = this.collection && this.collection.get(parentCellId);
+            parentCell.unembed(this);
+        }
+        
+        _.invoke(this.getEmbeddedCells(), 'remove', options);
+        
+        this.trigger('remove', this, this.collection, options);
+
+       if (collection) {
+           collection.trigger('batch:stop');
+       }
+    },
+
+    toFront: function() {
+
+        if (this.collection) {
+
+            this.set('z', (this.collection.last().get('z') || 0) + 1);
+        }
+    },
+    
+    toBack: function() {
+
+        if (this.collection) {
+            
+            this.set('z', (this.collection.first().get('z') || 0) - 1);
+        }
+    },
+
+    embed: function(cell) {
+
+       if (this.get('parent') == cell.id) {
+
+           throw new Error('Recursive embedding not allowed.');
+
+       } else {
+
+           this.trigger('batch:start');
+
+           cell.set('parent', this.id);
+           this.set('embeds', _.uniq((this.get('embeds') || []).concat([cell.id])));
+
+           this.trigger('batch:stop');
+       }
+    },
+
+    unembed: function(cell) {
+
+       this.trigger('batch:start');
+
+        var cellId = cell.id;
+        cell.unset('parent');
+
+        this.set('embeds', _.without(this.get('embeds'), cellId));
+
+       this.trigger('batch:stop');
+    },
+
+    getEmbeddedCells: function() {
+
+        // Cell models can only be retrieved when this element is part of a collection.
+        // There is no way this element knows about other cells otherwise.
+        // This also means that calling e.g. `translate()` on an element with embeds before
+        // adding it to a graph does not translate its embeds.
+        if (this.collection) {
+
+            return _.map(this.get('embeds') || [], function(cellId) {
+
+                return this.collection.get(cellId);
+                
+            }, this);
+        }
+        return [];
+    },
+
+    clone: function(opt) {
+
+        opt = opt || {};
+
+        var clone = Backbone.Model.prototype.clone.apply(this, arguments);
+        
+        // We don't want the clone to have the same ID as the original.
+        clone.set('id', joint.util.uuid(), { silent: true });
+        clone.set('embeds', '');
+
+        if (!opt.deep) return clone;
+
+        // The rest of the `clone()` method deals with embeds. If `deep` option is set to `true`,
+        // the return value is an array of all the embedded clones created.
+
+        var embeds = this.getEmbeddedCells();
+
+        var clones = [clone];
+
+        // This mapping stores cloned links under the `id`s of they originals.
+        // This prevents cloning a link more then once. Consider a link 'self loop' for example.
+        var linkCloneMapping = {};
+        
+        _.each(embeds, function(embed) {
+
+            var embedClones = embed.clone({ deep: true });
+
+            // Embed the first clone returned from `clone({ deep: true })` above. The first
+            // cell is always the clone of the cell that called the `clone()` method, i.e. clone of `embed` in this case.
+            clone.embed(embedClones[0]);
+
+            _.each(embedClones, function(embedClone) {
+
+                clones.push(embedClone);
+
+                // Skip links. Inbound/outbound links are not relevant for them.
+                if (embedClone instanceof joint.dia.Link) {
+
+                    return;
+                }
+
+                // Collect all inbound links, clone them (if not done already) and set their target to the `embedClone.id`.
+                var inboundLinks = this.collection.getConnectedLinks(embed, { inbound: true });
+
+                _.each(inboundLinks, function(link) {
+
+                    var linkClone = linkCloneMapping[link.id] || link.clone();
+
+                    // Make sure we don't clone a link more then once.
+                    linkCloneMapping[link.id] = linkClone;
+
+                    var target = _.clone(linkClone.get('target'));
+                    target.id = embedClone.id;
+                    linkClone.set('target', target);
+                });
+
+                // Collect all inbound links, clone them (if not done already) and set their source to the `embedClone.id`.
+                var outboundLinks = this.collection.getConnectedLinks(embed, { outbound: true });
+
+                _.each(outboundLinks, function(link) {
+
+                    var linkClone = linkCloneMapping[link.id] || link.clone();
+
+                    // Make sure we don't clone a link more then once.
+                    linkCloneMapping[link.id] = linkClone;
+
+                    var source = _.clone(linkClone.get('source'));
+                    source.id = embedClone.id;
+                    linkClone.set('source', source);
+                });
+
+            }, this);
+            
+        }, this);
+
+        // Add link clones to the array of all the new clones.
+        clones = clones.concat(_.values(linkCloneMapping));
+
+        return clones;
+    },
+
+    // A convenient way to set nested attributes.
+    attr: function(attrs, value, opt) {
+
+        var currentAttrs = this.get('attrs');
+        var delim = '/';
+        
+        if (_.isString(attrs)) {
+            // Get/set an attribute by a special path syntax that delimits
+            // nested objects by the colon character.
+
+            if (typeof value != 'undefined') {
+
+                var attr = {};
+                joint.util.setByPath(attr, attrs, value, delim);
+                return this.set('attrs', _.merge({}, currentAttrs, attr), opt);
+                
+            } else {
+                
+                return joint.util.getByPath(currentAttrs, attrs, delim);
+            }
+        }
+        
+        return this.set('attrs', _.merge({}, currentAttrs, attrs), value, opt);
+    },
+
+    // A convenient way to unset nested attributes
+    removeAttr: function(path, opt) {
+
+        if (_.isArray(path)) {
+            _.each(path, function(p) { this.removeAttr(p, opt); }, this);
+            return this;
+        }
+        
+        var attrs = joint.util.unsetByPath(_.merge({}, this.get('attrs')), path, '/');
+
+        return this.set('attrs', attrs, _.extend({ dirty: true }, opt));
+    },
+
+    transition: function(path, value, opt, delim) {
+
+       delim = delim || '/';
+
+       var defaults = {
+           duration: 100,
+           delay: 10,
+           timingFunction: joint.util.timing.linear,
+           valueFunction: joint.util.interpolate.number
+       };
+
+       opt = _.extend(defaults, opt);
+
+       var pathArray = path.split(delim);
+        var property = pathArray[0];
+       var isPropertyNested = pathArray.length > 1;
+       var firstFrameTime = 0;
+       var interpolatingFunction;
+
+       var setter = _.bind(function(runtime) {
+
+           var id, progress, propertyValue, status;
+
+           firstFrameTime = firstFrameTime || runtime;
+           runtime -= firstFrameTime;
+           progress = runtime / opt.duration;
+
+           if (progress < 1) {
+               this._transitionIds[path] = id = joint.util.nextFrame(setter);
+           } else {
+               progress = 1;
+               delete this._transitionIds[path];
+           }
+
+           propertyValue = interpolatingFunction(opt.timingFunction(progress));
+
+           if (isPropertyNested) {
+               var nestedPropertyValue = joint.util.setByPath({}, path, propertyValue, delim)[property];
+               propertyValue = _.merge({}, this.get(property), nestedPropertyValue);
+           }
+
+           opt.transitionId = id;
+
+           this.set(property, propertyValue, opt);
+
+           if (!id) this.trigger('transition:end', this, path);
+
+       }, this);
+
+       var initiator =_.bind(function(callback) {
+
+           this.stopTransitions(path);
+
+           interpolatingFunction = opt.valueFunction(joint.util.getByPath(this.attributes, path, delim), value);
+
+           this._transitionIds[path] = joint.util.nextFrame(callback);
+
+           this.trigger('transition:start', this, path);
+
+       }, this);
+
+       return _.delay(initiator, opt.delay, setter);
+    },
+
+    getTransitions: function() {
+       return _.keys(this._transitionIds);
+    },
+
+    stopTransitions: function(path, delim) {
+
+       delim = delim || '/';
+
+       var pathArray = path && path.split(delim);
+
+       _(this._transitionIds).keys().filter(pathArray && function(key) {
+
+           return _.isEqual(pathArray, key.split(delim).slice(0, pathArray.length));
+
+       }).each(function(key) {
+
+           joint.util.cancelFrame(this._transitionIds[key]);
+
+           delete this._transitionIds[key];
+
+           this.trigger('transition:end', this, key);
+
+       }, this);
+    }
+});
+
+// joint.dia.CellView base view and controller.
+// --------------------------------------------
+
+// This is the base view and controller for `joint.dia.ElementView` and `joint.dia.LinkView`.
+
+joint.dia.CellView = Backbone.View.extend({
+
+    tagName: 'g',
+
+    attributes: function() {
+
+        return { 'model-id': this.model.id }
+    },
+
+    initialize: function() {
+
+        _.bindAll(this, 'remove', 'update');
+
+        // Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree.
+        this.$el.data('view', this);
+
+       this.listenTo(this.model, 'remove', this.remove);
+       this.listenTo(this.model, 'change:attrs', this.onChangeAttrs);
+    },
+
+    onChangeAttrs: function(cell, attrs, opt) {
+
+        if (opt.dirty) {
+
+            // dirty flag could be set when a model attribute was removed and it needs to be cleared
+            // also from the DOM element. See cell.removeAttr().
+            return this.render();
+        }
+
+        return this.update();
+    },
+
+    _configure: function(options) {
+
+        // Make sure a global unique id is assigned to this view. Store this id also to the properties object.
+        // The global unique id makes sure that the same view can be rendered on e.g. different machines and
+        // still be associated to the same object among all those clients. This is necessary for real-time
+        // collaboration mechanism.
+        options.id = options.id || joint.util.guid(this);
+        
+        Backbone.View.prototype._configure.apply(this, arguments);
+    },
+
+    // Override the Backbone `_ensureElement()` method in order to create a `<g>` node that wraps
+    // all the nodes of the Cell view.
+    _ensureElement: function() {
+
+        var el;
+
+        if (!this.el) {
+
+            var attrs = _.extend({ id: this.id }, _.result(this, 'attributes'));
+            if (this.className) attrs['class'] = _.result(this, 'className');
+            el = V(_.result(this, 'tagName'), attrs).node;
+
+        } else {
+
+            el = _.result(this, 'el')
+        }
+
+        this.setElement(el, false);
+    },
+    
+    findBySelector: function(selector) {
+
+        // These are either descendants of `this.$el` of `this.$el` itself. 
+       // `.` is a special selector used to select the wrapping `<g>` element.
+        var $selected = selector === '.' ? this.$el : this.$el.find(selector);
+        return $selected;
+    },
+
+    notify: function(evt) {
+
+        if (this.paper) {
+
+            var args = Array.prototype.slice.call(arguments, 1);
+
+            // Trigger the event on both the element itself and also on the paper.
+            this.trigger.apply(this, [evt].concat(args));
+            
+            // Paper event handlers receive the view object as the first argument.
+            this.paper.trigger.apply(this.paper, [evt, this].concat(args));
+        }
+    },
+
+    getStrokeBBox: function(el) {
+        // Return a bounding box rectangle that takes into account stroke.
+        // Note that this is a naive and ad-hoc implementation that does not
+        // works only in certain cases and should be replaced as soon as browsers will
+        // start supporting the getStrokeBBox() SVG method.
+        // @TODO any better solution is very welcome!
+
+        var isMagnet = !!el;
+        
+        el = el || this.el;
+        var bbox = V(el).bbox(false, this.paper.viewport);
+
+        var strokeWidth;
+        if (isMagnet) {
+
+            strokeWidth = V(el).attr('stroke-width');
+            
+        } else {
+
+            strokeWidth = this.model.attr('rect/stroke-width') || this.model.attr('circle/stroke-width') || this.model.attr('ellipse/stroke-width') || this.model.attr('path/stroke-width');
+        }
+
+        strokeWidth = parseFloat(strokeWidth) || 0;
+
+        return g.rect(bbox).moveAndExpand({ x: -strokeWidth/2, y: -strokeWidth/2, width: strokeWidth, height: strokeWidth });
+    },
+    
+    getBBox: function() {
+
+        return V(this.el).bbox();
+    },
+
+    highlight: function(el) {
+
+        el = !el ? this.el : this.$(el)[0] || this.el;
+
+        V(el).addClass('highlighted');
+    },
+
+    unhighlight: function(el) {
+
+        el = !el ? this.el : this.$(el)[0] || this.el;
+
+        V(el).removeClass('highlighted');
+    },
+
+    // Find the closest element that has the `magnet` attribute set to `true`. If there was not such
+    // an element found, return the root element of the cell view.
+    findMagnet: function(el) {
+
+        var $el = this.$(el);
+
+        if ($el.length === 0 || $el[0] === this.el) {
+
+            // If the overall cell has set `magnet === false`, then return `undefined` to
+            // announce there is no magnet found for this cell.
+            // This is especially useful to set on cells that have 'ports'. In this case,
+            // only the ports have set `magnet === true` and the overall element has `magnet === false`.
+            var attrs = this.model.get('attrs') || {};
+            if (attrs['.'] && attrs['.']['magnet'] === false) {
+                return undefined;
+            }
+
+            return this.el;
+        }
+
+        if ($el.attr('magnet')) {
+
+            return $el[0];
+        }
+
+        return this.findMagnet($el.parent());
+    },
+
+    // `selector` is a CSS selector or `'.'`. `filter` must be in the special JointJS filter format:
+    // `{ name: <name of the filter>, args: { <arguments>, ... }`.
+    // An example is: `{ filter: { name: 'blur', args: { radius: 5 } } }`.
+    applyFilter: function(selector, filter) {
+
+        var $selected = this.findBySelector(selector);
+
+        // Generate a hash code from the stringified filter definition. This gives us
+        // a unique filter ID for different definitions.
+        var filterId = filter.name + this.paper.svg.id + joint.util.hashCode(JSON.stringify(filter));
+
+        // If the filter already exists in the document,
+        // we're done and we can just use it (reference it using `url()`).
+        // If not, create one.
+        if (!this.paper.svg.getElementById(filterId)) {
+
+            var filterSVGString = joint.util.filter[filter.name] && joint.util.filter[filter.name](filter.args || {});
+            if (!filterSVGString) {
+                throw new Error('Non-existing filter ' + filter.name);
+            }
+            var filterElement = V(filterSVGString);
+            filterElement.attr('filterUnits', 'userSpaceOnUse');
+            if (filter.attrs) filterElement.attr(filter.attrs);
+            filterElement.node.id = filterId;
+            V(this.paper.svg).defs().append(filterElement);
+        }
+
+        $selected.each(function() {
+            
+            V(this).attr('filter', 'url(#' + filterId + ')');
+        });
+    },
+
+    // `selector` is a CSS selector or `'.'`. `attr` is either a `'fill'` or `'stroke'`.
+    // `gradient` must be in the special JointJS gradient format:
+    // `{ type: <linearGradient|radialGradient>, stops: [ { offset: <offset>, color: <color> }, ... ]`.
+    // An example is: `{ fill: { type: 'linearGradient', stops: [ { offset: '10%', color: 'green' }, { offset: '50%', color: 'blue' } ] } }`.
+    applyGradient: function(selector, attr, gradient) {
+
+        var $selected = this.findBySelector(selector);
+
+        // Generate a hash code from the stringified filter definition. This gives us
+        // a unique filter ID for different definitions.
+        var gradientId = gradient.type + this.paper.svg.id + joint.util.hashCode(JSON.stringify(gradient));
+
+        // If the gradient already exists in the document,
+        // we're done and we can just use it (reference it using `url()`).
+        // If not, create one.
+        if (!this.paper.svg.getElementById(gradientId)) {
+
+            var gradientSVGString = [
+                '<' + gradient.type + '>',
+                _.map(gradient.stops, function(stop) {
+                    return '<stop offset="' + stop.offset + '" stop-color="' + stop.color + '" stop-opacity="' + (_.isFinite(stop.opacity) ? stop.opacity : 1) + '" />'
+                }).join(''),
+                '</' + gradient.type + '>'
+            ].join('');
+            
+            var gradientElement = V(gradientSVGString);
+            if (gradient.attrs) { gradientElement.attr(gradient.attrs); }
+            gradientElement.node.id = gradientId;
+            V(this.paper.svg).defs().append(gradientElement);
+        }
+
+        $selected.each(function() {
+            
+            V(this).attr(attr, 'url(#' + gradientId + ')');
+        });
+    },
+
+    // Construct a unique selector for the `el` element within this view.
+    // `selector` is being collected through the recursive call. No value for `selector` is expected when using this method.
+    getSelector: function(el, selector) {
+
+        if (el === this.el) {
+
+            return selector;
+        }
+
+        var index = $(el).index();
+
+        selector = el.tagName + ':nth-child(' + (index + 1) + ')' + ' ' + (selector || '');
+
+        return this.getSelector($(el).parent()[0], selector + ' ');
+    },
+
+    // Interaction. The controller part.
+    // ---------------------------------
+
+    // Interaction is handled by the paper and delegated to the view in interest.
+    // `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid.
+    // If necessary, real coordinates can be obtained from the `evt` event object.
+
+    // These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`,
+    // i.e. `joint.dia.Element` and `joint.dia.Link`.
+
+    pointerdblclick: function(evt, x, y) {
+
+        this.notify('cell:pointerdblclick', evt, x, y);
+    },
+
+    pointerclick: function(evt, x, y) {
+
+        this.notify('cell:pointerclick', evt, x, y);
+    },
+    
+    pointerdown: function(evt, x, y) {
+
+       if (this.model.collection) {
+           this.model.trigger('batch:start');
+           this._collection = this.model.collection;
+       }
+
+        this.notify('cell:pointerdown', evt, x, y);
+    },
+    
+    pointermove: function(evt, x, y) {
+
+        this.notify('cell:pointermove', evt, x, y);
+    },
+    
+    pointerup: function(evt, x, y) {
+
+        this.notify('cell:pointerup', evt, x, y);
+
+       if (this._collection) {
+           // we don't want to trigger event on model as model doesn't
+           // need to be member of collection anymore (remove)
+           this._collection.trigger('batch:stop');
+           delete this._collection;
+       }
+
+    }
+});
+
+
+if (typeof exports === 'object') {
+
+    module.exports.Cell = joint.dia.Cell;
+    module.exports.CellView = joint.dia.CellView;
+}
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('./core').util,
+        dia: {
+            Cell: require('./joint.dia.cell').Cell,
+            CellView: require('./joint.dia.cell').CellView
+        }
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+}
+
+
+// joint.dia.Element base model.
+// -----------------------------
+
+joint.dia.Element = joint.dia.Cell.extend({
+
+    defaults: {
+        position: { x: 0, y: 0 },
+       size: { width: 1, height: 1 },
+        angle: 0
+    },
+
+    position: function(x, y) {
+
+        this.set('position', { x: x, y: y });
+    },
+    
+    translate: function(tx, ty, opt) {
+
+        ty = ty || 0;
+
+        if (tx === 0 && ty === 0) {
+            // Like nothing has happened.
+            return this;
+        }
+
+        var position = this.get('position') || { x: 0, y: 0 };
+       var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 };
+
+       if (opt && opt.transition) {
+
+           if (!_.isObject(opt.transition)) opt.transition = {};
+
+           this.transition('position', translatedPosition, _.extend({}, opt.transition, {
+               valueFunction: joint.util.interpolate.object
+           }));
+
+       } else {
+
+            this.set('position', translatedPosition, opt);
+
+            // Recursively call `translate()` on all the embeds cells.
+            _.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt);
+       }
+
+        return this;
+    },
+
+    resize: function(width, height) {
+
+       this.trigger('batch:start');
+        this.set('size', { width: width, height: height });
+       this.trigger('batch:stop');
+
+       return this;
+    },
+
+    rotate: function(angle, absolute) {
+
+        return this.set('angle', absolute ? angle : ((this.get('angle') || 0) + angle) % 360);
+    },
+
+    getBBox: function() {
+
+       var position = this.get('position');
+       var size = this.get('size');
+
+       return g.rect(position.x, position.y, size.width, size.height);
+    }
+});
+
+// joint.dia.Element base view and controller.
+// -------------------------------------------
+
+joint.dia.ElementView = joint.dia.CellView.extend({
+
+    className: function() {
+        return 'element ' + this.model.get('type').split('.').join(' ');
+    },
+
+    initialize: function() {
+
+        _.bindAll(this, 'translate', 'resize', 'rotate');
+
+        joint.dia.CellView.prototype.initialize.apply(this, arguments);
+        
+       this.listenTo(this.model, 'change:position', this.translate);
+       this.listenTo(this.model, 'change:size', this.resize);
+       this.listenTo(this.model, 'change:angle', this.rotate);
+    },
+
+    // Default is to process the `attrs` object and set attributes on subelements based on the selectors.
+    update: function(cell, renderingOnlyAttrs) {
+
+        var allAttrs = this.model.get('attrs');
+
+        var rotatable = V(this.$('.rotatable')[0]);
+        if (rotatable) {
+
+            var rotation = rotatable.attr('transform');
+            rotatable.attr('transform', '');
+        }
+        
+        var relativelyPositioned = [];
+
+        _.each(renderingOnlyAttrs || allAttrs, function(attrs, selector) {
+
+            // Elements that should be updated.
+            var $selected = this.findBySelector(selector);
+
+            // No element matched by the `selector` was found. We're done then.
+            if ($selected.length === 0) return;
+
+            // Special attributes are treated by JointJS, not by SVG.
+            var specialAttributes = ['style', 'text', 'html', 'ref-x', 'ref-y', 'ref-dx', 'ref-dy', 'ref-width', 'ref-height', 'ref', 'x-alignment', 'y-alignment', 'port'];
+
+            // If the `filter` attribute is an object, it is in the special JointJS filter format and so
+            // it becomes a special attribute and is treated separately.
+            if (_.isObject(attrs.filter)) {
+
+                specialAttributes.push('filter');
+                this.applyFilter(selector, attrs.filter);
+            }
+
+            // If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so
+            // it becomes a special attribute and is treated separately.
+            if (_.isObject(attrs.fill)) {
+
+                specialAttributes.push('fill');
+                this.applyGradient(selector, 'fill', attrs.fill);
+            }
+            if (_.isObject(attrs.stroke)) {
+
+                specialAttributes.push('stroke');
+                this.applyGradient(selector, 'stroke', attrs.stroke);
+            }
+
+            // Make special case for `text` attribute. So that we can set text content of the `<text>` element
+            // via the `attrs` object as well.
+            // Note that it's important to set text before applying the rest of the final attributes.
+            // Vectorizer `text()` method sets on the element its own attributes and it has to be possible
+            // to rewrite them, if needed. (i.e display: 'none')
+            if (!_.isUndefined(attrs.text)) {
+
+                $selected.each(function() {
+
+                    V(this).text(attrs.text + '');
+                });
+            }
+
+            // Set regular attributes on the `$selected` subelement. Note that we cannot use the jQuery attr()
+            // method as some of the attributes might be namespaced (e.g. xlink:href) which fails with jQuery attr().
+            var finalAttributes = _.omit(attrs, specialAttributes);
+            
+            $selected.each(function() {
+                
+                V(this).attr(finalAttributes);
+            });
+
+            // `port` attribute contains the `id` of the port that the underlying magnet represents.
+            if (attrs.port) {
+
+                $selected.attr('port', _.isUndefined(attrs.port.id) ? attrs.port : attrs.port.id);
+            }
+
+            // `style` attribute is special in the sense that it sets the CSS style of the subelement.
+            if (attrs.style) {
+
+                $selected.css(attrs.style);
+            }
+            
+            if (!_.isUndefined(attrs.html)) {
+
+                $selected.each(function() {
+
+                    $(this).html(attrs.html + '');
+                });
+            }
+            
+            // Special `ref-x` and `ref-y` attributes make it possible to set both absolute or
+            // relative positioning of subelements.
+            if (!_.isUndefined(attrs['ref-x']) ||
+                !_.isUndefined(attrs['ref-y']) ||
+                !_.isUndefined(attrs['ref-dx']) ||
+                !_.isUndefined(attrs['ref-dy']) ||
+               !_.isUndefined(attrs['x-alignment']) ||
+               !_.isUndefined(attrs['y-alignment']) ||
+                !_.isUndefined(attrs['ref-width']) ||
+                !_.isUndefined(attrs['ref-height'])
+               ) {
+
+                   _.each($selected, function(el, index, list) {
+                       var $el = $(el);
+                       // copy original list selector to the element
+                       $el.selector = list.selector;
+                       relativelyPositioned.push($el);
+                   });
+            }
+            
+        }, this);
+
+        // We don't want the sub elements to affect the bounding box of the root element when
+        // positioning the sub elements relatively to the bounding box.
+        //_.invoke(relativelyPositioned, 'hide');
+        //_.invoke(relativelyPositioned, 'show');
+
+        // Note that we're using the bounding box without transformation because we are already inside
+        // a transformed coordinate system.
+        var bbox = this.el.getBBox();        
+
+        renderingOnlyAttrs = renderingOnlyAttrs || {};
+
+        _.each(relativelyPositioned, function($el) {
+
+            // if there was a special attribute affecting the position amongst renderingOnlyAttributes
+            // we have to merge it with rest of the element's attributes as they are necessary
+            // to update the position relatively (i.e `ref`)
+            var renderingOnlyElAttrs = renderingOnlyAttrs[$el.selector];
+            var elAttrs = renderingOnlyElAttrs
+                ? _.merge({}, allAttrs[$el.selector], renderingOnlyElAttrs)
+                : allAttrs[$el.selector];
+
+            this.positionRelative($el, bbox, elAttrs);
+            
+        }, this);
+
+        if (rotatable) {
+
+            rotatable.attr('transform', rotation || '');
+        }
+    },
+
+    positionRelative: function($el, bbox, elAttrs) {
+
+        var ref = elAttrs['ref'];
+        var refX = parseFloat(elAttrs['ref-x']);
+        var refY = parseFloat(elAttrs['ref-y']);
+        var refDx = parseFloat(elAttrs['ref-dx']);
+        var refDy = parseFloat(elAttrs['ref-dy']);
+        var yAlignment = elAttrs['y-alignment'];
+        var xAlignment = elAttrs['x-alignment'];
+        var refWidth = parseFloat(elAttrs['ref-width']);
+        var refHeight = parseFloat(elAttrs['ref-height']);
+
+        // `ref` is the selector of the reference element. If no `ref` is passed, reference
+        // element is the root element.
+
+        var isScalable = _.contains(_.pluck(_.pluck($el.parents('g'), 'className'), 'baseVal'), 'scalable');
+
+        if (ref) {
+
+            // Get the bounding box of the reference element relative to the root `<g>` element.
+            bbox = V(this.findBySelector(ref)[0]).bbox(false, this.el);
+        }
+
+        var vel = V($el[0]);
+
+        // Remove the previous translate() from the transform attribute and translate the element
+        // relative to the root bounding box following the `ref-x` and `ref-y` attributes.
+        if (vel.attr('transform')) {
+
+            vel.attr('transform', vel.attr('transform').replace(/translate\([^)]*\)/g, '') || '');
+        }
+
+        function isDefined(x) {
+            return _.isNumber(x) && !_.isNaN(x);
+        }
+
+        // The final translation of the subelement.
+        var tx = 0;
+        var ty = 0;
+
+        // 'ref-width'/'ref-height' defines the width/height of the subelement relatively to
+        // the reference element size
+        // val in 0..1         ref-width = 0.75 sets the width to 75% of the ref. el. width
+        // val < 0 || val > 1  ref-height = -20 sets the height to the the ref. el. height shorter by 20
+
+        if (isDefined(refWidth)) {
+
+            if (refWidth >= 0 && refWidth <= 1) {
+
+                vel.attr('width', refWidth * bbox.width);
+
+            } else {
+
+                vel.attr('width', Math.max(refWidth + bbox.width, 0));
+            }
+        }
+
+        if (isDefined(refHeight)) {
+
+            if (refHeight >= 0 && refHeight <= 1) {
+
+                vel.attr('height', refHeight * bbox.height);
+
+            } else {
+
+                vel.attr('height', Math.max(refHeight + bbox.height, 0));
+            }
+        }
+
+        // `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom
+        // coordinate of the reference element.
+        if (isDefined(refDx)) {
+
+            if (isScalable) {
+
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                tx = bbox.x + bbox.width + refDx / scale.sx;
+                
+            } else {
+                
+                tx = bbox.x + bbox.width + refDx;
+            }
+        }
+        if (isDefined(refDy)) {
+
+            if (isScalable) {
+                
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                ty = bbox.y + bbox.height + refDy / scale.sy;
+            } else {
+                
+                ty = bbox.y + bbox.height + refDy;
+            }
+        }
+
+        // if `refX` is in [0, 1] then `refX` is a fraction of bounding box width
+        // if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box
+        // otherwise, `refX` is the left coordinate of the bounding box
+        // Analogical rules apply for `refY`.
+        if (isDefined(refX)) {
+
+            if (refX > 0 && refX < 1) {
+
+                tx = bbox.x + bbox.width * refX;
+
+            } else if (isScalable) {
+
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                tx = bbox.x + refX / scale.sx;
+                
+            } else {
+
+                tx = bbox.x + refX;
+            }
+        }
+        if (isDefined(refY)) {
+
+            if (refY > 0 && refY < 1) {
+                
+                ty = bbox.y + bbox.height * refY;
+                
+            } else if (isScalable) {
+
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                ty = bbox.y + refY / scale.sy;
+                
+            } else {
+
+                ty = bbox.y + refY;
+            }
+        }
+
+       var velbbox = vel.bbox(false, this.paper.viewport);
+        // `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate.
+        if (yAlignment === 'middle') {
+
+            ty -= velbbox.height/2;
+            
+        } else if (isDefined(yAlignment)) {
+
+            ty += (yAlignment > -1 && yAlignment < 1) ?  velbbox.height * yAlignment : yAlignment;
+        }
+
+        // `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate.
+        if (xAlignment === 'middle') {
+            
+            tx -= velbbox.width/2;
+            
+        } else if (isDefined(xAlignment)) {
+
+            tx += (xAlignment > -1 && xAlignment < 1) ?  velbbox.width * xAlignment : xAlignment;
+        }
+
+        vel.translate(tx, ty);
+    },
+
+    // `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the
+    // default markup is not desirable.
+    renderMarkup: function() {
+        
+        var markup = this.model.markup || this.model.get('markup');
+        
+        if (markup) {
+
+            var nodes = V(markup);
+            V(this.el).append(nodes);
+            
+        } else {
+
+            throw new Error('properties.markup is missing while the default render() implementation is used.');
+        }
+    },
+
+    render: function() {
+
+        this.$el.empty();
+
+        this.renderMarkup();
+
+        this.update();
+
+        this.resize();
+        this.rotate();
+        this.translate();        
+
+        return this;
+    },
+
+    // Scale the whole `<g>` group. Note the difference between `scale()` and `resize()` here.
+    // `resize()` doesn't scale the whole `<g>` group but rather adjusts the `box.sx`/`box.sy` only.
+    // `update()` is then responsible for scaling only those elements that have the `follow-scale`
+    // attribute set to `true`. This is desirable in elements that have e.g. a `<text>` subelement
+    // that is not supposed to be scaled together with a surrounding `<rect>` element that IS supposed
+    // be be scaled.
+    scale: function(sx, sy) {
+
+        // TODO: take into account the origin coordinates `ox` and `oy`.
+        V(this.el).scale(sx, sy);
+    },
+
+    resize: function() {
+
+        var size = this.model.get('size') || { width: 1, height: 1 };
+        var angle = this.model.get('angle') || 0;
+        
+        var scalable = V(this.$('.scalable')[0]);
+        if (!scalable) {
+            // If there is no scalable elements, than there is nothing to resize.
+            return;
+        }
+        var scalableBbox = scalable.bbox(true);
+        
+        scalable.attr('transform', 'scale(' + (size.width / scalableBbox.width) + ',' + (size.height / scalableBbox.height) + ')');
+
+        // Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height`
+        // Order of transformations is significant but we want to reconstruct the object always in the order:
+        // resize(), rotate(), translate() no matter of how the object was transformed. For that to work,
+        // we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the
+        // rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation
+        // around the center of the resized object (which is a different origin then the origin of the previous rotation)
+        // and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was.
+        
+        // Cancel the rotation but now around a different origin, which is the center of the scaled object.
+        var rotatable = V(this.$('.rotatable')[0]);
+        var rotation = rotatable && rotatable.attr('transform');
+        if (rotation && rotation !== 'null') {
+
+            rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width/2) + ',' + (size.height/2) + ')');
+            var rotatableBbox = scalable.bbox(false, this.paper.viewport);
+            
+            // Store new x, y and perform rotate() again against the new rotation origin.
+            this.model.set('position', { x: rotatableBbox.x, y: rotatableBbox.y });
+            this.rotate();
+        }
+
+        // Update must always be called on non-rotated element. Otherwise, relative positioning
+        // would work with wrong (rotated) bounding boxes.
+        this.update();
+    },
+
+    translate: function(model, changes, opt) {
+
+        var position = this.model.get('position') || { x: 0, y: 0 };
+
+        V(this.el).attr('transform', 'translate(' + position.x + ',' + position.y + ')');
+    },
+
+    rotate: function() {
+
+        var rotatable = V(this.$('.rotatable')[0]);
+        if (!rotatable) {
+            // If there is no rotatable elements, then there is nothing to rotate.
+            return;
+        }
+        
+        var angle = this.model.get('angle') || 0;
+        var size = this.model.get('size') || { width: 1, height: 1 };
+
+        var ox = size.width/2;
+        var oy = size.height/2;
+        
+
+        rotatable.attr('transform', 'rotate(' + angle + ',' + ox + ',' + oy + ')');
+    },
+
+    // Interaction. The controller part.
+    // ---------------------------------
+
+    
+    pointerdown: function(evt, x, y) {
+
+        if ( // target is a valid magnet start linking
+            evt.target.getAttribute('magnet') &&
+            this.paper.options.validateMagnet.call(this.paper, this, evt.target)
+        ) {
+                this.model.trigger('batch:start');
+
+                var link = this.paper.getDefaultLink(this, evt.target);
+                link.set({
+                    source: {
+                        id: this.model.id,
+                        selector: this.getSelector(evt.target),
+                        port: $(evt.target).attr('port')
+                    },
+                    target: { x: x, y: y }
+                });
+
+                this.paper.model.addCell(link);
+
+               this._linkView = this.paper.findViewByModel(link);
+                this._linkView.startArrowheadMove('target');
+
+        } else {
+
+            this._dx = x;
+            this._dy = y;
+
+            joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
+        }
+    },
+
+    pointermove: function(evt, x, y) {
+
+        if (this._linkView) {
+
+            // let the linkview deal with this event
+            this._linkView.pointermove(evt, x, y);
+
+        } else {
+
+           var grid = this.paper.options.gridSize;
+
+            if (this.options.interactive !== false) {
+
+               var position = this.model.get('position');
+
+               // Make sure the new element's position always snaps to the current grid after
+               // translate as the previous one could be calculated with a different grid size.
+               this.model.translate(
+                   g.snapToGrid(position.x, grid) - position.x + g.snapToGrid(x - this._dx, grid),
+                   g.snapToGrid(position.y, grid) - position.y + g.snapToGrid(y - this._dy, grid)
+               );
+            }
+
+            this._dx = g.snapToGrid(x, grid);
+            this._dy = g.snapToGrid(y, grid);
+
+            joint.dia.CellView.prototype.pointermove.apply(this, arguments);
+        }
+    },
+
+    pointerup: function(evt, x, y) {
+
+        if (this._linkView) {
+
+            // let the linkview deal with this event
+            this._linkView.pointerup(evt, x, y);
+
+            delete this._linkView;
+
+            this.model.trigger('batch:stop');
+
+        } else {
+
+            joint.dia.CellView.prototype.pointerup.apply(this, arguments);
+        }
+    }
+
+});
+
+if (typeof exports === 'object') {
+
+    module.exports.Element = joint.dia.Element;
+    module.exports.ElementView = joint.dia.ElementView;
+}
+
+//      JointJS diagramming library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        dia: {
+            Cell: require('./joint.dia.cell').Cell,
+            CellView: require('./joint.dia.cell').CellView
+        }
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+    var g = require('./geometry');
+}
+
+
+
+// joint.dia.Link base model.
+// --------------------------
+joint.dia.Link = joint.dia.Cell.extend({
+
+    // The default markup for links.
+    markup: [
+        '<path class="connection" stroke="black"/>',
+        '<path class="marker-source" fill="black" stroke="black" />',
+        '<path class="marker-target" fill="black" stroke="black" />',
+        '<path class="connection-wrap"/>',
+        '<g class="labels"/>',
+        '<g class="marker-vertices"/>',
+        '<g class="marker-arrowheads"/>',
+        '<g class="link-tools"/>'
+    ].join(''),
+
+    labelMarkup: [
+        '<g class="label">',
+        '<rect />',
+        '<text />',
+        '</g>'
+    ].join(''),
+
+    toolMarkup: [
+        '<g class="link-tool">',
+        '<g class="tool-remove" event="remove">',
+        '<circle r="11" />',
+        '<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>',
+        '<title>Remove link.</title>',
+        '</g>',
+        '<g class="tool-options" event="link:options">',
+        '<circle r="11" transform="translate(25)"/>',
+        '<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>',
+        '<title>Link options.</title>',
+        '</g>',
+        '</g>'
+    ].join(''),
+
+    // The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`).
+    // Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for
+    // dragging vertices (changin their position). The latter is used for removing vertices.
+    vertexMarkup: [
+        '<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">',
+        '<circle class="marker-vertex" idx="<%= idx %>" r="10" />',
+        '<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>',
+        '<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',
+        '<title>Remove vertex.</title>',
+        '</path>',
+        '</g>'
+    ].join(''),
+
+    arrowheadMarkup: [
+        '<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">',
+        '<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />',
+        '</g>'
+    ].join(''),
+
+    defaults: {
+
+        type: 'link'
+    },
+
+    disconnect: function() {
+
+        return this.set({ source: g.point(0, 0), target: g.point(0, 0) });
+    },
+
+    // A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter.
+    label: function(idx, value) {
+
+        idx = idx || 0;
+        
+        var labels = this.get('labels') || [];
+        
+        // Is it a getter?
+        if (arguments.length === 0 || arguments.length === 1) {
+            
+            return labels[idx];
+        }
+
+        var newValue = _.merge({}, labels[idx], value);
+
+        var newLabels = labels.slice();
+        newLabels[idx] = newValue;
+        
+        return this.set({ labels: newLabels });
+    }
+});
+
+
+// joint.dia.Link base view and controller.
+// ----------------------------------------
+
+joint.dia.LinkView = joint.dia.CellView.extend({
+
+    className: function() {
+        return _.unique(this.model.get('type').split('.').concat('link')).join(' ');
+    },
+
+    options: {
+
+        shortLinkLength: 100
+    },
+    
+    initialize: function() {
+
+        joint.dia.CellView.prototype.initialize.apply(this, arguments);
+
+        // create methods in prototype, so they can be accessed from any instance and
+        // don't need to be create over and over
+        if (typeof this.constructor.prototype.watchSource !== 'function') {
+            this.constructor.prototype.watchSource = this._createWatcher('source');
+            this.constructor.prototype.watchTarget = this._createWatcher('target');
+        }
+
+        // `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to
+        // `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the
+        // nodes in `updateLabelPosition()` in order to update the label positions.
+        this._labelCache = {};
+
+        // keeps markers bboxes and positions again for quicker access
+        this._markerCache = {};
+
+        // bind events
+        this.startListening();
+    },
+
+    startListening: function() {
+
+       this.listenTo(this.model, 'change:markup', this.render);
+       this.listenTo(this.model, 'change:smooth change:manhattan change:router change:connector', this.update);
+        this.listenTo(this.model, 'change:toolMarkup', function() {
+            this.renderTools().updateToolsPosition();
+        });
+       this.listenTo(this.model, 'change:labels change:labelMarkup', function() {
+            this.renderLabels().updateLabelPositions();
+        });
+        this.listenTo(this.model, 'change:vertices change:vertexMarkup', function() {
+            this.renderVertexMarkers().update();
+        });
+       this.listenTo(this.model, 'change:source', function(cell, source) {
+            this.watchSource(cell, source).update();
+        });
+       this.listenTo(this.model, 'change:target', function(cell, target) {
+            this.watchTarget(cell, target).update();
+        });
+    },
+
+    // Rendering
+    //----------
+
+    render: function() {
+
+       this.$el.empty();
+
+        // A special markup can be given in the `properties.markup` property. This might be handy
+        // if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s.
+        // `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors
+        // of elements with special meaning though. Therefore, those classes should be preserved in any
+        // special markup passed in `properties.markup`.
+        var children = V(this.model.get('markup') || this.model.markup);
+
+        // custom markup may contain only one children
+        if (!_.isArray(children)) children = [children];
+
+        // Cache all children elements for quicker access.
+        this._V = {}; // vectorized markup;
+        _.each(children, function(child) {
+            var c = child.attr('class');
+            c && (this._V[$.camelCase(c)] = child);
+        }, this);
+
+        // Only the connection path is mandatory
+        if (!this._V.connection) throw new Error('link: no connection path in the markup');
+
+        // partial rendering
+        this.renderTools();
+        this.renderVertexMarkers();
+        this.renderArrowheadMarkers();
+
+        V(this.el).append(children);
+
+        // rendering labels has to be run after the link is appended to DOM tree. (otherwise <Text> bbox
+        // returns zero values)
+        this.renderLabels();
+
+        // start watching the ends of the link for changes
+        this.watchSource(this.model, this.model.get('source'))
+            .watchTarget(this.model, this.model.get('target'))
+            .update();
+
+        return this;
+    },
+
+    renderLabels: function() {
+
+        if (!this._V.labels) return this;
+
+        this._labelCache = {};
+        var $labels = $(this._V.labels.node).empty();
+
+        var labels = this.model.get('labels') || [];
+        if (!labels.length) return this;
+        
+        var labelTemplate = _.template(this.model.get('labelMarkup') || this.model.labelMarkup);
+        // This is a prepared instance of a vectorized SVGDOM node for the label element resulting from
+        // compilation of the labelTemplate. The purpose is that all labels will just `clone()` this
+        // node to create a duplicate.
+        var labelNodeInstance = V(labelTemplate());
+
+        _.each(labels, function(label, idx) {
+
+            var labelNode = labelNodeInstance.clone().node;
+            // Cache label nodes so that the `updateLabels()` can just update the label node positions.
+            this._labelCache[idx] = V(labelNode);
+
+            var $text = $(labelNode).find('text');
+            var $rect = $(labelNode).find('rect');
+
+            // Text attributes with the default `text-anchor` and font-size set.
+            var textAttributes = _.extend({ 'text-anchor': 'middle', 'font-size': 14 }, joint.util.getByPath(label, 'attrs/text', '/'));
+            
+            $text.attr(_.omit(textAttributes, 'text'));
+                
+            if (!_.isUndefined(textAttributes.text)) {
+
+                V($text[0]).text(textAttributes.text + '');
+            }
+
+            // Note that we first need to append the `<text>` element to the DOM in order to
+            // get its bounding box.
+            $labels.append(labelNode);
+
+            // `y-alignment` - center the text element around its y coordinate.
+            var textBbox = V($text[0]).bbox(true, $labels[0]);
+            V($text[0]).translate(0, -textBbox.height/2);
+
+            // Add default values.
+            var rectAttributes = _.extend({
+
+                fill: 'white',
+                rx: 3,
+                ry: 3
+                
+            }, joint.util.getByPath(label, 'attrs/rect', '/'));
+            
+            $rect.attr(_.extend(rectAttributes, {
+
+                x: textBbox.x,
+                y: textBbox.y - textBbox.height/2,  // Take into account the y-alignment translation.
+                width: textBbox.width,
+                height: textBbox.height
+            }));
+            
+        }, this);
+
+        return this;
+    },
+
+    renderTools: function() {
+
+        if (!this._V.linkTools) return this;
+
+        // Tools are a group of clickable elements that manipulate the whole link.
+        // A good example of this is the remove tool that removes the whole link.
+        // Tools appear after hovering the link close to the `source` element/point of the link
+        // but are offset a bit so that they don't cover the `marker-arrowhead`.
+
+        var $tools = $(this._V.linkTools.node).empty();
+        var toolTemplate = _.template(this.model.get('toolMarkup') || this.model.toolMarkup);
+        var tool = V(toolTemplate());
+
+        $tools.append(tool.node);
+        
+        // Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly.
+        this._toolCache = tool;
+
+        return this;
+    },
+
+    renderVertexMarkers: function() {
+
+        if (!this._V.markerVertices) return this;
+
+        var $markerVertices = $(this._V.markerVertices.node).empty();
+
+        // A special markup can be given in the `properties.vertexMarkup` property. This might be handy
+        // if default styling (elements) are not desired. This makes it possible to use any
+        // SVG elements for .marker-vertex and .marker-vertex-remove tools.
+        var markupTemplate = _.template(this.model.get('vertexMarkup') || this.model.vertexMarkup);
+        
+        _.each(this.model.get('vertices'), function(vertex, idx) {
+
+            $markerVertices.append(V(markupTemplate(_.extend({ idx: idx }, vertex))).node);
+        });
+        
+        return this;
+    },
+
+    renderArrowheadMarkers: function() {
+
+        // Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case.
+        if (!this._V.markerArrowheads) return this;
+
+        var $markerArrowheads = $(this._V.markerArrowheads.node);
+
+        $markerArrowheads.empty();
+
+        // A special markup can be given in the `properties.vertexMarkup` property. This might be handy
+        // if default styling (elements) are not desired. This makes it possible to use any
+        // SVG elements for .marker-vertex and .marker-vertex-remove tools.
+        var markupTemplate = _.template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup);
+
+        this._V.sourceArrowhead = V(markupTemplate({ end: 'source' }));
+        this._V.targetArrowhead = V(markupTemplate({ end: 'target' }));
+
+        $markerArrowheads.append(this._V.sourceArrowhead.node, this._V.targetArrowhead.node);
+
+        return this;
+    },
+
+    // Updating
+    //---------
+
+    // Default is to process the `attrs` object and set attributes on subelements based on the selectors.
+    update: function() {
+
+        // Update attributes.
+        _.each(this.model.get('attrs'), function(attrs, selector) {
+            
+            // If the `filter` attribute is an object, it is in the special JointJS filter format and so
+            // it becomes a special attribute and is treated separately.
+            if (_.isObject(attrs.filter)) {
+                
+                this.findBySelector(selector).attr(_.omit(attrs, 'filter'));
+                this.applyFilter(selector, attrs.filter);
+                
+            } else {
+                
+                this.findBySelector(selector).attr(attrs);
+            }
+        }, this);
+
+        // Path finding
+        var vertices = this.route = this.findRoute(this.model.get('vertices') || []);
+
+        // finds all the connection points taking new vertices into account
+        this._findConnectionPoints(vertices);
+
+        var pathData = this.getPathData(vertices);
+
+        // The markup needs to contain a `.connection`
+        this._V.connection.attr('d', pathData);
+        this._V.connectionWrap && this._V.connectionWrap.attr('d', pathData);
+
+        this._translateAndAutoOrientArrows(this._V.markerSource, this._V.markerTarget);
+
+        //partials updates
+        this.updateLabelPositions();
+        this.updateToolsPosition();
+        this.updateArrowheadMarkers();
+
+        delete this.options.perpendicular;
+
+        return this;
+    },
+
+    _findConnectionPoints: function(vertices) {
+
+        // cache source and target points
+        var sourcePoint, targetPoint, sourceMarkerPoint, targetMarkerPoint;
+
+        var firstVertex = _.first(vertices);
+
+        sourcePoint = this.getConnectionPoint(
+            'source', this.model.get('source'), firstVertex || this.model.get('target')
+        ).round();
+
+        var lastVertex = _.last(vertices);
+
+        targetPoint = this.getConnectionPoint(
+            'target', this.model.get('target'), lastVertex || sourcePoint
+        ).round();
+
+        // Move the source point by the width of the marker taking into account
+        // its scale around x-axis. Note that scale is the only transform that
+        // makes sense to be set in `.marker-source` attributes object
+        // as all other transforms (translate/rotate) will be replaced
+        // by the `translateAndAutoOrient()` function.
+        var cache = this._markerCache;
+
+        if (this._V.markerSource) {
+
+            cache.sourceBBox = cache.sourceBBox || this._V.markerSource.bbox(true);
+
+            sourceMarkerPoint = g.point(sourcePoint).move(
+                firstVertex || targetPoint,
+                cache.sourceBBox.width * this._V.markerSource.scale().sx * -1
+            ).round();
+        }
+
+        if (this._V.markerTarget) {
+
+            cache.targetBBox = cache.targetBBox || this._V.markerTarget.bbox(true);
+
+            targetMarkerPoint = g.point(targetPoint).move(
+                lastVertex || sourcePoint,
+                cache.targetBBox.width * this._V.markerTarget.scale().sx * -1
+            ).round();
+        }
+
+        // if there was no markup for the marker, use the connection point.
+        cache.sourcePoint = sourceMarkerPoint || sourcePoint;
+        cache.targetPoint = targetMarkerPoint || targetPoint;
+
+        // make connection points public
+        this.sourcePoint = sourcePoint;
+        this.targetPoint = targetPoint;
+    },
+
+    updateLabelPositions: function() {
+
+        if (!this._V.labels) return this;
+
+        // This method assumes all the label nodes are stored in the `this._labelCache` hash table
+        // by their indexes in the `this.get('labels')` array. This is done in the `renderLabels()` method.
+
+        var labels = this.model.get('labels') || [];
+        if (!labels.length) return this;
+
+        var connectionElement = this._V.connection.node;
+        var connectionLength = connectionElement.getTotalLength();
+
+        _.each(labels, function(label, idx) {
+
+            var position = label.position;
+            position = (position > connectionLength) ? connectionLength : position; // sanity check
+            position = (position < 0) ? connectionLength + position : position;
+            position = position > 1 ? position : connectionLength * position;
+
+            var labelCoordinates = connectionElement.getPointAtLength(position);
+
+            this._labelCache[idx].attr('transform', 'translate(' + labelCoordinates.x + ', ' + labelCoordinates.y + ')');
+
+        }, this);
+
+        return this;
+    },
+
+
+    updateToolsPosition: function() {
+
+        if (!this._V.linkTools) return this;
+
+        // Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker.
+        // Note that the offset is hardcoded here. The offset should be always
+        // more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking
+        // this up all the time would be slow.
+
+        var scale = '';
+        var offset = 40;
+
+        // If the link is too short, make the tools half the size and the offset twice as low.
+        if (this.getConnectionLength() < this.options.shortLinkLength) {
+            scale = 'scale(.5)';
+            offset /= 2;
+        }
+
+        var toolPosition = this.getPointAtLength(offset);
+        
+        this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale);
+
+        return this;
+    },
+
+
+    updateArrowheadMarkers: function() {
+
+        if (!this._V.markerArrowheads) return this;
+
+        // getting bbox of an element with `display="none"` in IE9 ends up with access violation
+        if ($.css(this._V.markerArrowheads.node, 'display') === 'none') return this;
+
+        var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1;
+        this._V.sourceArrowhead.scale(sx);
+        this._V.targetArrowhead.scale(sx);
+
+        this._translateAndAutoOrientArrows(this._V.sourceArrowhead, this._V.targetArrowhead);
+
+        return this;
+    },
+
+    // Returns a function observing changes on an end of the link. If a change happens and new end is a new model,
+    // it stops listening on the previous one and starts listening to the new one.
+    _createWatcher: function(endType) {
+
+        function watchEnd(link, end) {
+
+            end = end || {};
+
+            var previousEnd = link.previous(endType) || {};
+
+            // Pick updateMethod this._sourceBboxUpdate or this._targetBboxUpdate.
+            var updateEndFunction = this['_' + endType + 'BBoxUpdate'];
+
+            if (this._isModel(previousEnd)) {
+                this.stopListening(this.paper.getModelById(previousEnd.id), 'change', updateEndFunction);
+            }
+
+            if (this._isModel(end)) {
+                // If the observed model changes, it caches a new bbox and do the link update.
+                this.listenTo(this.paper.getModelById(end.id), 'change', updateEndFunction);
+            }
+
+            _.bind(updateEndFunction, this)({ cacheOnly: true });
+
+            return this;
+        }
+
+        return watchEnd;
+    },
+
+    // It's important to keep both methods (sourceBboxUpdate and targetBboxUpdate) as unique methods
+    // because of loop links. We have to be able to determine, which method we want to stop listen to.
+    // ListenTo(model, event, handler) as model and event will be identical.
+    _sourceBBoxUpdate: function(update) {
+
+        // keep track which end had been changed very last
+        this.lastEndChange = 'source';
+
+        update = update || {};
+        var end = this.model.get('source');
+
+        if (this._isModel(end)) {
+
+            var selector = this._makeSelector(end);
+            var view = this.paper.findViewByModel(end.id);
+            var magnetElement = this.paper.viewport.querySelector(selector);
+
+            this.sourceBBox = view.getStrokeBBox(magnetElement);
+
+        } else {
+            // the link end is a point ~ rect 1x1
+            this.sourceBBox = g.rect(end.x, end.y, 1, 1);
+        }
+
+        if (!update.cacheOnly) this.update();
+    },
+
+    _targetBBoxUpdate: function(update) {
+
+        // keep track which end had been changed very last
+        this.lastEndChange = 'target';
+
+        update = update || {};
+        var end = this.model.get('target');
+
+        if (this._isModel(end)) {
+
+            var selector = this._makeSelector(end);
+            var view = this.paper.findViewByModel(end.id);
+            var magnetElement = this.paper.viewport.querySelector(selector);
+
+            this.targetBBox = view.getStrokeBBox(magnetElement);
+
+        } else {
+            // the link end is a point ~ rect 1x1
+            this.targetBBox = g.rect(end.x, end.y, 1, 1);
+        }
+
+        if (!update.cacheOnly) this.update();
+    },
+
+    _translateAndAutoOrientArrows: function(sourceArrow, targetArrow) {
+
+        // Make the markers "point" to their sticky points being auto-oriented towards
+        // `targetPosition`/`sourcePosition`. And do so only if there is a markup for them.
+        if (sourceArrow) {
+            sourceArrow.translateAndAutoOrient(
+                this.sourcePoint,
+                _.first(this.route) || this.targetPoint,
+                this.paper.viewport
+            );
+        }
+
+        if (targetArrow) {
+            targetArrow.translateAndAutoOrient(
+                this.targetPoint,
+                _.last(this.route) || this.sourcePoint,
+                this.paper.viewport
+            );
+        }
+    },
+
+    removeVertex: function(idx) {
+
+        var vertices = _.clone(this.model.get('vertices'));
+        
+        if (vertices && vertices.length) {
+
+            vertices.splice(idx, 1);
+            this.model.set('vertices', vertices);
+        }
+
+        return this;
+    },
+
+    // This method ads a new vertex to the `vertices` array of `.connection`. This method
+    // uses a heuristic to find the index at which the new `vertex` should be placed at assuming
+    // the new vertex is somewhere on the path.
+    addVertex: function(vertex) {
+
+        this.model.set('attrs', this.model.get('attrs') || {});
+        var attrs = this.model.get('attrs');
+        
+        // As it is very hard to find a correct index of the newly created vertex,
+        // a little heuristics is taking place here.
+        // The heuristics checks if length of the newly created
+        // path is lot more than length of the old path. If this is the case,
+        // new vertex was probably put into a wrong index.
+        // Try to put it into another index and repeat the heuristics again.
+
+        var vertices = (this.model.get('vertices') || []).slice();
+        // Store the original vertices for a later revert if needed.
+        var originalVertices = vertices.slice();
+
+        // A `<path>` element used to compute the length of the path during heuristics.
+        var path = this._V.connection.node.cloneNode(false);
+        
+        // Length of the original path.        
+        var originalPathLength = path.getTotalLength();
+        // Current path length.
+        var pathLength;
+        // Tolerance determines the highest possible difference between the length
+        // of the old and new path. The number has been chosen heuristically.
+        var pathLengthTolerance = 20;
+        // Total number of vertices including source and target points.
+        var idx = vertices.length + 1;
+
+        // Loop through all possible indexes and check if the difference between
+        // path lengths changes significantly. If not, the found index is
+        // most probably the right one.
+        while (idx--) {
+
+            vertices.splice(idx, 0, vertex);
+            V(path).attr('d', this.getPathData(this.findRoute(vertices)));
+
+            pathLength = path.getTotalLength();
+
+            // Check if the path lengths changed significantly.
+            if (pathLength - originalPathLength > pathLengthTolerance) {
+
+                // Revert vertices to the original array. The path length has changed too much
+                // so that the index was not found yet.
+                vertices = originalVertices.slice();
+                
+            } else {
+
+                break;
+            }
+        }
+
+        this.model.set('vertices', vertices);
+
+        // In manhattan routing, if there are no vertices, the path length changes significantly
+        // with the first vertex added. Shall we check vertices.length === 0? at beginning of addVertex()
+        // in order to avoid the temporary path construction and other operations?
+        return Math.max(idx, 0);
+    },
+
+
+    findRoute: function(oldVertices) {
+
+        var router = this.model.get('router');
+
+        if (!router) {
+
+            if (this.model.get('manhattan')) {
+                // backwards compability
+                router = { name: 'orthogonal' };
+            } else {
+
+                return oldVertices;
+            }
+        }
+
+        var fn = joint.routers[router.name];
+
+        if (!_.isFunction(fn)) {
+
+            throw 'unknown router: ' + router.name;
+        }
+
+        var newVertices = fn.call(this, oldVertices || [], router.args || {}, this);
+
+        return newVertices;
+    },
+
+    // Return the `d` attribute value of the `<path>` element representing the link
+    // between `source` and `target`.
+    getPathData: function(vertices) {
+
+        var connector = this.model.get('connector');
+
+        if (!connector) {
+
+            // backwards compability
+            connector = this.model.get('smooth') ? { name: 'smooth' } : { name: 'normal' };
+        }
+
+        if (!_.isFunction(joint.connectors[connector.name])) {
+
+            throw 'unknown connector: ' + connector.name;
+        }
+
+        var pathData = joint.connectors[connector.name].call(
+            this,
+            this._markerCache.sourcePoint, // Note that the value is translated by the size
+            this._markerCache.targetPoint, // of the marker. (We'r not using this.sourcePoint)
+            vertices || (this.model.get('vertices') || {}),
+            connector.args || {}, // options
+            this
+        );
+
+        return pathData;
+    },
+
+    // Find a point that is the start of the connection.
+    // If `selectorOrPoint` is a point, then we're done and that point is the start of the connection.
+    // If the `selectorOrPoint` is an element however, we need to know a reference point (or element)
+    // that the link leads to in order to determine the start of the connection on the original element.
+    getConnectionPoint: function(end, selectorOrPoint, referenceSelectorOrPoint) {
+
+        var spot;
+
+        if (this._isPoint(selectorOrPoint)) {
+
+            // If the source is a point, we don't need a reference point to find the sticky point of connection.
+            spot = g.point(selectorOrPoint);
+
+        } else {
+
+            // If the source is an element, we need to find a point on the element boundary that is closest
+            // to the reference point (or reference element).
+            // Get the bounding box of the spot relative to the paper viewport. This is necessary
+            // in order to follow paper viewport transformations (scale/rotate).
+            // `_sourceBbox` (`_targetBbox`) comes from `_sourceBboxUpdate` (`_sourceBboxUpdate`)
+            // method, it exists since first render and are automatically updated
+            var spotBbox = end === 'source' ? this.sourceBBox : this.targetBBox;
+            
+            var reference;
+            
+            if (this._isPoint(referenceSelectorOrPoint)) {
+
+                // Reference was passed as a point, therefore, we're ready to find the sticky point of connection on the source element.
+                reference = g.point(referenceSelectorOrPoint);
+
+            } else {
+
+                // Reference was passed as an element, therefore we need to find a point on the reference
+                // element boundary closest to the source element.
+                // Get the bounding box of the spot relative to the paper viewport. This is necessary
+                // in order to follow paper viewport transformations (scale/rotate).
+                var referenceBbox = end === 'source' ? this.targetBBox : this.sourceBBox;
+
+                reference = g.rect(referenceBbox).intersectionWithLineFromCenterToPoint(g.rect(spotBbox).center());
+                reference = reference || g.rect(referenceBbox).center();
+            }
+
+            // If `perpendicularLinks` flag is set on the paper and there are vertices
+            // on the link, then try to find a connection point that makes the link perpendicular
+            // even though the link won't point to the center of the targeted object.
+            if (this.paper.options.perpendicularLinks || this.options.perpendicular) {
+
+                var horizontalLineRect = g.rect(0, reference.y, this.paper.options.width, 1);
+                var verticalLineRect = g.rect(reference.x, 0, 1, this.paper.options.height);
+                var nearestSide;
+
+                if (horizontalLineRect.intersect(g.rect(spotBbox))) {
+
+                    nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
+                    switch (nearestSide) {
+                      case 'left':
+                        spot = g.point(spotBbox.x, reference.y);
+                        break;
+                      case 'right':
+                        spot = g.point(spotBbox.x + spotBbox.width, reference.y);
+                        break;
+                    default:
+                        spot = g.rect(spotBbox).center();
+                        break;
+                    }
+                    
+                } else if (verticalLineRect.intersect(g.rect(spotBbox))) {
+
+                    nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
+                    switch (nearestSide) {
+                      case 'top':
+                        spot = g.point(reference.x, spotBbox.y);
+                        break;
+                      case 'bottom':
+                        spot = g.point(reference.x, spotBbox.y + spotBbox.height);
+                        break;
+                    default:
+                        spot = g.rect(spotBbox).center();
+                        break;
+                    }
+                    
+                } else {
+
+                    // If there is no intersection horizontally or vertically with the object bounding box,
+                    // then we fall back to the regular situation finding straight line (not perpendicular)
+                    // between the object and the reference point.
+
+                    spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
+                    spot = spot || g.rect(spotBbox).center();
+                }
+                
+            } else {
+            
+                spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
+                spot = spot || g.rect(spotBbox).center();
+            }
+        }
+
+        return spot;
+    },
+
+    _isModel: function(end) {
+
+        return end && end.id;
+    },
+
+    _isPoint: function(end) {
+
+        return !this._isModel(end);
+    },
+
+    _makeSelector: function(end) {
+
+        var selector = '[model-id="' + end.id + '"]';
+        // `port` has a higher precendence over `selector`. This is because the selector to the magnet
+        // might change while the name of the port can stay the same.
+        if (end.port) {
+            selector += ' [port="' + end.port + '"]';
+        } else if (end.selector) {
+            selector += ' ' + end.selector;
+        }
+
+        return selector;
+    },
+
+    // Public API
+    // ----------
+
+    getConnectionLength: function() {
+
+        return this._V.connection.node.getTotalLength();
+    },
+
+    getPointAtLength: function(length) {
+
+        return this._V.connection.node.getPointAtLength(length);
+    },
+
+    // Interaction. The controller part.
+    // ---------------------------------
+
+    _beforeArrowheadMove: function() {
+
+        this.model.trigger('batch:start');
+
+        this._z = this.model.get('z');
+        this.model.set('z', Number.MAX_VALUE);
+
+        // Let the pointer propagate throught the link view elements so that
+        // the `evt.target` is another element under the pointer, not the link itself.
+        this.el.style.pointerEvents = 'none';
+    },
+
+    _afterArrowheadMove: function() {
+
+        if (this._z) {
+            this.model.set('z', this._z);
+            delete this._z;
+        }
+
+        // Put `pointer-events` back to its original value. See `startArrowheadMove()` for explanation.
+       // Value `auto` doesn't work in IE9. We force to use `visiblePainted` instead.
+       // See `https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events`.
+        this.el.style.pointerEvents = 'visiblePainted';
+
+        this.model.trigger('batch:stop');
+    },
+
+    _createValidateConnectionArgs: function(arrowhead) {
+        // It makes sure the arguments for validateConnection have the following form:
+        // (source view, source magnet, target view, target magnet and link view)
+        var args = [];
+
+        args[4] = arrowhead;
+        args[5] = this;
+
+        var oppositeArrowhead, i = 0, j = 0;
+
+        if (arrowhead === 'source') {
+            i = 2;
+            oppositeArrowhead = 'target';
+        } else {
+            j = 2;
+            oppositeArrowhead = 'source';
+        }
+
+        var end = this.model.get(oppositeArrowhead);
+
+        if (end.id) {
+            args[i] = this.paper.findViewByModel(end.id);
+            args[i+1] = end.selector && args[i].el.querySelector(end.selector);
+        }
+
+        function validateConnectionArgs(cellView, magnet) {
+            args[j] = cellView;
+            args[j+1] = cellView.el === magnet ? undefined : magnet;
+            return args;
+        }
+
+        return validateConnectionArgs;
+    },
+
+    startArrowheadMove: function(end) {
+        // Allow to delegate events from an another view to this linkView in order to trigger arrowhead
+        // move without need to click on the actual arrowhead dom element.
+        this._action = 'arrowhead-move';
+        this._arrowhead = end;
+        this._beforeArrowheadMove();
+        this._validateConnectionArgs = this._createValidateConnectionArgs(this._arrowhead);
+    },
+
+    pointerdown: function(evt, x, y) {
+
+        joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
+
+       this._dx = x;
+        this._dy = y;
+
+        if (this.options.interactive === false) return;
+
+        var className = evt.target.getAttribute('class');
+
+        switch (className) {
+
+        case 'marker-vertex':
+            this._action = 'vertex-move';
+            this._vertexIdx = evt.target.getAttribute('idx');
+            break;
+
+        case 'marker-vertex-remove':
+        case 'marker-vertex-remove-area':
+            this.removeVertex(evt.target.getAttribute('idx'));
+            break;
+
+        case 'marker-arrowhead':
+            this.startArrowheadMove(evt.target.getAttribute('end'));
+            break;
+
+        default:
+
+            var targetParentEvent = evt.target.parentNode.getAttribute('event');
+
+            if (targetParentEvent) {
+
+                // `remove` event is built-in. Other custom events are triggered on the paper.
+                if (targetParentEvent === 'remove') {
+                    this.model.remove();
+                } else {
+                    this.paper.trigger(targetParentEvent, evt, this, x, y);
+                }
+
+            } else {
+
+                // Store the index at which the new vertex has just been placed.
+                // We'll be update the very same vertex position in `pointermove()`.
+                this._vertexIdx = this.addVertex({ x: x, y: y });
+                this._action = 'vertex-move';
+            }
+        }
+    },
+
+    pointermove: function(evt, x, y) {
+
+        joint.dia.CellView.prototype.pointermove.apply(this, arguments);
+
+        switch (this._action) {
+
+          case 'vertex-move':
+
+            var vertices = _.clone(this.model.get('vertices'));
+            vertices[this._vertexIdx] = { x: x, y: y };
+            this.model.set('vertices', vertices);
+            break;
+
+          case 'arrowhead-move':
+
+            if (this.paper.options.snapLinks) {
+
+                // checking view in close area of the pointer
+
+                var r = this.paper.options.snapLinks.radius || 50;
+                var viewsInArea = this.paper.findViewsInArea({ x: x - r, y: y - r, width: 2 * r, height: 2 * r });
+
+                this._closestView && this._closestView.unhighlight(this._closestEnd.selector);
+                this._closestView = this._closestEnd = null;
+
+                var pointer = g.point(x,y);
+                var distance, minDistance = Number.MAX_VALUE;
+
+                _.each(viewsInArea, function(view) {
+
+                    // skip connecting to the element in case '.': { magnet: false } attribute present
+                    if (view.el.getAttribute('magnet') !== 'false') {
+
+                        // find distance from the center of the model to pointer coordinates
+                        distance = view.model.getBBox().center().distance(pointer);
+
+                        // the connection is looked up in a circle area by `distance < r`
+                        if (distance < r && distance < minDistance) {
+
+                            if (this.paper.options.validateConnection.apply(
+                                this.paper, this._validateConnectionArgs(view, null)
+                            )) {
+                                minDistance = distance;
+                                this._closestView = view;
+                                this._closestEnd = { id: view.model.id };
+                            }
+                        }
+                    }
+
+                    view.$('[magnet]').each(_.bind(function(index, magnet) {
+
+                        var bbox = V(magnet).bbox(false, this.paper.viewport);
+
+                        distance = pointer.distance({
+                            x: bbox.x + bbox.width / 2,
+                            y: bbox.y + bbox.height / 2
+                        });
+
+                        if (distance < r && distance < minDistance) {
+
+                            if (this.paper.options.validateConnection.apply(
+                                this.paper, this._validateConnectionArgs(view, magnet)
+                            )) {
+                                minDistance = distance;
+                                this._closestView = view;
+                                this._closestEnd = {
+                                    id: view.model.id,
+                                    selector: view.getSelector(magnet),
+                                    port: magnet.getAttribute('port')
+                                };
+                            }
+                        }
+
+                    }, this));
+
+                }, this);
+
+                this._closestView && this._closestView.highlight(this._closestEnd.selector);
+
+                this.model.set(this._arrowhead, this._closestEnd || { x: x, y: y });
+
+            } else {
+
+                // checking views right under the pointer
+
+                // Touchmove event's target is not reflecting the element under the coordinates as mousemove does.
+                // It holds the element when a touchstart triggered.
+                var target = (evt.type === 'mousemove')
+                    ? evt.target
+                    : document.elementFromPoint(evt.clientX, evt.clientY);
+
+                if (this._targetEvent !== target) {
+                    // Unhighlight the previous view under pointer if there was one.
+                    this._magnetUnderPointer && this._viewUnderPointer.unhighlight(this._magnetUnderPointer);
+                    this._viewUnderPointer = this.paper.findView(target);
+                    if (this._viewUnderPointer) {
+                        // If we found a view that is under the pointer, we need to find the closest
+                        // magnet based on the real target element of the event.
+                        this._magnetUnderPointer = this._viewUnderPointer.findMagnet(target);
+
+                        if (this._magnetUnderPointer && this.paper.options.validateConnection.apply(
+                            this.paper,
+                            this._validateConnectionArgs(this._viewUnderPointer, this._magnetUnderPointer)
+                        )) {
+                            // If there was no magnet found, do not highlight anything and assume there
+                            // is no view under pointer we're interested in reconnecting to.
+                            // This can only happen if the overall element has the attribute `'.': { magnet: false }`.
+                            this._magnetUnderPointer && this._viewUnderPointer.highlight(this._magnetUnderPointer);
+                        } else {
+                            // This type of connection is not valid. Disregard this magnet.
+                            this._magnetUnderPointer = null;
+                        }
+                    } else {
+                        // Make sure we'll delete previous magnet
+                        this._magnetUnderPointer = null;
+                    }
+                }
+
+               this._targetEvent = target;
+
+                this.model.set(this._arrowhead, { x: x, y: y });
+            }
+
+            break;
+        }
+
+        this._dx = x;
+        this._dy = y;
+    },
+
+    pointerup: function(evt) {
+
+        joint.dia.CellView.prototype.pointerup.apply(this, arguments);
+
+        if (this._action === 'arrowhead-move') {
+
+            if (this.paper.options.snapLinks) {
+
+                this._closestView && this._closestView.unhighlight(this._closestEnd.selector);
+                this._closestView = this._closestEnd = null;
+
+            } else {
+
+                if (this._magnetUnderPointer) {
+                    this._viewUnderPointer.unhighlight(this._magnetUnderPointer);
+                    // Find a unique `selector` of the element under pointer that is a magnet. If the
+                    // `this._magnetUnderPointer` is the root element of the `this._viewUnderPointer` itself,
+                    // the returned `selector` will be `undefined`. That means we can directly pass it to the
+                    // `source`/`target` attribute of the link model below.
+                   this.model.set(this._arrowhead, {
+                        id: this._viewUnderPointer.model.id,
+                        selector: this._viewUnderPointer.getSelector(this._magnetUnderPointer),
+                        port: $(this._magnetUnderPointer).attr('port')
+                    });
+                }
+
+                delete this._viewUnderPointer;
+                delete this._magnetUnderPointer;
+                delete this._staticView;
+                delete this._staticMagnet;
+            }
+
+            this._afterArrowheadMove();
+        }
+
+        delete this._action;
+    }
+});
+
+
+if (typeof exports === 'object') {
+
+    module.exports.Link = joint.dia.Link;
+    module.exports.LinkView = joint.dia.LinkView;
+}
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+
+joint.dia.Paper = Backbone.View.extend({
+
+    options: {
+
+        width: 800,
+        height: 600,
+        gridSize: 50,
+        perpendicularLinks: false,
+        elementView: joint.dia.ElementView,
+        linkView: joint.dia.LinkView,
+        snapLinks: false, // false, true, { radius: value }
+
+        // Defines what link model is added to the graph after an user clicks on an active magnet.
+        // Value could be the Backbone.model or a function returning the Backbone.model
+        // defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() }
+        defaultLink: new joint.dia.Link,
+
+        // Check whether to add a new link to the graph when user clicks on an a magnet.
+        validateMagnet: function(cellView, magnet) {
+            return magnet.getAttribute('magnet') !== 'passive';
+        },
+
+        // Check whether to allow or disallow the link connection while an arrowhead end (source/target)
+        // being changed.
+        validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
+            return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView;
+        }
+    },
+
+    events: {
+
+        'mousedown': 'pointerdown',
+        'dblclick': 'mousedblclick',
+        'click': 'mouseclick',
+        'touchstart': 'pointerdown',
+        'mousemove': 'pointermove',
+        'touchmove': 'pointermove'
+    },
+
+    initialize: function() {
+
+        _.bindAll(this, 'addCell', 'sortCells', 'resetCells', 'pointerup');
+
+        this.svg = V('svg').node;
+        this.viewport = V('g').node;
+
+        // Append `<defs>` element to the SVG document. This is useful for filters and gradients.
+        V(this.svg).append(V('defs').node);
+
+        V(this.viewport).attr({ 'class': 'viewport' });
+        
+        V(this.svg).append(this.viewport);
+
+        this.$el.append(this.svg);
+
+        this.setDimensions();
+
+       this.listenTo(this.model, 'add', this.addCell);
+       this.listenTo(this.model, 'reset', this.resetCells);
+       this.listenTo(this.model, 'sort', this.sortCells);
+
+       $(document).on('mouseup touchend', this.pointerup);
+
+        // Hold the value when mouse has been moved: when mouse moved, no click event will be triggered.
+        this._mousemoved = false;
+    },
+
+    remove: function() {
+
+       $(document).off('mouseup touchend', this.pointerup);
+
+       Backbone.View.prototype.remove.call(this);
+    },
+
+    setDimensions: function(width, height) {
+
+        if (width) this.options.width = width;
+        if (height) this.options.height = height;
+        
+        V(this.svg).attr('width', this.options.width);
+        V(this.svg).attr('height', this.options.height);
+
+       this.trigger('resize');
+    },
+
+    // Expand/shrink the paper to fit the content. Snap the width/height to the grid
+    // defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper.
+    fitToContent: function(gridWidth, gridHeight, padding) {
+
+       gridWidth = gridWidth || 1;
+       gridHeight = gridHeight || 1;
+        padding = padding || 0;
+
+       // Calculate the paper size to accomodate all the graph's elements.
+       var bbox = V(this.viewport).bbox(true, this.svg);
+
+       var calcWidth = Math.ceil((bbox.width + bbox.x) / gridWidth) * gridWidth;
+       var calcHeight = Math.ceil((bbox.height + bbox.y) / gridHeight) * gridHeight;
+
+        calcWidth += padding;
+        calcHeight += padding;
+        
+       // Change the dimensions only if there is a size discrepency
+       if (calcWidth != this.options.width || calcHeight != this.options.height) {
+           this.setDimensions(calcWidth || this.options.width , calcHeight || this.options.height);
+       }
+    },
+
+    getContentBBox: function() {
+
+        var crect = this.viewport.getBoundingClientRect();
+
+        // Using Screen CTM was the only way to get the real viewport bounding box working in both
+        // Google Chrome and Firefox.
+        var ctm = this.viewport.getScreenCTM();
+
+        var bbox = g.rect(Math.abs(crect.left - ctm.e), Math.abs(crect.top - ctm.f), crect.width, crect.height);
+
+        return bbox;
+    },
+
+    createViewForModel: function(cell) {
+
+        var view;
+        
+        var type = cell.get('type');
+        var module = type.split('.')[0];
+        var entity = type.split('.')[1];
+
+        // If there is a special view defined for this model, use that one instead of the default `elementView`/`linkView`.
+        if (joint.shapes[module] && joint.shapes[module][entity + 'View']) {
+
+            view = new joint.shapes[module][entity + 'View']({ model: cell, interactive: this.options.interactive });
+            
+        } else if (cell instanceof joint.dia.Element) {
+                
+            view = new this.options.elementView({ model: cell, interactive: this.options.interactive });
+
+        } else {
+
+            view = new this.options.linkView({ model: cell, interactive: this.options.interactive });
+        }
+
+        return view;
+    },
+    
+    addCell: function(cell) {
+
+        var view = this.createViewForModel(cell);
+
+        V(this.viewport).append(view.el);
+        view.paper = this;
+        view.render();
+
+        // This is the only way to prevent image dragging in Firefox that works.
+        // Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help.
+        $(view.el).find('image').on('dragstart', function() { return false; });
+    },
+
+    resetCells: function(cellsCollection) {
+
+        $(this.viewport).empty();
+
+        var cells = cellsCollection.models.slice();
+
+        // Make sure links are always added AFTER elements.
+        // They wouldn't find their sources/targets in the DOM otherwise.
+        cells.sort(function(a, b) { return a instanceof joint.dia.Link ? 1 : -1; });
+        
+        _.each(cells, this.addCell, this);
+
+        // Sort the cells in the DOM manually as we might have changed the order they
+        // were added to the DOM (see above).
+        this.sortCells();
+    },
+
+    sortCells: function() {
+
+        // Run insertion sort algorithm in order to efficiently sort DOM elements according to their
+        // associated model `z` attribute.
+
+        var $cells = $(this.viewport).children('[model-id]');
+        var cells = this.model.get('cells');
+
+        this.sortElements($cells, function(a, b) {
+
+            var cellA = cells.get($(a).attr('model-id'));
+            var cellB = cells.get($(b).attr('model-id'));
+            
+            return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1;
+        });
+    },
+
+    // Highly inspired by the jquery.sortElements plugin by Padolsey.
+    // See http://james.padolsey.com/javascript/sorting-elements-with-jquery/.
+    sortElements: function(elements, comparator) {
+
+        var $elements = $(elements);
+        
+        var placements = $elements.map(function() {
+
+            var sortElement = this;
+            var parentNode = sortElement.parentNode;
+
+            // Since the element itself will change position, we have
+            // to have some way of storing it's original position in
+            // the DOM. The easiest way is to have a 'flag' node:
+            var nextSibling = parentNode.insertBefore(
+                document.createTextNode(''),
+                sortElement.nextSibling
+            );
+
+            return function() {
+                
+                if (parentNode === this) {
+                    throw new Error(
+                        "You can't sort elements if any one is a descendant of another."
+                    );
+                }
+                
+                // Insert before flag:
+                parentNode.insertBefore(this, nextSibling);
+                // Remove flag:
+                parentNode.removeChild(nextSibling);
+                
+            };
+        });
+
+        return Array.prototype.sort.call($elements, comparator).each(function(i) {
+            placements[i].call(this);
+        });
+    },
+
+    scale: function(sx, sy, ox, oy) {
+
+        if (!ox) {
+
+            ox = 0;
+            oy = 0;
+        }
+
+        // Remove previous transform so that the new scale is not affected by previous scales, especially
+        // the old translate() does not affect the new translate if an origin is specified.
+        V(this.viewport).attr('transform', '');
+        
+        // TODO: V.scale() doesn't support setting scale origin. #Fix        
+        if (ox || oy) {
+            V(this.viewport).translate(-ox * (sx - 1), -oy * (sy - 1));
+        }
+        
+        V(this.viewport).scale(sx, sy);
+
+       this.trigger('scale', ox, oy);
+
+        return this;
+    },
+
+    rotate: function(deg, ox, oy) {
+        
+        // If the origin is not set explicitely, rotate around the center. Note that
+        // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us
+        // the real bounding box (`bbox()`) including transformations).
+        if (_.isUndefined(ox)) {
+
+            var bbox = this.viewport.getBBox();
+            ox = bbox.width/2;
+            oy = bbox.height/2;
+        }
+
+        V(this.viewport).rotate(deg, ox, oy);
+    },
+
+    // Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also
+    // be a selector or a jQuery object.
+    findView: function(el) {
+
+        var $el = this.$(el);
+
+        if ($el.length === 0 || $el[0] === this.el) {
+
+            return undefined;
+        }
+
+        if ($el.data('view')) {
+
+            return $el.data('view');
+        }
+
+        return this.findView($el.parent());
+    },
+
+    // Find a view for a model `cell`. `cell` can also be a string representing a model `id`.
+    findViewByModel: function(cell) {
+
+        var id = _.isString(cell) ? cell : cell.id;
+        
+        var $view = this.$('[model-id="' + id + '"]');
+        if ($view.length) {
+
+            return $view.data('view');
+        }
+        return undefined;
+    },
+
+    // Find all views at given point
+    findViewsFromPoint: function(p) {
+
+       p = g.point(p);
+
+        var views = _.map(this.model.getElements(), this.findViewByModel);
+
+       return _.filter(views, function(view) {
+           return g.rect(V(view.el).bbox(false, this.viewport)).containsPoint(p);
+       }, this);
+    },
+
+    // Find all views in given area
+    findViewsInArea: function(r) {
+
+       r = g.rect(r);
+
+        var views = _.map(this.model.getElements(), this.findViewByModel);
+
+       return _.filter(views, function(view) {
+           return r.intersect(g.rect(V(view.el).bbox(false, this.viewport)));
+       }, this);
+    },
+
+    getModelById: function(id) {
+
+        return this.model.getCell(id);
+    },
+
+    snapToGrid: function(p) {
+
+        // Convert global coordinates to the local ones of the `viewport`. Otherwise,
+        // improper transformation would be applied when the viewport gets transformed (scaled/rotated). 
+        var localPoint = V(this.viewport).toLocalPoint(p.x, p.y);
+
+        return {
+            x: g.snapToGrid(localPoint.x, this.options.gridSize),
+            y: g.snapToGrid(localPoint.y, this.options.gridSize)
+        };
+    },
+
+    getDefaultLink: function(cellView, magnet) {
+
+        return _.isFunction(this.options.defaultLink)
+        // default link is a function producing link model
+            ? this.options.defaultLink.call(this, cellView, magnet)
+        // default link is the Backbone model
+            : this.options.defaultLink.clone();
+    },
+
+    // Interaction.
+    // ------------
+
+    mousedblclick: function(evt) {
+        
+        evt.preventDefault();
+        evt = joint.util.normalizeEvent(evt);
+        
+        var view = this.findView(evt.target);
+        var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+
+        if (view) {
+            
+            view.pointerdblclick(evt, localPoint.x, localPoint.y);
+            
+        } else {
+            
+            this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y);
+        }
+    },
+
+    mouseclick: function(evt) {
+
+        // Trigger event when mouse not moved.
+        if (!this._mousemoved) {
+            
+            evt.preventDefault();
+            evt = joint.util.normalizeEvent(evt);
+
+            var view = this.findView(evt.target);
+            var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+
+            if (view) {
+
+                view.pointerclick(evt, localPoint.x, localPoint.y);
+                
+            } else {
+
+                this.trigger('blank:pointerclick', evt, localPoint.x, localPoint.y);
+            }
+        }
+
+        this._mousemoved = false;
+    },
+
+    pointerdown: function(evt) {
+
+        evt.preventDefault();
+        evt = joint.util.normalizeEvent(evt);
+        
+        var view = this.findView(evt.target);
+
+        var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+        
+        if (view) {
+
+            this.sourceView = view;
+
+            view.pointerdown(evt, localPoint.x, localPoint.y);
+            
+        } else {
+
+            this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y);
+        }
+    },
+
+    pointermove: function(evt) {
+
+        evt.preventDefault();
+        evt = joint.util.normalizeEvent(evt);
+
+        if (this.sourceView) {
+
+            // Mouse moved.
+            this._mousemoved = true;
+
+            var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+
+            this.sourceView.pointermove(evt, localPoint.x, localPoint.y);
+        }
+    },
+
+    pointerup: function(evt) {
+
+        evt = joint.util.normalizeEvent(evt);
+
+        var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+        
+        if (this.sourceView) {
+
+            this.sourceView.pointerup(evt, localPoint.x, localPoint.y);
+
+            //"delete sourceView" occasionally throws an error in chrome (illegal access exception)
+           this.sourceView = null;
+
+        } else {
+
+            this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y);
+        }
+    }
+});
+
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {},
+        dia: {
+            Element: require('../src/joint.dia.element').Element,
+            ElementView: require('../src/joint.dia.element').ElementView
+        }
+    };
+    var _ = require('lodash');
+}
+
+
+joint.shapes.basic = {};
+
+
+joint.shapes.basic.Generic = joint.dia.Element.extend({
+
+    defaults: joint.util.deepSupplement({
+        
+        type: 'basic.Generic',
+        attrs: {
+            '.': { fill: '#FFFFFF', stroke: 'none' }
+        }
+        
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.basic.Rect = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+    
+        type: 'basic.Rect',
+        attrs: {
+            'rect': { fill: '#FFFFFF', stroke: 'black', width: 100, height: 60 },
+            'text': { 'font-size': 14, text: '', 'ref-x': .5, 'ref-y': .5, ref: 'rect', 'y-alignment': 'middle', 'x-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+        
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Text = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><text/></g></g>',
+    
+    defaults: joint.util.deepSupplement({
+        
+        type: 'basic.Text',
+        attrs: {
+            'text': { 'font-size': 18, fill: 'black' }
+        }
+        
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Circle = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.Circle',
+        size: { width: 60, height: 60 },
+        attrs: {
+            'circle': { fill: '#FFFFFF', stroke: 'black', r: 30, transform: 'translate(30, 30)' },
+            'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, ref: 'circle', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Image = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.Image',
+        attrs: {
+            'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'image', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Path = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.Path',
+        size: { width: 60, height: 60 },
+        attrs: {
+            'path': { fill: '#FFFFFF', stroke: 'black' },
+            'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'path', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+// PortsModelInterface is a common interface for shapes that have ports. This interface makes it easy
+// to create new shapes with ports functionality. It is assumed that the new shapes have
+// `inPorts` and `outPorts` array properties. Only these properties should be used to set ports.
+// In other words, using this interface, it is no longer recommended to set ports directly through the
+// `attrs` object.
+
+// Usage:
+// joint.shapes.custom.MyElementWithPorts = joint.shapes.basic.Path.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
+//     getPortAttrs: function(portName, index, total, selector, type) {
+//         var attrs = {};
+//         var portClass = 'port' + index;
+//         var portSelector = selector + '>.' + portClass;
+//         var portTextSelector = portSelector + '>text';
+//         var portCircleSelector = portSelector + '>circle';
+//
+//         attrs[portTextSelector] = { text: portName };
+//         attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type) , type: type } };
+//         attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) };
+//
+//         if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; }
+//
+//         return attrs;
+//     }
+//}));
+joint.shapes.basic.PortsModelInterface = {
+
+    initialize: function() {
+
+        this.updatePortsAttrs();
+        this.on('change:inPorts change:outPorts', this.updatePortsAttrs, this);
+
+        // Call the `initialize()` of the parent.
+        this.constructor.__super__.constructor.__super__.initialize.apply(this, arguments);
+    },
+    
+    updatePortsAttrs: function(eventName) {
+
+        // Delete previously set attributes for ports.
+        var currAttrs = this.get('attrs');
+        _.each(this._portSelectors, function(selector) {
+            if (currAttrs[selector]) delete currAttrs[selector];
+        });
+        
+        // This holds keys to the `attrs` object for all the port specific attribute that
+        // we set in this method. This is necessary in order to remove previously set
+        // attributes for previous ports.
+        this._portSelectors = [];
+        
+        var attrs = {};
+        
+        _.each(this.get('inPorts'), function(portName, index, ports) {
+            var portAttributes = this.getPortAttrs(portName, index, ports.length, '.inPorts', 'in');
+            this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
+            _.extend(attrs, portAttributes);
+        }, this);
+        
+        _.each(this.get('outPorts'), function(portName, index, ports) {
+            var portAttributes = this.getPortAttrs(portName, index, ports.length, '.outPorts', 'out');
+            this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
+            _.extend(attrs, portAttributes);
+        }, this);
+
+        // Silently set `attrs` on the cell so that noone knows the attrs have changed. This makes sure
+        // that, for example, command manager does not register `change:attrs` command but only
+        // the important `change:inPorts`/`change:outPorts` command.
+        this.attr(attrs, { silent: true });
+        // Manually call the `processPorts()` method that is normally called on `change:attrs` (that we just made silent).
+        this.processPorts();
+        // Let the outside world (mainly the `ModelView`) know that we're done configuring the `attrs` object.
+        this.trigger('process:ports');
+    },
+
+    getPortSelector: function(name) {
+
+        var selector = '.inPorts';
+        var index = this.get('inPorts').indexOf(name);
+
+        if (index < 0) {
+            selector = '.outPorts';
+            index = this.get('outPorts').indexOf(name);
+
+            if (index < 0) throw new Error("getPortSelector(): Port doesn't exist.");
+        }
+
+        return selector + '>g:nth-child(' + (index + 1) + ')>circle';
+    }
+};
+
+joint.shapes.basic.PortsViewInterface = {
+    
+    initialize: function() {
+
+        // `Model` emits the `process:ports` whenever it's done configuring the `attrs` object for ports.
+        this.listenTo(this.model, 'process:ports', this.update);
+        
+        joint.dia.ElementView.prototype.initialize.apply(this, arguments);
+    },
+
+    update: function() {
+
+        // First render ports so that `attrs` can be applied to those newly created DOM elements
+        // in `ElementView.prototype.update()`.
+        this.renderPorts();
+        joint.dia.ElementView.prototype.update.apply(this, arguments);
+    },
+
+    renderPorts: function() {
+
+        var $inPorts = this.$('.inPorts').empty();
+        var $outPorts = this.$('.outPorts').empty();
+
+        var portTemplate = _.template(this.model.portMarkup);
+
+        _.each(_.filter(this.model.ports, function(p) { return p.type === 'in' }), function(port, index) {
+
+            $inPorts.append(V(portTemplate({ id: index, port: port })).node);
+        });
+        _.each(_.filter(this.model.ports, function(p) { return p.type === 'out' }), function(port, index) {
+
+            $outPorts.append(V(portTemplate({ id: index, port: port })).node);
+        });
+    }
+};
+
+joint.shapes.basic.TextBlock = joint.shapes.basic.Generic.extend({
+
+    markup: ['<g class="rotatable"><g class="scalable"><rect/></g><switch>',
+
+             // if foreignObject supported
+
+             '<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">',
+             '<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',
+             '</foreignObject>',
+
+             // else foreignObject is not supported (fallback for IE)
+             '<text class="content"/>',
+
+             '</switch></g>'].join(''),
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.TextBlock',
+
+        // see joint.css for more element styles
+        attrs: {
+            rect: {
+                fill: '#ffffff',
+                stroke: '#000000',
+                width: 80,
+                height: 100
+            },
+            text: {
+                fill: '#000000',
+                'font-size': 14,
+                'font-family': 'Arial, helvetica, sans-serif'
+            },
+            '.content': {
+                text: '',
+                ref: 'rect',
+                'ref-x': .5,
+                'ref-y': .5,
+                'y-alignment': 'middle',
+                'x-alignment': 'middle'
+            }
+        },
+
+        content: ''
+
+    }, joint.shapes.basic.Generic.prototype.defaults),
+
+    initialize: function() {
+
+        if (typeof SVGForeignObjectElement !== 'undefined') {
+
+            // foreignObject supported
+            this.setForeignObjectSize(this, this.get('size'));
+            this.setDivContent(this, this.get('content'));
+            this.listenTo(this, 'change:size', this.setForeignObjectSize);
+            this.listenTo(this, 'change:content', this.setDivContent);
+
+        }
+
+        joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
+    },
+
+    setForeignObjectSize: function(cell, size) {
+
+        // Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead.
+        // We have to clone size as we don't want attributes.div.style to be same object as attributes.size.
+        cell.attr({
+            '.fobj': _.clone(size),
+            div: { style: _.clone(size) }
+        });
+    },
+
+    setDivContent: function(cell, content) {
+
+        // Append the content to div as html.
+        cell.attr({ div : {
+            html: content
+        }});
+    }
+
+});
+
+// TextBlockView implements the fallback for IE when no foreignObject exists and
+// the text needs to be manually broken.
+joint.shapes.basic.TextBlockView = joint.dia.ElementView.extend({
+
+    initialize: function() {
+
+        joint.dia.ElementView.prototype.initialize.apply(this, arguments);
+
+        if (typeof SVGForeignObjectElement === 'undefined') {
+
+            this.noSVGForeignObjectElement = true;
+
+            this.listenTo(this.model, 'change:content', function(cell) {
+                // avoiding pass of extra paramters
+                this.updateContent(cell);
+            });
+        }
+    },
+
+    update: function(cell, renderingOnlyAttrs) {
+
+        if (this.noSVGForeignObjectElement) {
+
+            var model = this.model;
+
+            // Update everything but the content first.
+            var noTextAttrs = _.omit(renderingOnlyAttrs || model.get('attrs'), '.content');
+            joint.dia.ElementView.prototype.update.call(this, model, noTextAttrs);
+
+            if (!renderingOnlyAttrs || _.has(renderingOnlyAttrs, '.content')) {
+                // Update the content itself.
+                this.updateContent(model, renderingOnlyAttrs);
+            }
+
+        } else {
+
+            joint.dia.ElementView.prototype.update.call(this, model, renderingOnlyAttrs);
+        }
+    },
+
+    updateContent: function(cell, renderingOnlyAttrs) {
+
+        // Create copy of the text attributes
+        var textAttrs = _.merge({}, (renderingOnlyAttrs || cell.get('attrs'))['.content']);
+
+        delete textAttrs.text;
+
+        // Break the content to fit the element size taking into account the attributes
+        // set on the model.
+        var text = joint.util.breakText(cell.get('content'), cell.get('size'), textAttrs, {
+            // measuring sandbox svg document
+            svgDocument: this.paper.svg
+        });
+
+        // Create a new attrs with same structure as the model attrs { text: { *textAttributes* }}
+        var attrs = joint.util.setByPath({}, '.content', textAttrs,'/');
+
+        // Replace text attribute with the one we just processed.
+        attrs['.content'].text = text;
+
+        // Update the view using renderingOnlyAttributes parameter.
+        joint.dia.ElementView.prototype.update.call(this, cell, attrs);
+    }
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.basic;
+}
+
+joint.routers.orthogonal = function() {
+
+    var sourceBBox, targetBBox;
+
+    // Return the direction that one would have to take traveling from `p1` to `p2`.
+    // This function assumes the line between `p1` and `p2` is orthogonal.
+    function direction(p1, p2) {
+        
+        if (p1.y < p2.y && p1.x === p2.x) {
+            return 'down';
+        } else if (p1.y > p2.y && p1.x === p2.x) {
+            return 'up';
+        } else if (p1.x < p2.x && p1.y === p2.y) {
+            return 'right';
+        }
+        return 'left';
+    }
+
+    function bestDirection(p1, p2, preferredDirection) {
+
+        var directions;
+
+        // This branching determines possible directions that one can take to travel
+        // from `p1` to `p2`.
+        if (p1.x < p2.x) {
+
+            if (p1.y > p2.y) { directions = ['up', 'right']; }
+            else if (p1.y < p2.y) { directions = ['down', 'right']; }
+            else { directions = ['right']; }
+
+        } else if (p1.x > p2.x) {
+
+            if (p1.y > p2.y) { directions = ['up', 'left']; }
+            else if (p1.y < p2.y) { directions = ['down', 'left']; }
+            else { directions = ['left']; }
+
+        } else {
+
+            if (p1.y > p2.y) { directions = ['up']; }
+            else { directions = ['down']; }
+        }
+
+        if (_.contains(directions, preferredDirection)) {
+            return preferredDirection;
+        }
+
+        var direction = _.first(directions);
+
+        // Should the direction be the exact opposite of the preferred direction,
+        // try another one if such direction exists.
+        switch (preferredDirection) {
+        case 'down': if (direction === 'up') return _.last(directions); break;
+        case 'up': if (direction === 'down') return _.last(directions); break;
+        case 'left': if (direction === 'right') return _.last(directions); break;
+        case 'right': if (direction === 'left') return _.last(directions); break;
+        }
+        return direction;
+    };
+
+    // Find a vertex in between the vertices `p1` and `p2` so that the route between those vertices
+    // is orthogonal. Prefer going the direction determined by `preferredDirection`.
+    function findMiddleVertex(p1, p2, preferredDirection) {
+        
+        var direction = bestDirection(p1, p2, preferredDirection);
+        if (direction === 'down' || direction === 'up') {
+            return { x: p1.x, y: p2.y, d: direction };
+        }
+        return { x: p2.x, y: p1.y, d: direction };
+    }
+
+    // Return points that one needs to draw a connection through in order to have a orthogonal link
+    // routing from source to target going through `vertices`.
+    function findOrthogonalRoute(vertices) {
+
+        vertices = (vertices || []).slice();
+        var orthogonalVertices = [];
+
+        var sourceCenter = sourceBBox.center();
+        var targetCenter = targetBBox.center();
+
+        if (!vertices.length) {
+
+            if (Math.abs(sourceCenter.x - targetCenter.x) < (sourceBBox.width / 2) ||
+                Math.abs(sourceCenter.y - targetCenter.y) < (sourceBBox.height / 2)
+            ) {
+
+                vertices = [{
+                    x: Math.min(sourceCenter.x, targetCenter.x) +
+                        Math.abs(sourceCenter.x - targetCenter.x) / 2,
+                    y: Math.min(sourceCenter.y, targetCenter.y) +
+                        Math.abs(sourceCenter.y - targetCenter.y) / 2
+                }];
+            }
+        }
+
+        vertices.unshift(sourceCenter);
+        vertices.push(targetCenter);
+
+        var orthogonalVertex;
+        var lastOrthogonalVertex;
+        var vertex;
+        var nextVertex;
+
+        // For all the pairs of link model vertices...
+        for (var i = 0; i < vertices.length - 1; i++) {
+
+            vertex = vertices[i];
+            nextVertex = vertices[i + 1];
+            lastOrthogonalVertex = _.last(orthogonalVertices);
+            
+            if (i > 0) {
+                // Push all the link vertices to the orthogonal route.
+                orthogonalVertex = vertex;
+                // Determine a direction between the last vertex and the new one.
+                // Therefore, each vertex contains the `d` property describing the direction that one
+                // would have to take to travel to that vertex.
+                orthogonalVertex.d = lastOrthogonalVertex
+                    ? direction(lastOrthogonalVertex, vertex)
+                    : 'top';
+
+                orthogonalVertices.push(orthogonalVertex);
+                lastOrthogonalVertex = orthogonalVertex;
+            }
+
+            // Make sure that we don't create a vertex that would go the opposite direction then
+            // that of the previous one.
+            // Othwerwise, a 'spike' segment would be created which is not desirable.
+            // Find a dummy vertex to keep the link orthogonal. Preferably, take the same direction
+            // as the previous one.
+            var d = lastOrthogonalVertex && lastOrthogonalVertex.d;
+            orthogonalVertex = findMiddleVertex(vertex, nextVertex, d);
+
+            // Do not add a new vertex that is the same as one of the vertices already added.
+            if (!g.point(orthogonalVertex).equals(g.point(vertex)) &&
+                !g.point(orthogonalVertex).equals(g.point(nextVertex))) {
+
+                orthogonalVertices.push(orthogonalVertex);
+            }
+        }
+        return orthogonalVertices;
+    };
+
+    return function(vertices) {
+
+        sourceBBox = this.sourceBBox;
+        targetBBox = this.targetBBox;
+
+        return findOrthogonalRoute(vertices);
+    };
+
+}();
+
+joint.routers.manhattan = (function() {
+
+    'use strict';
+
+    var config = {
+
+        // size of the step to find a route
+        step: 10,
+
+        // use of the perpendicular linkView option to connect center of element with first vertex
+        perpendicular: true,
+
+        // tells how to divide the paper when creating the elements map
+        mapGridSize: 100,
+
+        // should be source or target not to be consider as an obstacle
+        excludeEnds: [], // 'source', 'target'
+
+        // should be any element with a certain type not to be consider as an obstacle
+        excludeTypes: ['basic.Text'],
+
+        // if number of route finding loops exceed the maximum, stops searching and returns
+        // fallback route
+        maximumLoops: 500,
+
+        // possible starting directions from an element
+        startDirections: ['left','right','top','bottom'],
+
+        // possible ending directions to an element
+        endDirections: ['left','right','top','bottom'],
+
+        // specify directions above
+        directionMap: {
+            right: { x: 1, y: 0 },
+            bottom: { x: 0, y: 1 },
+            left: { x: -1, y: 0 },
+            top: { x: 0, y: -1 }
+        },
+
+        // maximum change of the direction
+        maxAllowedDirectionChange: 1,
+
+        // padding applied on the element bounding boxes
+        paddingBox: function() {
+
+            var step = this.step;
+
+            return {
+                x: -step,
+                y: -step,
+                width: 2*step,
+                height: 2*step
+            }
+        },
+
+        // an array of directions to find next points on the route
+        directions: function() {
+
+            var step = this.step;
+
+            return [
+                { offsetX: step  , offsetY: 0     , cost: step },
+                { offsetX: 0     , offsetY: step  , cost: step },
+                { offsetX: -step , offsetY: 0     , cost: step },
+                { offsetX: 0     , offsetY: -step , cost: step }
+            ];
+        },
+
+        // a penalty received for direction change
+        penalties: function() {
+
+            return [0, this.step / 2, this.step];
+        },
+
+        // heurestic method to determine the distance between two points
+        estimateCost: function(from, to) {
+
+            return from.manhattanDistance(to);
+        },
+
+        // a simple route used in situations, when main routing method fails
+        // (exceed loops, inaccessible).
+        fallbackRoute: function(from, to, opts) {
+
+            // Find an orthogonal route ignoring obstacles.
+
+            var prevDirIndexes = opts.prevDirIndexes || {};
+
+            var point = (prevDirIndexes[from] || 0) % 2
+                    ? g.point(from.x, to.y)
+                    : g.point(to.x, from.y);
+
+            return [point, to];
+        },
+
+        // if a function is provided, it's used to route the link while dragging an end
+        // i.e. function(from, to, opts) { return []; }
+        draggingRoute: null
+    };
+
+    // reconstructs a route by concating points with their parents
+    function reconstructRoute(parents, point) {
+
+        var route = [];
+        var prevDiff = { x: 0, y: 0 };
+        var current = point;
+        var parent;
+
+        while ((parent = parents[current])) {
+
+            var diff = parent.difference(current);
+
+            if (!diff.equals(prevDiff)) {
+
+                route.unshift(current);
+                prevDiff = diff;
+            }
+
+            current = parent;
+        }
+
+        route.unshift(current);
+
+        return route;
+    };
+
+    // find points around the rectangle taking given directions in the account
+    function getRectPoints(bbox, directionList, opts) {
+
+        var step = opts.step;
+
+        var center = bbox.center();
+
+        var startPoints = _.chain(opts.directionMap).pick(directionList).map(function(direction) {
+
+            var x = direction.x * bbox.width / 2;
+            var y = direction.y * bbox.height / 2;
+
+            var point = g.point(center).offset(x,y).snapToGrid(step);
+
+            if (bbox.containsPoint(point)) {
+
+                point.offset(direction.x * step, direction.y * step);
+            }
+
+            return point;
+
+        }).value();
+
+        return startPoints;
+    };
+
+    // returns a direction index from start point to end point
+    function getDirection(start, end, dirLen) {
+
+        var dirAngle = 360 / dirLen;
+
+        var q = Math.floor(start.theta(end) / dirAngle);
+
+        return dirLen - q;
+    }
+
+    // finds the route between to points/rectangles implementing A* alghoritm
+    function findRoute(start, end, map, opt) {
+
+        var startDirections = opt.reversed ? opt.endDirections : opt.startDirections;
+        var endDirections = opt.reversed ? opt.startDirections : opt.endDirections;
+
+        // set of points we start pathfinding from
+        var startSet = start instanceof g.rect
+                ? getRectPoints(start, startDirections, opt)
+                : [start];
+
+        // set of points we want the pathfinding to finish at
+        var endSet = end instanceof g.rect
+                ? getRectPoints(end, endDirections, opt)
+                : [end];
+
+        var startCenter = startSet.length > 1 ? start.center() : startSet[0];
+        var endCenter = endSet.length > 1 ? end.center() : endSet[0];
+
+        // take into account  only accessible end points
+        var endPoints = _.filter(endSet, function(point) {
+
+            var mapKey = g.point(point).snapToGrid(opt.mapGridSize).toString();
+
+            var accesible = _.every(map[mapKey], function(obstacle) {
+                return !obstacle.containsPoint(point);
+            });
+
+            return accesible;
+        });
+
+
+        if (endPoints.length) {
+
+            var step = opt.step;
+            var penalties = opt.penalties;
+
+            // choose the end point with the shortest estimated path cost
+            var endPoint = _.chain(endPoints).invoke('snapToGrid', step).min(function(point) {
+
+                return opt.estimateCost(startCenter, point);
+
+            }).value();
+
+            var parents = {};
+            var costFromStart = {};
+            var totalCost = {};
+
+            // directions
+            var dirs = opt.directions;
+            var dirLen = dirs.length;
+            var dirHalfLen = dirLen / 2;
+            var dirIndexes = opt.previousDirIndexes || {};
+
+            // The set of point already evaluated.
+            var closeHash = {}; // keeps only information whether a point was evaluated'
+
+            // The set of tentative points to be evaluated, initially containing the start points
+            var openHash = {}; // keeps only information whether a point is to be evaluated'
+            var openSet = _.chain(startSet).invoke('snapToGrid', step).each(function(point) {
+
+                var key = point.toString();
+
+                costFromStart[key] = 0; // Cost from start along best known path.
+                totalCost[key] = opt.estimateCost(point, endPoint);
+                dirIndexes[key] = dirIndexes[key] || getDirection(startCenter, point, dirLen);
+                openHash[key] = true;
+
+            }).map(function(point) {
+
+                return point.toString();
+
+            }).sortBy(function(pointKey) {
+
+                return totalCost[pointKey];
+
+            }).value();
+
+            var loopCounter = opt.maximumLoops;
+
+            var maxAllowedDirectionChange = opt.maxAllowedDirectionChange;
+
+            // main route finding loop
+            while (openSet.length && loopCounter--) {
+
+                var currentKey = openSet[0];
+                var currentPoint = g.point(currentKey);
+
+                if (endPoint.equals(currentPoint)) {
+
+                    opt.previousDirIndexes = _.pick(dirIndexes, currentKey);
+                    return reconstructRoute(parents, currentPoint);
+                }
+
+                // remove current from the open list
+                openSet.splice(0, 1);
+                openHash[neighborKey] = null;
+
+                // add current to the close list
+                closeHash[neighborKey] = true;
+
+                var currentDirIndex = dirIndexes[currentKey];
+                var currentDist = costFromStart[currentKey];
+
+                for (var dirIndex = 0; dirIndex < dirLen; dirIndex++) {
+
+                    var dirChange = Math.abs(dirIndex - currentDirIndex);
+
+                    if (dirChange > dirHalfLen) {
+
+                        dirChange = dirLen - dirChange;
+                    }
+
+                    // if the direction changed rapidly don't use this point
+                    if (dirChange > maxAllowedDirectionChange) {
+
+                        continue;
+                    }
+
+                    var dir = dirs[dirIndex];
+
+                    var neighborPoint = g.point(currentPoint).offset(dir.offsetX, dir.offsetY);
+                    var neighborKey = neighborPoint.toString();
+
+                    if (closeHash[neighborKey]) {
+
+                        continue;
+                    }
+
+                    // is point accesible - no obstacle in the way
+
+                    var mapKey = g.point(neighborPoint).snapToGrid(opt.mapGridSize).toString();
+
+                    var isAccesible = _.every(map[mapKey], function(obstacle) {
+                        return !obstacle.containsPoint(neighborPoint);
+                    });
+
+                    if (!isAccesible) {
+
+                        continue;
+                    }
+
+                    var inOpenSet = _.has(openHash, neighborKey);
+
+                    var costToNeighbor = currentDist + dir.cost;
+
+                    if (!inOpenSet || costToNeighbor < costFromStart[neighborKey]) {
+
+                        parents[neighborKey] = currentPoint;
+                        dirIndexes[neighborKey] = dirIndex;
+                        costFromStart[neighborKey] = costToNeighbor;
+
+                        totalCost[neighborKey] = costToNeighbor +
+                            opt.estimateCost(neighborPoint, endPoint) +
+                            penalties[dirChange];
+
+                        if (!inOpenSet) {
+
+                            var openIndex = _.sortedIndex(openSet, neighborKey, function(openKey) {
+
+                                return totalCost[openKey];
+                            });
+
+                            openSet.splice(openIndex, 0, neighborKey);
+                            openHash[neighborKey] = true;
+                        }
+                    };
+                };
+            }
+        }
+
+        // no route found ('to' point wasn't either accessible or finding route took
+        // way to much calculations)
+        return opt.fallbackRoute(startCenter, endCenter, opt);
+    };
+
+    // initiation of the route finding
+    function router(oldVertices, opt) {
+
+        // resolve some of the options
+        opt.directions = _.result(opt, 'directions');
+        opt.penalties = _.result(opt, 'penalties');
+        opt.paddingBox = _.result(opt, 'paddingBox');
+
+        // enable/disable linkView perpendicular option
+        this.options.perpendicular = !!opt.perpendicular;
+
+        // As route changes its shape rapidly when we start finding route from different point
+        // it's necessary to start from the element that was not interacted with
+        // (the position was changed) at very last.
+        var reverseRouting = opt.reversed = (this.lastEndChange === 'source');
+
+        var sourceBBox = reverseRouting ? g.rect(this.targetBBox) : g.rect(this.sourceBBox);
+        var targetBBox = reverseRouting ? g.rect(this.sourceBBox) : g.rect(this.targetBBox);
+
+        // expand boxes by specific padding
+        sourceBBox.moveAndExpand(opt.paddingBox);
+        targetBBox.moveAndExpand(opt.paddingBox);
+
+        // building an elements map
+
+        var link = this.model;
+        var graph = this.paper.model;
+
+        // source or target element could be excluded from set of obstacles
+        var excludedEnds = _.chain(opt.excludeEnds)
+                .map(link.get, link)
+                .pluck('id')
+                .map(graph.getCell, graph).value();
+
+        var mapGridSize = opt.mapGridSize;
+
+        // builds a map of all elements for quicker obstacle queries (i.e. is a point contained
+        // in any obstacle?) (a simplified grid search)
+        // The paper is divided to smaller cells, where each of them holds an information which
+        // elements belong to it. When we query whether a point is in an obstacle we don't need
+        // to go through all obstacles, we check only those in a particular cell.
+        var map = _.chain(graph.getElements())
+            // remove source and target element if required
+            .difference(excludedEnds)
+            // remove all elements whose type is listed in excludedTypes array
+            .reject(function(element) {
+                return _.contains(opt.excludeTypes, element.get('type'));
+            })
+            // change elements (models) to their bounding boxes
+            .invoke('getBBox')
+            // expand their boxes by specific padding
+            .invoke('moveAndExpand', opt.paddingBox)
+            // build the map
+            .foldl(function(res, bbox) {
+
+                var origin = bbox.origin().snapToGrid(mapGridSize);
+                var corner = bbox.corner().snapToGrid(mapGridSize);
+
+                for (var x = origin.x; x <= corner.x; x += mapGridSize) {
+                    for (var y = origin.y; y <= corner.y; y += mapGridSize) {
+
+                        var gridKey = x + '@' + y;
+
+                        res[gridKey] = res[gridKey] || [];
+                        res[gridKey].push(bbox);
+                    }
+                }
+
+                return res;
+
+            }, {}).value();
+
+        // pathfinding
+
+        var newVertices = [];
+
+        var points = _.map(oldVertices, g.point);
+
+        var tailPoint = sourceBBox.center();
+
+        // find a route by concating all partial routes (routes need to go through the vertices)
+        // startElement -> vertex[1] -> ... -> vertex[n] -> endElement
+        for (var i = 0, len = points.length; i <= len; i++) {
+
+            var partialRoute = null;
+
+            var from = to || sourceBBox;
+            var to = points[i];
+
+            if (!to) {
+
+                to = targetBBox;
+
+                // 'to' is not a vertex. If the target is a point (i.e. it's not an element), we
+                // might use dragging route instead of main routing method if that is enabled.
+                var endingAtPoint = !this.model.get('source').id || !this.model.get('target').id;
+
+                if (endingAtPoint && _.isFunction(opt.draggingRoute)) {
+                    // Make sure we passing points only (not rects).
+                    var dragFrom = from instanceof g.rect ? from.center() : from;
+                    partialRoute = opt.draggingRoute(dragFrom, to.origin(), opt);
+                }
+            }
+
+            // if partial route has not been calculated yet use the main routing method to find one
+            partialRoute = partialRoute || findRoute(from, to, map, opt);
+
+            var leadPoint = _.first(partialRoute);
+
+            if (leadPoint && leadPoint.equals(tailPoint)) {
+
+                // remove the first point if the previous partial route had the same point as last
+                partialRoute.shift();
+            }
+
+            tailPoint = _.last(partialRoute) || tailPoint;
+
+            newVertices = newVertices.concat(partialRoute);
+        };
+
+        // we might have to reverse the result if we swapped source and target at the beginning
+        return reverseRouting ? newVertices.reverse() : newVertices;
+    };
+
+    // public function
+    return function(vertices, opt, linkView) {
+
+        return router.call(linkView, vertices, _.extend({}, config, opt));
+    };
+
+})();
+
+joint.routers.metro = (function() {
+
+    if (!_.isFunction(joint.routers.manhattan)) {
+
+        throw('Metro requires the manhattan router.');
+    }
+
+    var config = {
+
+        // cost of a diagonal step (calculated if not defined).
+        diagonalCost: null,
+
+        // an array of directions to find next points on the route
+        directions: function() {
+
+            var step = this.step;
+            var diagonalCost = this.diagonalCost || Math.ceil(Math.sqrt(step * step << 1));
+
+            return [
+                { offsetX: step  , offsetY: 0     , cost: step         },
+                { offsetX: step  , offsetY: step  , cost: diagonalCost },
+                { offsetX: 0     , offsetY: step  , cost: step         },
+                { offsetX: -step , offsetY: step  , cost: diagonalCost },
+                { offsetX: -step , offsetY: 0     , cost: step         },
+                { offsetX: -step , offsetY: -step , cost: diagonalCost },
+                { offsetX: 0     , offsetY: -step , cost: step         },
+                { offsetX: step  , offsetY: -step , cost: diagonalCost }
+            ];
+        },
+
+        // a simple route used in situations, when main routing method fails
+        // (exceed loops, inaccessible).
+        fallbackRoute: function(from, to, opts) {
+
+            // Find a route which breaks by 45 degrees ignoring all obstacles.
+
+            var theta = from.theta(to);
+
+            var a = { x: to.x, y: from.y };
+            var b = { x: from.x, y: to.y };
+
+            if (theta % 180 > 90) {
+                var t = a;
+                a = b;
+                b = t;
+            }
+
+            var p1 = (theta % 90) < 45 ? a : b;
+
+            var l1 = g.line(from, p1);
+
+            var alpha = 90 * Math.ceil(theta / 90);
+
+            var p2 = g.point.fromPolar(l1.squaredLength(), g.toRad(alpha + 135), p1);
+
+            var l2 = g.line(to, p2);
+
+            var point = l1.intersection(l2);
+
+            return point ? [point.round(), to] : [to];
+        }
+    };
+
+    // public function
+    return function(vertices, opts, linkView) {
+
+        return joint.routers.manhattan(vertices, _.extend({}, config, opts), linkView);
+    };
+
+})();
+
+joint.connectors.normal = function(sourcePoint, targetPoint, vertices) {
+
+    // Construct the `d` attribute of the `<path>` element.
+    var d = ['M', sourcePoint.x, sourcePoint.y];
+
+    _.each(vertices, function(vertex) {
+
+        d.push(vertex.x, vertex.y);
+    });
+
+    d.push(targetPoint.x, targetPoint.y);
+
+    return d.join(' ');
+};
+
+joint.connectors.rounded = function(sourcePoint, targetPoint, vertices, opts) {
+
+    var offset = opts.radius || 10;
+
+    var c1, c2, d1, d2, prev, next;
+
+    // Construct the `d` attribute of the `<path>` element.
+    var d = ['M', sourcePoint.x, sourcePoint.y];
+
+    _.each(vertices, function(vertex, index) {
+
+        // the closest vertices
+        prev = vertices[index-1] || sourcePoint;
+        next = vertices[index+1] || targetPoint;
+
+        // a half distance to the closest vertex
+        d1 = d2 || g.point(vertex).distance(prev) / 2;
+        d2 = g.point(vertex).distance(next) / 2;
+
+        // control points
+        c1 = g.point(vertex).move(prev, -Math.min(offset, d1)).round();
+        c2 = g.point(vertex).move(next, -Math.min(offset, d2)).round();
+
+        d.push(c1.x, c1.y, 'S', vertex.x, vertex.y, c2.x, c2.y, 'L');
+    });
+
+    d.push(targetPoint.x, targetPoint.y);
+
+    return d.join(' ');
+};
+
+joint.connectors.smooth = function(sourcePoint, targetPoint, vertices) {
+
+    var d;
+
+    if (vertices.length) {
+
+        d = g.bezier.curveThroughPoints([sourcePoint].concat(vertices).concat([targetPoint]));
+
+    } else {
+        // if we have no vertices use a default cubic bezier curve, cubic bezier requires
+        // two control points. The two control points are both defined with X as mid way
+        // between the source and target points. SourceControlPoint Y is equal to sourcePoint Y
+        // and targetControlPointY being equal to targetPointY. Handle situation were
+        // sourcePointX is greater or less then targetPointX.
+        var controlPointX = (sourcePoint.x < targetPoint.x) 
+                ? targetPoint.x - ((targetPoint.x - sourcePoint.x) / 2)
+                : sourcePoint.x - ((sourcePoint.x - targetPoint.x) / 2);
+
+        d = [
+            'M', sourcePoint.x, sourcePoint.y,
+            'C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y,
+            targetPoint.x, targetPoint.y
+        ];
+    }
+
+    return d.join(' ');
+};
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {},
+        dia: {
+            Element: require('../src/joint.dia.element').Element,
+            Link: require('../src/joint.dia.link').Link
+        }
+    };
+}
+
+
+joint.shapes.erd = {};
+
+joint.shapes.erd.Entity = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Entity',
+        size: { width: 150, height: 60 },
+        attrs: {
+            '.outer': {
+                fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2,
+                points: '100,0 100,60 0,60 0,0'
+            },
+            '.inner': {
+                fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2,
+                points: '95,5 95,55 5,55 5,5',
+                display: 'none'
+            },
+            text: {
+                text: 'Entity',
+                'font-family': 'Arial', 'font-size': 14,
+                ref: '.outer', 'ref-x': .5, 'ref-y': .5,
+                'x-alignment': 'middle', 'y-alignment': 'middle'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.erd.WeakEntity = joint.shapes.erd.Entity.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.WeakEntity',
+
+        attrs: {
+            '.inner' : { display: 'auto' },
+            text: { text: 'Weak Entity' }
+        }
+
+    }, joint.shapes.erd.Entity.prototype.defaults)
+});
+
+joint.shapes.erd.Relationship = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Relationship',
+        size: { width: 80, height: 80 },
+        attrs: {
+            '.outer': {
+                fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2,
+                points: '40,0 80,40 40,80 0,40'
+            },
+            '.inner': {
+                fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2,
+                points: '40,5 75,40 40,75 5,40',
+                display: 'none'
+            },
+            text: {
+                text: 'Relationship',
+                'font-family': 'Arial', 'font-size': 12,
+                ref: '.', 'ref-x': .5, 'ref-y': .5,
+                'x-alignment': 'middle', 'y-alignment': 'middle'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.erd.IdentifyingRelationship = joint.shapes.erd.Relationship.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.IdentifyingRelationship',
+
+        attrs: {
+            '.inner': { display: 'auto' },
+            text: { text: 'Identifying' }
+        }
+
+    }, joint.shapes.erd.Relationship.prototype.defaults)
+});
+
+joint.shapes.erd.Attribute = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><ellipse class="outer"/><ellipse class="inner"/></g><text/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Attribute',
+        size: { width: 100, height: 50 },
+        attrs: {
+            'ellipse': {
+                transform: 'translate(50, 25)'
+            },
+            '.outer': {
+                stroke: '#D35400', 'stroke-width': 2,
+                cx: 0, cy: 0, rx: 50, ry: 25,
+                fill: '#E67E22'
+            },
+            '.inner': {
+                stroke: '#D35400', 'stroke-width': 2,
+                cx: 0, cy: 0, rx: 45, ry: 20,
+                fill: 'transparent', display: 'none'
+            },
+            text: {
+                 'font-family': 'Arial', 'font-size': 14,
+                 ref: '.', 'ref-x': .5, 'ref-y': .5,
+                 'x-alignment': 'middle', 'y-alignment': 'middle'
+             }
+         }
+
+     }, joint.dia.Element.prototype.defaults)
+
+ });
+
+ joint.shapes.erd.Multivalued = joint.shapes.erd.Attribute.extend({
+
+     defaults: joint.util.deepSupplement({
+
+         type: 'erd.Multivalued',
+
+         attrs: {
+             '.inner': { display: 'block' },
+             text: { text: 'multivalued' }
+         }
+     }, joint.shapes.erd.Attribute.prototype.defaults)
+ });
+
+ joint.shapes.erd.Derived = joint.shapes.erd.Attribute.extend({
+
+     defaults: joint.util.deepSupplement({
+
+         type: 'erd.Derived',
+
+         attrs: {
+             '.outer': { 'stroke-dasharray': '3,5' },
+             text: { text: 'derived' }
+         }
+
+     }, joint.shapes.erd.Attribute.prototype.defaults)
+ });
+
+ joint.shapes.erd.Key = joint.shapes.erd.Attribute.extend({
+
+     defaults: joint.util.deepSupplement({
+
+         type: 'erd.Key',
+
+         attrs: {
+             ellipse: { 'stroke-width': 4 },
+             text: { text: 'key', 'font-weight': 'bold', 'text-decoration': 'underline' }
+         }
+     }, joint.shapes.erd.Attribute.prototype.defaults)
+});
+
+joint.shapes.erd.Normal = joint.shapes.erd.Attribute.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Normal',
+
+        attrs: { text: { text: 'Normal' }}
+
+    }, joint.shapes.erd.Attribute.prototype.defaults)
+});
+
+joint.shapes.erd.ISA = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.ISA',
+        size: { width: 100, height: 50 },
+        attrs: {
+            polygon: {
+                points: '0,0 50,50 100,0',
+                fill: '#F1C40F', stroke: '#F39C12', 'stroke-width': 2
+            },
+            text: {
+                text: 'ISA',
+                ref: '.', 'ref-x': .5, 'ref-y': .3,
+                'x-alignment': 'middle', 'y-alignment': 'middle'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+
+});
+
+joint.shapes.erd.Line = joint.dia.Link.extend({
+
+    defaults: { type: "erd.Line" },
+
+    cardinality: function(value) {
+        this.set('labels', [{ position: -20, attrs: { text: { dy: -8, text: value }}}]);
+    }
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.erd;
+}
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {
+            basic: require('./joint.shapes.basic')
+        },
+        dia: {
+            Element: require('../src/joint.dia.element').Element,
+            Link: require('../src/joint.dia.link').Link
+        }
+    };
+}
+
+joint.shapes.fsa = {};
+
+joint.shapes.fsa.State = joint.shapes.basic.Circle.extend({
+    defaults: joint.util.deepSupplement({
+        type: 'fsa.State',
+        attrs: {
+            circle: { 'stroke-width': 3 },
+            text: { 'font-weight': 'bold' }
+        }
+    }, joint.shapes.basic.Circle.prototype.defaults)
+});
+
+joint.shapes.fsa.StartState = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><circle/></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'fsa.StartState',
+        size: { width: 20, height: 20 },
+        attrs: {
+            circle: {
+                transform: 'translate(10, 10)',
+                r: 10,
+                fill: 'black'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.fsa.EndState = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'fsa.EndState',
+        size: { width: 20, height: 20 },
+        attrs: {
+            '.outer': {
+                transform: 'translate(10, 10)',
+                r: 10,
+                fill: '#FFFFFF',
+                stroke: 'black'
+            },
+
+            '.inner': {
+                transform: 'translate(10, 10)',
+                r: 6,
+                fill: '#000000'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.fsa.Arrow = joint.dia.Link.extend({
+
+    defaults: joint.util.deepSupplement({
+       type: 'fsa.Arrow',
+        attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }},
+        smooth: true
+    }, joint.dia.Link.prototype.defaults)
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.fsa;
+}
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {},
+        dia: {
+            Element: require('../src/joint.dia.element').Element,
+            Link: require('../src/joint.dia.link').Link
+        }
+    };
+}
+
+joint.shapes.org = {};
+
+joint.shapes.org.Member = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><rect class="card"/><image/></g><text class="rank"/><text class="name"/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'org.Member',
+        size: { width: 180, height: 70 },
+        attrs: {
+
+            rect: { width: 170, height: 60 },
+
+            '.card': {
+                fill: '#FFFFFF', stroke: '#000000', 'stroke-width': 2,
+                'pointer-events': 'visiblePainted', rx: 10, ry: 10
+            },
+
+            image: {
+               width: 48, height: 48,
+                ref: '.card', 'ref-x': 10, 'ref-y': 5
+            },
+            
+            '.rank': {
+                'text-decoration': 'underline',
+                ref: '.card', 'ref-x': 0.9, 'ref-y': 0.2,
+                'font-family': 'Courier New', 'font-size': 14,
+               'text-anchor': 'end'
+            },
+
+            '.name': {
+                'font-weight': 'bold',
+                ref: '.card', 'ref-x': 0.9, 'ref-y': 0.6,
+                'font-family': 'Courier New', 'font-size': 14,
+               'text-anchor': 'end'
+            }
+        }
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.org.Arrow = joint.dia.Link.extend({
+
+    defaults: {
+        type: 'org.Arrow',
+        source: { selector: '.card' }, target: { selector: '.card' },
+        attrs: { '.connection': { stroke: '#585858', 'stroke-width': 3 }},
+        z: -1
+    }
+});
+
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.org;
+}
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {
+            basic: require('./joint.shapes.basic')
+        },
+        dia: {}
+    };
+}
+
+joint.shapes.chess = {};
+
+joint.shapes.chess.KingWhite = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;"><path      d="M 22.5,11.63 L 22.5,6"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path      d="M 20,8 L 25,8"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path      d="M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25"      style="fill:#ffffff; stroke:#000000; stroke-linecap:butt; stroke-linejoin:miter;" />    <path      d="M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z "      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 11.5,30 C 17,27 27,27 32.5,30"      style="fill:none; stroke:#000000;" />    <path      d="M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5"      style="fill:none; stroke:#000000;" />    <path      d="M 11.5,37 C 17,34 27,34 32.5,37"      style="fill:none; stroke:#000000;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.KingWhite',
+        size: { width: 42, height: 38 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.KingBlack = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path       d="M 22.5,11.63 L 22.5,6"       style="fill:none; stroke:#000000; stroke-linejoin:miter;"       id="path6570" />    <path       d="M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25"       style="fill:#000000;fill-opacity:1; stroke-linecap:butt; stroke-linejoin:miter;" />    <path       d="M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z "       style="fill:#000000; stroke:#000000;" />    <path       d="M 20,8 L 25,8"       style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path       d="M 32,29.5 C 32,29.5 40.5,25.5 38.03,19.85 C 34.15,14 25,18 22.5,24.5 L 22.51,26.6 L 22.5,24.5 C 20,18 9.906,14 6.997,19.85 C 4.5,25.5 11.85,28.85 11.85,28.85"       style="fill:none; stroke:#ffffff;" />    <path       d="M 11.5,30 C 17,27 27,27 32.5,30 M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5 M 11.5,37 C 17,34 27,34 32.5,37"       style="fill:none; stroke:#ffffff;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.KingBlack',
+        size: { width: 42, height: 38 }
+        
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.QueenWhite = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(-1,-1)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(15.5,-5.5)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(32,-1)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(7,-4.5)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(24,-4)" />    <path      d="M 9,26 C 17.5,24.5 30,24.5 36,26 L 38,14 L 31,25 L 31,11 L 25.5,24.5 L 22.5,9.5 L 19.5,24.5 L 14,10.5 L 14,25 L 7,14 L 9,26 z "      style="stroke-linecap:butt;" />    <path      d="M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z "      style="stroke-linecap:butt;" />    <path      d="M 11.5,30 C 15,29 30,29 33.5,30"      style="fill:none;" />    <path      d="M 12,33.5 C 18,32.5 27,32.5 33,33.5"      style="fill:none;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.QueenWhite',
+        size: { width: 42, height: 38 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.QueenBlack = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#000000; stroke:none;">      <circle cx="6"    cy="12" r="2.75" />      <circle cx="14"   cy="9"  r="2.75" />      <circle cx="22.5" cy="8"  r="2.75" />      <circle cx="31"   cy="9"  r="2.75" />      <circle cx="39"   cy="12" r="2.75" />    </g>    <path       d="M 9,26 C 17.5,24.5 30,24.5 36,26 L 38.5,13.5 L 31,25 L 30.7,10.9 L 25.5,24.5 L 22.5,10 L 19.5,24.5 L 14.3,10.9 L 14,25 L 6.5,13.5 L 9,26 z"       style="stroke-linecap:butt; stroke:#000000;" />    <path       d="M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z"       style="stroke-linecap:butt;" />    <path       d="M 11,38.5 A 35,35 1 0 0 34,38.5"       style="fill:none; stroke:#000000; stroke-linecap:butt;" />    <path       d="M 11,29 A 35,35 1 0 1 34,29"       style="fill:none; stroke:#ffffff;" />    <path       d="M 12.5,31.5 L 32.5,31.5"       style="fill:none; stroke:#ffffff;" />    <path       d="M 11.5,34.5 A 35,35 1 0 0 33.5,34.5"       style="fill:none; stroke:#ffffff;" />    <path       d="M 10.5,37.5 A 35,35 1 0 0 34.5,37.5"       style="fill:none; stroke:#ffffff;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.QueenBlack',
+        size: { width: 42, height: 38 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.RookWhite = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z "      style="stroke-linecap:butt;" />    <path      d="M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z "      style="stroke-linecap:butt;" />    <path      d="M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14"      style="stroke-linecap:butt;" />    <path      d="M 34,14 L 31,17 L 14,17 L 11,14" />    <path      d="M 31,17 L 31,29.5 L 14,29.5 L 14,17"      style="stroke-linecap:butt; stroke-linejoin:miter;" />    <path      d="M 31,29.5 L 32.5,32 L 12.5,32 L 14,29.5" />    <path      d="M 11,14 L 34,14"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.RookWhite',
+        size: { width: 32, height: 34 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.RookBlack = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z "      style="stroke-linecap:butt;" />    <path      d="M 12.5,32 L 14,29.5 L 31,29.5 L 32.5,32 L 12.5,32 z "      style="stroke-linecap:butt;" />    <path      d="M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z "      style="stroke-linecap:butt;" />    <path      d="M 14,29.5 L 14,16.5 L 31,16.5 L 31,29.5 L 14,29.5 z "      style="stroke-linecap:butt;stroke-linejoin:miter;" />    <path      d="M 14,16.5 L 11,14 L 34,14 L 31,16.5 L 14,16.5 z "      style="stroke-linecap:butt;" />    <path      d="M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14 L 11,14 z "      style="stroke-linecap:butt;" />    <path      d="M 12,35.5 L 33,35.5 L 33,35.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 13,31.5 L 32,31.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 14,29.5 L 31,29.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 14,16.5 L 31,16.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 11,14 L 34,14"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.RookBlack',
+        size: { width: 32, height: 34 }
+        
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.BishopWhite = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-rule:evenodd; fill-opacity:1; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:round; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#ffffff; stroke:#000000; stroke-linecap:butt;">       <path        d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />      <path        d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />      <path        d="M 25 8 A 2.5 2.5 0 1 1  20,8 A 2.5 2.5 0 1 1  25 8 z" />    </g>    <path      d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.BishopWhite',
+        size: { width: 38, height: 38 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.BishopBlack = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-rule:evenodd; fill-opacity:1; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:round; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#000000; stroke:#000000; stroke-linecap:butt;">       <path        d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />      <path        d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />      <path        d="M 25 8 A 2.5 2.5 0 1 1  20,8 A 2.5 2.5 0 1 1  25 8 z" />    </g>    <path       d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"       style="fill:none; stroke:#ffffff; stroke-linejoin:miter;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.BishopBlack',
+        size: { width: 38, height: 38 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.KnightWhite = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18"      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10"      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z"      style="fill:#000000; stroke:#000000;" />    <path      d="M 15 15.5 A 0.5 1.5 0 1 1  14,15.5 A 0.5 1.5 0 1 1  15 15.5 z"      transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)"      style="fill:#000000; stroke:#000000;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.KnightWhite',
+        size: { width: 38, height: 37 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.KnightBlack = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18"      style="fill:#000000; stroke:#000000;" />    <path      d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10"      style="fill:#000000; stroke:#000000;" />    <path      d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z"      style="fill:#ffffff; stroke:#ffffff;" />    <path      d="M 15 15.5 A 0.5 1.5 0 1 1  14,15.5 A 0.5 1.5 0 1 1  15 15.5 z"      transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)"      style="fill:#ffffff; stroke:#ffffff;" />    <path      d="M 24.55,10.4 L 24.1,11.85 L 24.6,12 C 27.75,13 30.25,14.49 32.5,18.75 C 34.75,23.01 35.75,29.06 35.25,39 L 35.2,39.5 L 37.45,39.5 L 37.5,39 C 38,28.94 36.62,22.15 34.25,17.66 C 31.88,13.17 28.46,11.02 25.06,10.5 L 24.55,10.4 z "      style="fill:#ffffff; stroke:none;" />  </g></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.KnightBlack',
+        size: { width: 38, height: 37 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.PawnWhite = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><path d="M 22,9 C 19.79,9 18,10.79 18,13 C 18,13.89 18.29,14.71 18.78,15.38 C 16.83,16.5 15.5,18.59 15.5,21 C 15.5,23.03 16.44,24.84 17.91,26.03 C 14.91,27.09 10.5,31.58 10.5,39.5 L 33.5,39.5 C 33.5,31.58 29.09,27.09 26.09,26.03 C 27.56,24.84 28.5,23.03 28.5,21 C 28.5,18.59 27.17,16.5 25.22,15.38 C 25.71,14.71 26,13.89 26,13 C 26,10.79 24.21,9 22,9 z "  style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:nonzero; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:miter; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;" /></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.PawnWhite',
+        size: { width: 28, height: 33 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.chess.PawnBlack = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><path d="M 22,9 C 19.79,9 18,10.79 18,13 C 18,13.89 18.29,14.71 18.78,15.38 C 16.83,16.5 15.5,18.59 15.5,21 C 15.5,23.03 16.44,24.84 17.91,26.03 C 14.91,27.09 10.5,31.58 10.5,39.5 L 33.5,39.5 C 33.5,31.58 29.09,27.09 26.09,26.03 C 27.56,24.84 28.5,23.03 28.5,21 C 28.5,18.59 27.17,16.5 25.22,15.38 C 25.71,14.71 26,13.89 26,13 C 26,10.79 24.21,9 22,9 z "  style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:nonzero; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:miter; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;" /></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'chess.PawnBlack',
+        size: { width: 28, height: 33 }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.chess;
+}
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {
+            basic: require('./joint.shapes.basic')
+        },
+        dia: {
+            ElementView: require('../src/joint.dia.element').ElementView,
+            Link: require('../src/joint.dia.link').Link
+        }
+    };
+}
+
+joint.shapes.pn = {};
+
+joint.shapes.pn.Place = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><circle class="root"/><g class="tokens" /></g><text class="label"/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'pn.Place',
+        size: { width: 50, height: 50 },
+        attrs: {
+            '.root': {
+                r: 25,
+                fill: 'white',
+                stroke: 'black',
+                transform: 'translate(25, 25)'
+            },
+            '.label': {
+                'text-anchor': 'middle',
+                'ref-x': .5,
+                'ref-y': -20,
+                ref: '.root',
+                fill: 'black',
+                'font-size': 12
+            },
+            '.tokens > circle': {
+                fill: 'black',
+                r: 5
+            },
+            '.tokens.one > circle': { transform: 'translate(25, 25)' },
+            
+            '.tokens.two > circle:nth-child(1)': { transform: 'translate(19, 25)' },
+            '.tokens.two > circle:nth-child(2)': { transform: 'translate(31, 25)' },
+            
+            '.tokens.three > circle:nth-child(1)': { transform: 'translate(18, 29)' },
+            '.tokens.three > circle:nth-child(2)': { transform: 'translate(25, 19)' },
+            '.tokens.three > circle:nth-child(3)': { transform: 'translate(32, 29)' },
+
+            '.tokens.alot > text': {
+               transform: 'translate(25, 18)',
+               'text-anchor': 'middle',
+                fill: 'black'
+            }
+        }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+
+joint.shapes.pn.PlaceView = joint.dia.ElementView.extend({
+
+    initialize: function() {
+
+        joint.dia.ElementView.prototype.initialize.apply(this, arguments);
+
+        this.model.on('change:tokens', function() {
+
+            this.renderTokens();
+            this.update();
+
+        }, this);
+    },
+
+    render: function() {
+
+        joint.dia.ElementView.prototype.render.apply(this, arguments);
+
+        this.renderTokens();
+        this.update();
+    },
+
+    renderTokens: function() {
+
+        var $tokens = this.$('.tokens').empty();
+        $tokens[0].className.baseVal = 'tokens';
+
+        var tokens = this.model.get('tokens');
+
+        if (!tokens) return;
+
+        switch (tokens) {
+
+          case 1:
+            $tokens[0].className.baseVal += ' one';
+            $tokens.append(V('<circle/>').node);
+            break;
+            
+          case 2:
+            $tokens[0].className.baseVal += ' two';
+            $tokens.append(V('<circle/>').node, V('<circle/>').node);
+            break;
+
+          case 3:
+            $tokens[0].className.baseVal += ' three';
+            $tokens.append(V('<circle/>').node, V('<circle/>').node, V('<circle/>').node);
+            break;
+
+          default:
+            $tokens[0].className.baseVal += ' alot';
+            $tokens.append(V('<text/>').text(tokens + '' ).node);
+            break;
+        }
+    }
+});
+
+
+joint.shapes.pn.Transition = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><rect class="root"/></g></g><text class="label"/>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'pn.Transition',
+        size: { width: 12, height: 50 },
+        attrs: {
+            'rect': {
+                width: 12,
+                height: 50,
+                fill: 'black',
+                stroke: 'black'
+            },
+            '.label': {
+                'text-anchor': 'middle',
+                'ref-x': .5,
+                'ref-y': -20,
+                ref: 'rect',
+                fill: 'black',
+                'font-size': 12
+            }
+        }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.pn.Link = joint.dia.Link.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }}
+        
+    }, joint.dia.Link.prototype.defaults)
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.pn;
+}
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {
+            basic: require('./joint.shapes.basic')
+        },
+        dia: {
+            ElementView: require('../src/joint.dia.element').ElementView,
+            Link: require('../src/joint.dia.link').Link
+        }
+    };
+    var _ = require('lodash');
+}
+
+joint.shapes.devs = {};
+
+joint.shapes.devs.Model = joint.shapes.basic.Generic.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
+
+    markup: '<g class="rotatable"><g class="scalable"><rect/></g><text class="label"/><g class="inPorts"/><g class="outPorts"/></g>',
+    portMarkup: '<g class="port<%= id %>"><circle/><text/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'devs.Model',
+        size: { width: 1, height: 1 },
+        
+        inPorts: [],
+        outPorts: [],
+
+        attrs: {
+            '.': { magnet: false },
+            rect: {
+                width: 150, height: 250,
+                stroke: 'black'
+            },
+            circle: {
+                r: 10,
+                magnet: true,
+                stroke: 'black'
+            },
+            text: {
+                fill: 'black',
+                'pointer-events': 'none'
+            },
+            '.label': { text: 'Model', 'ref-x': .3, 'ref-y': .2 },
+            '.inPorts text': { x:-15, dy: 4, 'text-anchor': 'end' },
+            '.outPorts text':{ x: 15, dy: 4 }
+        }
+
+    }, joint.shapes.basic.Generic.prototype.defaults),
+
+    getPortAttrs: function(portName, index, total, selector, type) {
+
+        var attrs = {};
+        
+        var portClass = 'port' + index;
+        var portSelector = selector + '>.' + portClass;
+        var portTextSelector = portSelector + '>text';
+        var portCircleSelector = portSelector + '>circle';
+
+        attrs[portTextSelector] = { text: portName };
+        attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type) , type: type } };
+        attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) };
+        
+        if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; }
+
+        return attrs;
+    }
+}));
+
+
+joint.shapes.devs.Atomic = joint.shapes.devs.Model.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'devs.Atomic',
+        size: { width: 80, height: 80 },
+        attrs: {
+            rect: { fill: 'salmon' },
+            '.label': { text: 'Atomic' },
+            '.inPorts circle': { fill: 'PaleGreen' },
+            '.outPorts circle': { fill: 'Tomato' }
+        }
+
+    }, joint.shapes.devs.Model.prototype.defaults)
+
+});
+
+joint.shapes.devs.Coupled = joint.shapes.devs.Model.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'devs.Coupled',
+        size: { width: 200, height: 300 },
+        attrs: {
+            rect: { fill: 'seaGreen' },
+            '.label': { text: 'Coupled' },
+            '.inPorts circle': { fill: 'PaleGreen' },
+            '.outPorts circle': { fill: 'Tomato' }
+        }
+
+    }, joint.shapes.devs.Model.prototype.defaults)
+});
+
+joint.shapes.devs.Link = joint.dia.Link.extend({
+
+    defaults: {
+        type: 'devs.Link',
+        attrs: { '.connection' : { 'stroke-width' :  2 }}
+    }
+});
+
+joint.shapes.devs.ModelView = joint.dia.ElementView.extend(joint.shapes.basic.PortsViewInterface);
+joint.shapes.devs.AtomicView = joint.shapes.devs.ModelView;
+joint.shapes.devs.CoupledView = joint.shapes.devs.ModelView;
+
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.devs;
+}
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {
+            basic: require('./joint.shapes.basic')
+        },
+        dia: {
+            ElementView: require('../src/joint.dia.element').ElementView,
+            Link: require('../src/joint.dia.link').Link
+        }
+    };
+    var _ = require('lodash');
+}
+
+joint.shapes.uml = {}
+
+joint.shapes.uml.Class = joint.shapes.basic.Generic.extend({
+
+    markup: [
+        '<g class="rotatable">',
+          '<g class="scalable">',
+            '<rect class="uml-class-name-rect"/><rect class="uml-class-attrs-rect"/><rect class="uml-class-methods-rect"/>',
+          '</g>',
+          '<text class="uml-class-name-text"/><text class="uml-class-attrs-text"/><text class="uml-class-methods-text"/>',
+        '</g>'
+    ].join(''),
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'uml.Class',
+
+        attrs: {
+            rect: { 'width': 200 },
+
+            '.uml-class-name-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#3498db' },
+            '.uml-class-attrs-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' },
+            '.uml-class-methods-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' },
+
+            '.uml-class-name-text': {
+                'ref': '.uml-class-name-rect', 'ref-y': .5, 'ref-x': .5, 'text-anchor': 'middle', 'y-alignment': 'middle', 'font-weight': 'bold',
+                'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
+            },
+            '.uml-class-attrs-text': {
+                'ref': '.uml-class-attrs-rect', 'ref-y': 5, 'ref-x': 5,
+                'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
+            },
+            '.uml-class-methods-text': {
+                'ref': '.uml-class-methods-rect', 'ref-y': 5, 'ref-x': 5,
+                'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
+            }
+        },
+
+        name: [],
+        attributes: [],
+        methods: []
+
+    }, joint.shapes.basic.Generic.prototype.defaults),
+
+    initialize: function() {
+
+        _.bindAll(this, 'updateRectangles');
+
+        this.on('change:name change:attributes change:methods', function() {
+            this.updateRectangles();
+           this.trigger('uml-update');
+        });
+
+        this.updateRectangles();
+
+        joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
+    },
+
+    getClassName: function() {
+        return this.get('name');
+    },
+
+    updateRectangles: function() {
+
+        var attrs = this.get('attrs');
+
+        var rects = [
+            { type: 'name', text: this.getClassName() },
+            { type: 'attrs', text: this.get('attributes') },
+            { type: 'methods', text: this.get('methods') }
+        ];
+
+        var offsetY = 0;
+
+        _.each(rects, function(rect) {
+
+            var lines = _.isArray(rect.text) ? rect.text : [rect.text];
+           var rectHeight = lines.length * 20 + 20;
+
+            attrs['.uml-class-' + rect.type + '-text'].text = lines.join('\n');
+            attrs['.uml-class-' + rect.type + '-rect'].height = rectHeight;
+            attrs['.uml-class-' + rect.type + '-rect'].transform = 'translate(0,'+ offsetY + ')';
+
+            offsetY += rectHeight;
+        });
+    }
+
+});
+
+joint.shapes.uml.ClassView = joint.dia.ElementView.extend({
+
+    initialize: function() {
+
+        joint.dia.ElementView.prototype.initialize.apply(this, arguments);
+
+       this.model.on('uml-update', _.bind(function() {
+           this.update();
+           this.resize();
+       }, this));
+    }
+});
+
+joint.shapes.uml.Abstract = joint.shapes.uml.Class.extend({
+
+    defaults: joint.util.deepSupplement({
+        type: 'uml.Abstract',
+        attrs: {
+            '.uml-class-name-rect': { fill : '#e74c3c' },
+            '.uml-class-attrs-rect': { fill : '#c0392b' },
+            '.uml-class-methods-rect': { fill : '#c0392b' }
+        }
+    }, joint.shapes.uml.Class.prototype.defaults),
+
+    getClassName: function() {
+        return ['<<Abstract>>', this.get('name')];
+    }
+
+});
+joint.shapes.uml.AbstractView = joint.shapes.uml.ClassView;
+
+joint.shapes.uml.Interface = joint.shapes.uml.Class.extend({
+
+    defaults: joint.util.deepSupplement({
+        type: 'uml.Interface',
+        attrs: {
+            '.uml-class-name-rect': { fill : '#f1c40f' },
+            '.uml-class-attrs-rect': { fill : '#f39c12' },
+            '.uml-class-methods-rect': { fill : '#f39c12' }
+        }
+    }, joint.shapes.uml.Class.prototype.defaults),
+
+    getClassName: function() {
+        return ['<<Interface>>', this.get('name')];
+    }
+
+});
+joint.shapes.uml.InterfaceView = joint.shapes.uml.ClassView;
+
+joint.shapes.uml.Generalization = joint.dia.Link.extend({
+    defaults: {
+        type: 'uml.Generalization',
+        attrs: { '.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' }}
+    }
+});
+
+joint.shapes.uml.Implementation = joint.dia.Link.extend({
+    defaults: {
+        type: 'uml.Implementation',
+        attrs: {
+            '.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' },
+            '.connection': { 'stroke-dasharray': '3,3' }
+        }
+    }
+});
+
+joint.shapes.uml.Aggregation = joint.dia.Link.extend({
+    defaults: {
+        type: 'uml.Aggregation',
+        attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'white' }}
+    }
+});
+
+joint.shapes.uml.Composition = joint.dia.Link.extend({
+    defaults: {
+        type: 'uml.Composition',
+        attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'black' }}
+    }
+});
+
+joint.shapes.uml.Association = joint.dia.Link.extend({
+    defaults: { type: 'uml.Association' }
+});
+
+// Statechart
+
+joint.shapes.uml.State = joint.shapes.basic.Generic.extend({
+
+    markup: [
+        '<g class="rotatable">',
+          '<g class="scalable">',
+            '<rect/>',
+          '</g>',
+          '<path/><text class="uml-state-name"/><text class="uml-state-events"/>',
+        '</g>'
+    ].join(''),
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'uml.State',
+
+        attrs: {
+            rect: { 'width': 200, 'height': 200, 'fill': '#ecf0f1', 'stroke': '#bdc3c7', 'stroke-width': 3, 'rx': 10, 'ry': 10 },
+            path: { 'd': 'M 0 20 L 200 20', 'stroke': '#bdc3c7', 'stroke-width': 2 },
+            '.uml-state-name': {
+                'ref': 'rect', 'ref-x': .5, 'ref-y': 5, 'text-anchor': 'middle',
+                'font-family': 'Courier New', 'font-size': 14, fill: '#000000'
+            },
+            '.uml-state-events': {
+                'ref': 'path', 'ref-x': 5, 'ref-y': 5,
+                'font-family': 'Courier New', 'font-size': 14, fill: '#000000'
+            }
+        },
+
+        name: 'State',
+        events: []
+
+    }, joint.shapes.basic.Generic.prototype.defaults),
+
+    initialize: function() {
+
+        _.bindAll(this, 'updateEvents', 'updatePath');
+
+        this.on({
+            'change:name': function() { this.updateName(); this.trigger('change:attrs'); },
+            'change:events': function() { this.updateEvents(); this.trigger('change:attrs'); },
+            'change:size': this.updatePath
+        });
+
+        this.updateName();
+        this.updateEvents();
+        this.updatePath();
+
+        joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
+    },
+
+    updateName: function() {
+        this.get('attrs')['.uml-state-name'].text = this.get('name');
+    },
+
+    updateEvents: function() {
+        this.get('attrs')['.uml-state-events'].text = this.get('events').join('\n');
+    },
+
+    updatePath: function() {
+        this.get('attrs')['path'].d = 'M 0 20 L ' + this.get('size').width + ' 20';
+    }
+
+});
+
+joint.shapes.uml.StartState = joint.shapes.basic.Circle.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'uml.StartState',
+        attrs: { circle: { 'fill': '#34495e', 'stroke': '#2c3e50', 'stroke-width': 2, 'rx': 1 }}
+
+    }, joint.shapes.basic.Circle.prototype.defaults)
+
+});
+
+joint.shapes.uml.EndState = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'uml.EndState',
+        size: { width: 20, height: 20 },
+        attrs: {
+            'circle.outer': {
+                transform: 'translate(10, 10)',
+                r: 10,
+                fill: 'white',
+                stroke: '#2c3e50'
+            },
+
+            'circle.inner': {
+                transform: 'translate(10, 10)',
+                r: 6,
+                fill: '#34495e'
+            }
+        }
+
+    }, joint.shapes.basic.Generic.prototype.defaults)
+
+});
+
+joint.shapes.uml.Transition = joint.dia.Link.extend({
+    defaults: {
+        type: 'uml.Transition',
+        attrs: {
+            '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z', fill: '#34495e', stroke: '#2c3e50' },
+            '.connection': { stroke: '#2c3e50' }
+        }
+    }
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.uml;
+}
+
+;(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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 global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
+ * @license
+ * Copyright (c) 2012-2013 Chris Pettitt
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+global.dagre = require("./index");
+
+},{"./index":2}],2:[function(require,module,exports){
+/*
+Copyright (c) 2012-2013 Chris Pettitt
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+exports.Digraph = require("graphlib").Digraph;
+exports.Graph = require("graphlib").Graph;
+exports.layout = require("./lib/layout");
+exports.version = require("./lib/version");
+
+},{"./lib/layout":3,"./lib/version":18,"graphlib":24}],3:[function(require,module,exports){
+var util = require('./util'),
+    rank = require('./rank'),
+    order = require('./order'),
+    CGraph = require('graphlib').CGraph,
+    CDigraph = require('graphlib').CDigraph;
+
+module.exports = function() {
+  // External configuration
+  var config = {
+    // How much debug information to include?
+    debugLevel: 0,
+    // Max number of sweeps to perform in order phase
+    orderMaxSweeps: order.DEFAULT_MAX_SWEEPS,
+    // Use network simplex algorithm in ranking
+    rankSimplex: false,
+    // Rank direction. Valid values are (TB, LR)
+    rankDir: 'TB'
+  };
+
+  // Phase functions
+  var position = require('./position')();
+
+  // This layout object
+  var self = {};
+
+  self.orderIters = util.propertyAccessor(self, config, 'orderMaxSweeps');
+
+  self.rankSimplex = util.propertyAccessor(self, config, 'rankSimplex');
+
+  self.nodeSep = delegateProperty(position.nodeSep);
+  self.edgeSep = delegateProperty(position.edgeSep);
+  self.universalSep = delegateProperty(position.universalSep);
+  self.rankSep = delegateProperty(position.rankSep);
+  self.rankDir = util.propertyAccessor(self, config, 'rankDir');
+  self.debugAlignment = delegateProperty(position.debugAlignment);
+
+  self.debugLevel = util.propertyAccessor(self, config, 'debugLevel', function(x) {
+    util.log.level = x;
+    position.debugLevel(x);
+  });
+
+  self.run = util.time('Total layout', run);
+
+  self._normalize = normalize;
+
+  return self;
+
+  /*
+   * Constructs an adjacency graph using the nodes and edges specified through
+   * config. For each node and edge we add a property `dagre` that contains an
+   * object that will hold intermediate and final layout information. Some of
+   * the contents include:
+   *
+   *  1) A generated ID that uniquely identifies the object.
+   *  2) Dimension information for nodes (copied from the source node).
+   *  3) Optional dimension information for edges.
+   *
+   * After the adjacency graph is constructed the code no longer needs to use
+   * the original nodes and edges passed in via config.
+   */
+  function initLayoutGraph(inputGraph) {
+    var g = new CDigraph();
+
+    inputGraph.eachNode(function(u, value) {
+      if (value === undefined) value = {};
+      g.addNode(u, {
+        width: value.width,
+        height: value.height
+      });
+      if (value.hasOwnProperty('rank')) {
+        g.node(u).prefRank = value.rank;
+      }
+    });
+
+    // Set up subgraphs
+    if (inputGraph.parent) {
+      inputGraph.nodes().forEach(function(u) {
+        g.parent(u, inputGraph.parent(u));
+      });
+    }
+
+    inputGraph.eachEdge(function(e, u, v, value) {
+      if (value === undefined) value = {};
+      var newValue = {
+        e: e,
+        minLen: value.minLen || 1,
+        width: value.width || 0,
+        height: value.height || 0,
+        points: []
+      };
+
+      g.addEdge(null, u, v, newValue);
+    });
+
+    // Initial graph attributes
+    var graphValue = inputGraph.graph() || {};
+    g.graph({
+      rankDir: graphValue.rankDir || config.rankDir,
+      orderRestarts: graphValue.orderRestarts
+    });
+
+    return g;
+  }
+
+  function run(inputGraph) {
+    var rankSep = self.rankSep();
+    var g;
+    try {
+      // Build internal graph
+      g = util.time('initLayoutGraph', initLayoutGraph)(inputGraph);
+
+      if (g.order() === 0) {
+        return g;
+      }
+
+      // Make space for edge labels
+      g.eachEdge(function(e, s, t, a) {
+        a.minLen *= 2;
+      });
+      self.rankSep(rankSep / 2);
+
+      // Determine the rank for each node. Nodes with a lower rank will appear
+      // above nodes of higher rank.
+      util.time('rank.run', rank.run)(g, config.rankSimplex);
+
+      // Normalize the graph by ensuring that every edge is proper (each edge has
+      // a length of 1). We achieve this by adding dummy nodes to long edges,
+      // thus shortening them.
+      util.time('normalize', normalize)(g);
+
+      // Order the nodes so that edge crossings are minimized.
+      util.time('order', order)(g, config.orderMaxSweeps);
+
+      // Find the x and y coordinates for every node in the graph.
+      util.time('position', position.run)(g);
+
+      // De-normalize the graph by removing dummy nodes and augmenting the
+      // original long edges with coordinate information.
+      util.time('undoNormalize', undoNormalize)(g);
+
+      // Reverses points for edges that are in a reversed state.
+      util.time('fixupEdgePoints', fixupEdgePoints)(g);
+
+      // Restore delete edges and reverse edges that were reversed in the rank
+      // phase.
+      util.time('rank.restoreEdges', rank.restoreEdges)(g);
+
+      // Construct final result graph and return it
+      return util.time('createFinalGraph', createFinalGraph)(g, inputGraph.isDirected());
+    } finally {
+      self.rankSep(rankSep);
+    }
+  }
+
+  /*
+   * This function is responsible for 'normalizing' the graph. The process of
+   * normalization ensures that no edge in the graph has spans more than one
+   * rank. To do this it inserts dummy nodes as needed and links them by adding
+   * dummy edges. This function keeps enough information in the dummy nodes and
+   * edges to ensure that the original graph can be reconstructed later.
+   *
+   * This method assumes that the input graph is cycle free.
+   */
+  function normalize(g) {
+    var dummyCount = 0;
+    g.eachEdge(function(e, s, t, a) {
+      var sourceRank = g.node(s).rank;
+      var targetRank = g.node(t).rank;
+      if (sourceRank + 1 < targetRank) {
+        for (var u = s, rank = sourceRank + 1, i = 0; rank < targetRank; ++rank, ++i) {
+          var v = '_D' + (++dummyCount);
+          var node = {
+            width: a.width,
+            height: a.height,
+            edge: { id: e, source: s, target: t, attrs: a },
+            rank: rank,
+            dummy: true
+          };
+
+          // If this node represents a bend then we will use it as a control
+          // point. For edges with 2 segments this will be the center dummy
+          // node. For edges with more than two segments, this will be the
+          // first and last dummy node.
+          if (i === 0) node.index = 0;
+          else if (rank + 1 === targetRank) node.index = 1;
+
+          g.addNode(v, node);
+          g.addEdge(null, u, v, {});
+          u = v;
+        }
+        g.addEdge(null, u, t, {});
+        g.delEdge(e);
+      }
+    });
+  }
+
+  /*
+   * Reconstructs the graph as it was before normalization. The positions of
+   * dummy nodes are used to build an array of points for the original 'long'
+   * edge. Dummy nodes and edges are removed.
+   */
+  function undoNormalize(g) {
+    g.eachNode(function(u, a) {
+      if (a.dummy) {
+        if ('index' in a) {
+          var edge = a.edge;
+          if (!g.hasEdge(edge.id)) {
+            g.addEdge(edge.id, edge.source, edge.target, edge.attrs);
+          }
+          var points = g.edge(edge.id).points;
+          points[a.index] = { x: a.x, y: a.y, ul: a.ul, ur: a.ur, dl: a.dl, dr: a.dr };
+        }
+        g.delNode(u);
+      }
+    });
+  }
+
+  /*
+   * For each edge that was reversed during the `acyclic` step, reverse its
+   * array of points.
+   */
+  function fixupEdgePoints(g) {
+    g.eachEdge(function(e, s, t, a) { if (a.reversed) a.points.reverse(); });
+  }
+
+  function createFinalGraph(g, isDirected) {
+    var out = isDirected ? new CDigraph() : new CGraph();
+    out.graph(g.graph());
+    g.eachNode(function(u, value) { out.addNode(u, value); });
+    g.eachNode(function(u) { out.parent(u, g.parent(u)); });
+    g.eachEdge(function(e, u, v, value) {
+      out.addEdge(value.e, u, v, value);
+    });
+
+    // Attach bounding box information
+    var maxX = 0, maxY = 0;
+    g.eachNode(function(u, value) {
+      if (!g.children(u).length) {
+        maxX = Math.max(maxX, value.x + value.width / 2);
+        maxY = Math.max(maxY, value.y + value.height / 2);
+      }
+    });
+    g.eachEdge(function(e, u, v, value) {
+      var maxXPoints = Math.max.apply(Math, value.points.map(function(p) { return p.x; }));
+      var maxYPoints = Math.max.apply(Math, value.points.map(function(p) { return p.y; }));
+      maxX = Math.max(maxX, maxXPoints + value.width / 2);
+      maxY = Math.max(maxY, maxYPoints + value.height / 2);
+    });
+    out.graph().width = maxX;
+    out.graph().height = maxY;
+
+    return out;
+  }
+
+  /*
+   * Given a function, a new function is returned that invokes the given
+   * function. The return value from the function is always the `self` object.
+   */
+  function delegateProperty(f) {
+    return function() {
+      if (!arguments.length) return f();
+      f.apply(null, arguments);
+      return self;
+    };
+  }
+};
+
+
+},{"./order":4,"./position":9,"./rank":10,"./util":17,"graphlib":24}],4:[function(require,module,exports){
+var util = require('./util'),
+    crossCount = require('./order/crossCount'),
+    initLayerGraphs = require('./order/initLayerGraphs'),
+    initOrder = require('./order/initOrder'),
+    sortLayer = require('./order/sortLayer');
+
+module.exports = order;
+
+// The maximum number of sweeps to perform before finishing the order phase.
+var DEFAULT_MAX_SWEEPS = 24;
+order.DEFAULT_MAX_SWEEPS = DEFAULT_MAX_SWEEPS;
+
+/*
+ * Runs the order phase with the specified `graph, `maxSweeps`, and
+ * `debugLevel`. If `maxSweeps` is not specified we use `DEFAULT_MAX_SWEEPS`.
+ * If `debugLevel` is not set we assume 0.
+ */
+function order(g, maxSweeps) {
+  if (arguments.length < 2) {
+    maxSweeps = DEFAULT_MAX_SWEEPS;
+  }
+
+  var restarts = g.graph().orderRestarts || 0;
+
+  var layerGraphs = initLayerGraphs(g);
+  // TODO: remove this when we add back support for ordering clusters
+  layerGraphs.forEach(function(lg) {
+    lg = lg.filterNodes(function(u) { return !g.children(u).length; });
+  });
+
+  var iters = 0,
+      currentBestCC,
+      allTimeBestCC = Number.MAX_VALUE,
+      allTimeBest = {};
+
+  function saveAllTimeBest() {
+    g.eachNode(function(u, value) { allTimeBest[u] = value.order; });
+  }
+
+  for (var j = 0; j < Number(restarts) + 1 && allTimeBestCC !== 0; ++j) {
+    currentBestCC = Number.MAX_VALUE;
+    initOrder(g, restarts > 0);
+
+    util.log(2, 'Order phase start cross count: ' + g.graph().orderInitCC);
+
+    var i, lastBest, cc;
+    for (i = 0, lastBest = 0; lastBest < 4 && i < maxSweeps && currentBestCC > 0; ++i, ++lastBest, ++iters) {
+      sweep(g, layerGraphs, i);
+      cc = crossCount(g);
+      if (cc < currentBestCC) {
+        lastBest = 0;
+        currentBestCC = cc;
+        if (cc < allTimeBestCC) {
+          saveAllTimeBest();
+          allTimeBestCC = cc;
+        }
+      }
+      util.log(3, 'Order phase start ' + j + ' iter ' + i + ' cross count: ' + cc);
+    }
+  }
+
+  Object.keys(allTimeBest).forEach(function(u) {
+    if (!g.children || !g.children(u).length) {
+      g.node(u).order = allTimeBest[u];
+    }
+  });
+  g.graph().orderCC = allTimeBestCC;
+
+  util.log(2, 'Order iterations: ' + iters);
+  util.log(2, 'Order phase best cross count: ' + g.graph().orderCC);
+}
+
+function predecessorWeights(g, nodes) {
+  var weights = {};
+  nodes.forEach(function(u) {
+    weights[u] = g.inEdges(u).map(function(e) {
+      return g.node(g.source(e)).order;
+    });
+  });
+  return weights;
+}
+
+function successorWeights(g, nodes) {
+  var weights = {};
+  nodes.forEach(function(u) {
+    weights[u] = g.outEdges(u).map(function(e) {
+      return g.node(g.target(e)).order;
+    });
+  });
+  return weights;
+}
+
+function sweep(g, layerGraphs, iter) {
+  if (iter % 2 === 0) {
+    sweepDown(g, layerGraphs, iter);
+  } else {
+    sweepUp(g, layerGraphs, iter);
+  }
+}
+
+function sweepDown(g, layerGraphs) {
+  var cg;
+  for (i = 1; i < layerGraphs.length; ++i) {
+    cg = sortLayer(layerGraphs[i], cg, predecessorWeights(g, layerGraphs[i].nodes()));
+  }
+}
+
+function sweepUp(g, layerGraphs) {
+  var cg;
+  for (i = layerGraphs.length - 2; i >= 0; --i) {
+    sortLayer(layerGraphs[i], cg, successorWeights(g, layerGraphs[i].nodes()));
+  }
+}
+
+},{"./order/crossCount":5,"./order/initLayerGraphs":6,"./order/initOrder":7,"./order/sortLayer":8,"./util":17}],5:[function(require,module,exports){
+var util = require('../util');
+
+module.exports = crossCount;
+
+/*
+ * Returns the cross count for the given graph.
+ */
+function crossCount(g) {
+  var cc = 0;
+  var ordering = util.ordering(g);
+  for (var i = 1; i < ordering.length; ++i) {
+    cc += twoLayerCrossCount(g, ordering[i-1], ordering[i]);
+  }
+  return cc;
+}
+
+/*
+ * This function searches through a ranked and ordered graph and counts the
+ * number of edges that cross. This algorithm is derived from:
+ *
+ *    W. Barth et al., Bilayer Cross Counting, JGAA, 8(2) 179–194 (2004)
+ */
+function twoLayerCrossCount(g, layer1, layer2) {
+  var indices = [];
+  layer1.forEach(function(u) {
+    var nodeIndices = [];
+    g.outEdges(u).forEach(function(e) { nodeIndices.push(g.node(g.target(e)).order); });
+    nodeIndices.sort(function(x, y) { return x - y; });
+    indices = indices.concat(nodeIndices);
+  });
+
+  var firstIndex = 1;
+  while (firstIndex < layer2.length) firstIndex <<= 1;
+
+  var treeSize = 2 * firstIndex - 1;
+  firstIndex -= 1;
+
+  var tree = [];
+  for (var i = 0; i < treeSize; ++i) { tree[i] = 0; }
+
+  var cc = 0;
+  indices.forEach(function(i) {
+    var treeIndex = i + firstIndex;
+    ++tree[treeIndex];
+    while (treeIndex > 0) {
+      if (treeIndex % 2) {
+        cc += tree[treeIndex + 1];
+      }
+      treeIndex = (treeIndex - 1) >> 1;
+      ++tree[treeIndex];
+    }
+  });
+
+  return cc;
+}
+
+},{"../util":17}],6:[function(require,module,exports){
+var nodesFromList = require('graphlib').filter.nodesFromList,
+    /* jshint -W079 */
+    Set = require('cp-data').Set;
+
+module.exports = initLayerGraphs;
+
+/*
+ * This function takes a compound layered graph, g, and produces an array of
+ * layer graphs. Each entry in the array represents a subgraph of nodes
+ * relevant for performing crossing reduction on that layer.
+ */
+function initLayerGraphs(g) {
+  var ranks = [];
+
+  function dfs(u) {
+    if (u === null) {
+      g.children(u).forEach(function(v) { dfs(v); });
+      return;
+    }
+
+    var value = g.node(u);
+    value.minRank = ('rank' in value) ? value.rank : Number.MAX_VALUE;
+    value.maxRank = ('rank' in value) ? value.rank : Number.MIN_VALUE;
+    var uRanks = new Set();
+    g.children(u).forEach(function(v) {
+      var rs = dfs(v);
+      uRanks = Set.union([uRanks, rs]);
+      value.minRank = Math.min(value.minRank, g.node(v).minRank);
+      value.maxRank = Math.max(value.maxRank, g.node(v).maxRank);
+    });
+
+    if ('rank' in value) uRanks.add(value.rank);
+
+    uRanks.keys().forEach(function(r) {
+      if (!(r in ranks)) ranks[r] = [];
+      ranks[r].push(u);
+    });
+
+    return uRanks;
+  }
+  dfs(null);
+
+  var layerGraphs = [];
+  ranks.forEach(function(us, rank) {
+    layerGraphs[rank] = g.filterNodes(nodesFromList(us));
+  });
+
+  return layerGraphs;
+}
+
+},{"cp-data":19,"graphlib":24}],7:[function(require,module,exports){
+var crossCount = require('./crossCount'),
+    util = require('../util');
+
+module.exports = initOrder;
+
+/*
+ * Given a graph with a set of layered nodes (i.e. nodes that have a `rank`
+ * attribute) this function attaches an `order` attribute that uniquely
+ * arranges each node of each rank. If no constraint graph is provided the
+ * order of the nodes in each rank is entirely arbitrary.
+ */
+function initOrder(g, random) {
+  var layers = [];
+
+  g.eachNode(function(u, value) {
+    var layer = layers[value.rank];
+    if (g.children && g.children(u).length > 0) return;
+    if (!layer) {
+      layer = layers[value.rank] = [];
+    }
+    layer.push(u);
+  });
+
+  layers.forEach(function(layer) {
+    if (random) {
+      util.shuffle(layer);
+    }
+    layer.forEach(function(u, i) {
+      g.node(u).order = i;
+    });
+  });
+
+  var cc = crossCount(g);
+  g.graph().orderInitCC = cc;
+  g.graph().orderCC = Number.MAX_VALUE;
+}
+
+},{"../util":17,"./crossCount":5}],8:[function(require,module,exports){
+var util = require('../util');
+/*
+    Digraph = require('graphlib').Digraph,
+    topsort = require('graphlib').alg.topsort,
+    nodesFromList = require('graphlib').filter.nodesFromList;
+*/
+
+module.exports = sortLayer;
+
+/*
+function sortLayer(g, cg, weights) {
+  var result = sortLayerSubgraph(g, null, cg, weights);
+  result.list.forEach(function(u, i) {
+    g.node(u).order = i;
+  });
+  return result.constraintGraph;
+}
+*/
+
+function sortLayer(g, cg, weights) {
+  var ordering = [];
+  var bs = {};
+  g.eachNode(function(u, value) {
+    ordering[value.order] = u;
+    var ws = weights[u];
+    if (ws.length) {
+      bs[u] = util.sum(ws) / ws.length;
+    }
+  });
+
+  var toSort = g.nodes().filter(function(u) { return bs[u] !== undefined; });
+  toSort.sort(function(x, y) {
+    return bs[x] - bs[y] || g.node(x).order - g.node(y).order;
+  });
+
+  for (var i = 0, j = 0, jl = toSort.length; j < jl; ++i) {
+    if (bs[ordering[i]] !== undefined) {
+      g.node(toSort[j++]).order = i;
+    }
+  }
+}
+
+// TOOD: re-enable constrained sorting once we have a strategy for handling
+// undefined barycenters.
+/*
+function sortLayerSubgraph(g, sg, cg, weights) {
+  cg = cg ? cg.filterNodes(nodesFromList(g.children(sg))) : new Digraph();
+
+  var nodeData = {};
+  g.children(sg).forEach(function(u) {
+    if (g.children(u).length) {
+      nodeData[u] = sortLayerSubgraph(g, u, cg, weights);
+      nodeData[u].firstSG = u;
+      nodeData[u].lastSG = u;
+    } else {
+      var ws = weights[u];
+      nodeData[u] = {
+        degree: ws.length,
+        barycenter: ws.length > 0 ? util.sum(ws) / ws.length : 0,
+        list: [u]
+      };
+    }
+  });
+
+  resolveViolatedConstraints(g, cg, nodeData);
+
+  var keys = Object.keys(nodeData);
+  keys.sort(function(x, y) {
+    return nodeData[x].barycenter - nodeData[y].barycenter;
+  });
+
+  var result =  keys.map(function(u) { return nodeData[u]; })
+                    .reduce(function(lhs, rhs) { return mergeNodeData(g, lhs, rhs); });
+  return result;
+}
+
+/*
+function mergeNodeData(g, lhs, rhs) {
+  var cg = mergeDigraphs(lhs.constraintGraph, rhs.constraintGraph);
+
+  if (lhs.lastSG !== undefined && rhs.firstSG !== undefined) {
+    if (cg === undefined) {
+      cg = new Digraph();
+    }
+    if (!cg.hasNode(lhs.lastSG)) { cg.addNode(lhs.lastSG); }
+    cg.addNode(rhs.firstSG);
+    cg.addEdge(null, lhs.lastSG, rhs.firstSG);
+  }
+
+  return {
+    degree: lhs.degree + rhs.degree,
+    barycenter: (lhs.barycenter * lhs.degree + rhs.barycenter * rhs.degree) /
+                (lhs.degree + rhs.degree),
+    list: lhs.list.concat(rhs.list),
+    firstSG: lhs.firstSG !== undefined ? lhs.firstSG : rhs.firstSG,
+    lastSG: rhs.lastSG !== undefined ? rhs.lastSG : lhs.lastSG,
+    constraintGraph: cg
+  };
+}
+
+function mergeDigraphs(lhs, rhs) {
+  if (lhs === undefined) return rhs;
+  if (rhs === undefined) return lhs;
+
+  lhs = lhs.copy();
+  rhs.nodes().forEach(function(u) { lhs.addNode(u); });
+  rhs.edges().forEach(function(e, u, v) { lhs.addEdge(null, u, v); });
+  return lhs;
+}
+
+function resolveViolatedConstraints(g, cg, nodeData) {
+  // Removes nodes `u` and `v` from `cg` and makes any edges incident on them
+  // incident on `w` instead.
+  function collapseNodes(u, v, w) {
+    // TODO original paper removes self loops, but it is not obvious when this would happen
+    cg.inEdges(u).forEach(function(e) {
+      cg.delEdge(e);
+      cg.addEdge(null, cg.source(e), w);
+    });
+
+    cg.outEdges(v).forEach(function(e) {
+      cg.delEdge(e);
+      cg.addEdge(null, w, cg.target(e));
+    });
+
+    cg.delNode(u);
+    cg.delNode(v);
+  }
+
+  var violated;
+  while ((violated = findViolatedConstraint(cg, nodeData)) !== undefined) {
+    var source = cg.source(violated),
+        target = cg.target(violated);
+
+    var v;
+    while ((v = cg.addNode(null)) && g.hasNode(v)) {
+      cg.delNode(v);
+    }
+
+    // Collapse barycenter and list
+    nodeData[v] = mergeNodeData(g, nodeData[source], nodeData[target]);
+    delete nodeData[source];
+    delete nodeData[target];
+
+    collapseNodes(source, target, v);
+    if (cg.incidentEdges(v).length === 0) { cg.delNode(v); }
+  }
+}
+
+function findViolatedConstraint(cg, nodeData) {
+  var us = topsort(cg);
+  for (var i = 0; i < us.length; ++i) {
+    var u = us[i];
+    var inEdges = cg.inEdges(u);
+    for (var j = 0; j < inEdges.length; ++j) {
+      var e = inEdges[j];
+      if (nodeData[cg.source(e)].barycenter >= nodeData[u].barycenter) {
+        return e;
+      }
+    }
+  }
+}
+*/
+
+},{"../util":17}],9:[function(require,module,exports){
+var util = require('./util');
+
+/*
+ * The algorithms here are based on Brandes and Köpf, "Fast and Simple
+ * Horizontal Coordinate Assignment".
+ */
+module.exports = function() {
+  // External configuration
+  var config = {
+    nodeSep: 50,
+    edgeSep: 10,
+    universalSep: null,
+    rankSep: 30
+  };
+
+  var self = {};
+
+  self.nodeSep = util.propertyAccessor(self, config, 'nodeSep');
+  self.edgeSep = util.propertyAccessor(self, config, 'edgeSep');
+  // If not null this separation value is used for all nodes and edges
+  // regardless of their widths. `nodeSep` and `edgeSep` are ignored with this
+  // option.
+  self.universalSep = util.propertyAccessor(self, config, 'universalSep');
+  self.rankSep = util.propertyAccessor(self, config, 'rankSep');
+  self.debugLevel = util.propertyAccessor(self, config, 'debugLevel');
+
+  self.run = run;
+
+  return self;
+
+  function run(g) {
+    g = g.filterNodes(util.filterNonSubgraphs(g));
+
+    var layering = util.ordering(g);
+
+    var conflicts = findConflicts(g, layering);
+
+    var xss = {};
+    ['u', 'd'].forEach(function(vertDir) {
+      if (vertDir === 'd') layering.reverse();
+
+      ['l', 'r'].forEach(function(horizDir) {
+        if (horizDir === 'r') reverseInnerOrder(layering);
+
+        var dir = vertDir + horizDir;
+        var align = verticalAlignment(g, layering, conflicts, vertDir === 'u' ? 'predecessors' : 'successors');
+        xss[dir]= horizontalCompaction(g, layering, align.pos, align.root, align.align);
+
+        if (config.debugLevel >= 3)
+          debugPositioning(vertDir + horizDir, g, layering, xss[dir]);
+
+        if (horizDir === 'r') flipHorizontally(xss[dir]);
+
+        if (horizDir === 'r') reverseInnerOrder(layering);
+      });
+
+      if (vertDir === 'd') layering.reverse();
+    });
+
+    balance(g, layering, xss);
+
+    g.eachNode(function(v) {
+      var xs = [];
+      for (var alignment in xss) {
+        var alignmentX = xss[alignment][v];
+        posXDebug(alignment, g, v, alignmentX);
+        xs.push(alignmentX);
+      }
+      xs.sort(function(x, y) { return x - y; });
+      posX(g, v, (xs[1] + xs[2]) / 2);
+    });
+
+    // Align y coordinates with ranks
+    var y = 0, reverseY = g.graph().rankDir === 'BT' || g.graph().rankDir === 'RL';
+    layering.forEach(function(layer) {
+      var maxHeight = util.max(layer.map(function(u) { return height(g, u); }));
+      y += maxHeight / 2;
+      layer.forEach(function(u) {
+        posY(g, u, reverseY ? -y : y);
+      });
+      y += maxHeight / 2 + config.rankSep;
+    });
+
+    // Translate layout so that top left corner of bounding rectangle has
+    // coordinate (0, 0).
+    var minX = util.min(g.nodes().map(function(u) { return posX(g, u) - width(g, u) / 2; }));
+    var minY = util.min(g.nodes().map(function(u) { return posY(g, u) - height(g, u) / 2; }));
+    g.eachNode(function(u) {
+      posX(g, u, posX(g, u) - minX);
+      posY(g, u, posY(g, u) - minY);
+    });
+  }
+
+  /*
+   * Generate an ID that can be used to represent any undirected edge that is
+   * incident on `u` and `v`.
+   */
+  function undirEdgeId(u, v) {
+    return u < v
+      ? u.toString().length + ':' + u + '-' + v
+      : v.toString().length + ':' + v + '-' + u;
+  }
+
+  function findConflicts(g, layering) {
+    var conflicts = {}, // Set of conflicting edge ids
+        pos = {},       // Position of node in its layer
+        prevLayer,
+        currLayer,
+        k0,     // Position of the last inner segment in the previous layer
+        l,      // Current position in the current layer (for iteration up to `l1`)
+        k1;     // Position of the next inner segment in the previous layer or
+                // the position of the last element in the previous layer
+
+    if (layering.length <= 2) return conflicts;
+
+    function updateConflicts(v) {
+      var k = pos[v];
+      if (k < k0 || k > k1) {
+        conflicts[undirEdgeId(currLayer[l], v)] = true;
+      }
+    }
+
+    layering[1].forEach(function(u, i) { pos[u] = i; });
+    for (var i = 1; i < layering.length - 1; ++i) {
+      prevLayer = layering[i];
+      currLayer = layering[i+1];
+      k0 = 0;
+      l = 0;
+
+      // Scan current layer for next node that is incident to an inner segement
+      // between layering[i+1] and layering[i].
+      for (var l1 = 0; l1 < currLayer.length; ++l1) {
+        var u = currLayer[l1]; // Next inner segment in the current layer or
+                               // last node in the current layer
+        pos[u] = l1;
+        k1 = undefined;
+
+        if (g.node(u).dummy) {
+          var uPred = g.predecessors(u)[0];
+          // Note: In the case of self loops and sideways edges it is possible
+          // for a dummy not to have a predecessor.
+          if (uPred !== undefined && g.node(uPred).dummy)
+            k1 = pos[uPred];
+        }
+        if (k1 === undefined && l1 === currLayer.length - 1)
+          k1 = prevLayer.length - 1;
+
+        if (k1 !== undefined) {
+          for (; l <= l1; ++l) {
+            g.predecessors(currLayer[l]).forEach(updateConflicts);
+          }
+          k0 = k1;
+        }
+      }
+    }
+
+    return conflicts;
+  }
+
+  function verticalAlignment(g, layering, conflicts, relationship) {
+    var pos = {},   // Position for a node in its layer
+        root = {},  // Root of the block that the node participates in
+        align = {}; // Points to the next node in the block or, if the last
+                    // element in the block, points to the first block's root
+
+    layering.forEach(function(layer) {
+      layer.forEach(function(u, i) {
+        root[u] = u;
+        align[u] = u;
+        pos[u] = i;
+      });
+    });
+
+    layering.forEach(function(layer) {
+      var prevIdx = -1;
+      layer.forEach(function(v) {
+        var related = g[relationship](v), // Adjacent nodes from the previous layer
+            mid;                          // The mid point in the related array
+
+        if (related.length > 0) {
+          related.sort(function(x, y) { return pos[x] - pos[y]; });
+          mid = (related.length - 1) / 2;
+          related.slice(Math.floor(mid), Math.ceil(mid) + 1).forEach(function(u) {
+            if (align[v] === v) {
+              if (!conflicts[undirEdgeId(u, v)] && prevIdx < pos[u]) {
+                align[u] = v;
+                align[v] = root[v] = root[u];
+                prevIdx = pos[u];
+              }
+            }
+          });
+        }
+      });
+    });
+
+    return { pos: pos, root: root, align: align };
+  }
+
+  // This function deviates from the standard BK algorithm in two ways. First
+  // it takes into account the size of the nodes. Second it includes a fix to
+  // the original algorithm that is described in Carstens, "Node and Label
+  // Placement in a Layered Layout Algorithm".
+  function horizontalCompaction(g, layering, pos, root, align) {
+    var sink = {},       // Mapping of node id -> sink node id for class
+        maybeShift = {}, // Mapping of sink node id -> { class node id, min shift }
+        shift = {},      // Mapping of sink node id -> shift
+        pred = {},       // Mapping of node id -> predecessor node (or null)
+        xs = {};         // Calculated X positions
+
+    layering.forEach(function(layer) {
+      layer.forEach(function(u, i) {
+        sink[u] = u;
+        maybeShift[u] = {};
+        if (i > 0)
+          pred[u] = layer[i - 1];
+      });
+    });
+
+    function updateShift(toShift, neighbor, delta) {
+      if (!(neighbor in maybeShift[toShift])) {
+        maybeShift[toShift][neighbor] = delta;
+      } else {
+        maybeShift[toShift][neighbor] = Math.min(maybeShift[toShift][neighbor], delta);
+      }
+    }
+
+    function placeBlock(v) {
+      if (!(v in xs)) {
+        xs[v] = 0;
+        var w = v;
+        do {
+          if (pos[w] > 0) {
+            var u = root[pred[w]];
+            placeBlock(u);
+            if (sink[v] === v) {
+              sink[v] = sink[u];
+            }
+            var delta = sep(g, pred[w]) + sep(g, w);
+            if (sink[v] !== sink[u]) {
+              updateShift(sink[u], sink[v], xs[v] - xs[u] - delta);
+            } else {
+              xs[v] = Math.max(xs[v], xs[u] + delta);
+            }
+          }
+          w = align[w];
+        } while (w !== v);
+      }
+    }
+
+    // Root coordinates relative to sink
+    util.values(root).forEach(function(v) {
+      placeBlock(v);
+    });
+
+    // Absolute coordinates
+    // There is an assumption here that we've resolved shifts for any classes
+    // that begin at an earlier layer. We guarantee this by visiting layers in
+    // order.
+    layering.forEach(function(layer) {
+      layer.forEach(function(v) {
+        xs[v] = xs[root[v]];
+        if (v === root[v] && v === sink[v]) {
+          var minShift = 0;
+          if (v in maybeShift && Object.keys(maybeShift[v]).length > 0) {
+            minShift = util.min(Object.keys(maybeShift[v])
+                                 .map(function(u) {
+                                      return maybeShift[v][u] + (u in shift ? shift[u] : 0);
+                                      }
+                                 ));
+          }
+          shift[v] = minShift;
+        }
+      });
+    });
+
+    layering.forEach(function(layer) {
+      layer.forEach(function(v) {
+        xs[v] += shift[sink[root[v]]] || 0;
+      });
+    });
+
+    return xs;
+  }
+
+  function findMinCoord(g, layering, xs) {
+    return util.min(layering.map(function(layer) {
+      var u = layer[0];
+      return xs[u];
+    }));
+  }
+
+  function findMaxCoord(g, layering, xs) {
+    return util.max(layering.map(function(layer) {
+      var u = layer[layer.length - 1];
+      return xs[u];
+    }));
+  }
+
+  function balance(g, layering, xss) {
+    var min = {},                            // Min coordinate for the alignment
+        max = {},                            // Max coordinate for the alginment
+        smallestAlignment,
+        shift = {};                          // Amount to shift a given alignment
+
+    function updateAlignment(v) {
+      xss[alignment][v] += shift[alignment];
+    }
+
+    var smallest = Number.POSITIVE_INFINITY;
+    for (var alignment in xss) {
+      var xs = xss[alignment];
+      min[alignment] = findMinCoord(g, layering, xs);
+      max[alignment] = findMaxCoord(g, layering, xs);
+      var w = max[alignment] - min[alignment];
+      if (w < smallest) {
+        smallest = w;
+        smallestAlignment = alignment;
+      }
+    }
+
+    // Determine how much to adjust positioning for each alignment
+    ['u', 'd'].forEach(function(vertDir) {
+      ['l', 'r'].forEach(function(horizDir) {
+        var alignment = vertDir + horizDir;
+        shift[alignment] = horizDir === 'l'
+            ? min[smallestAlignment] - min[alignment]
+            : max[smallestAlignment] - max[alignment];
+      });
+    });
+
+    // Find average of medians for xss array
+    for (alignment in xss) {
+      g.eachNode(updateAlignment);
+    }
+  }
+
+  function flipHorizontally(xs) {
+    for (var u in xs) {
+      xs[u] = -xs[u];
+    }
+  }
+
+  function reverseInnerOrder(layering) {
+    layering.forEach(function(layer) {
+      layer.reverse();
+    });
+  }
+
+  function width(g, u) {
+    switch (g.graph().rankDir) {
+      case 'LR': return g.node(u).height;
+      case 'RL': return g.node(u).height;
+      default:   return g.node(u).width;
+    }
+  }
+
+  function height(g, u) {
+    switch(g.graph().rankDir) {
+      case 'LR': return g.node(u).width;
+      case 'RL': return g.node(u).width;
+      default:   return g.node(u).height;
+    }
+  }
+
+  function sep(g, u) {
+    if (config.universalSep !== null) {
+      return config.universalSep;
+    }
+    var w = width(g, u);
+    var s = g.node(u).dummy ? config.edgeSep : config.nodeSep;
+    return (w + s) / 2;
+  }
+
+  function posX(g, u, x) {
+    if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') {
+      if (arguments.length < 3) {
+        return g.node(u).y;
+      } else {
+        g.node(u).y = x;
+      }
+    } else {
+      if (arguments.length < 3) {
+        return g.node(u).x;
+      } else {
+        g.node(u).x = x;
+      }
+    }
+  }
+
+  function posXDebug(name, g, u, x) {
+    if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') {
+      if (arguments.length < 3) {
+        return g.node(u)[name];
+      } else {
+        g.node(u)[name] = x;
+      }
+    } else {
+      if (arguments.length < 3) {
+        return g.node(u)[name];
+      } else {
+        g.node(u)[name] = x;
+      }
+    }
+  }
+
+  function posY(g, u, y) {
+    if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') {
+      if (arguments.length < 3) {
+        return g.node(u).x;
+      } else {
+        g.node(u).x = y;
+      }
+    } else {
+      if (arguments.length < 3) {
+        return g.node(u).y;
+      } else {
+        g.node(u).y = y;
+      }
+    }
+  }
+
+  function debugPositioning(align, g, layering, xs) {
+    layering.forEach(function(l, li) {
+      var u, xU;
+      l.forEach(function(v) {
+        var xV = xs[v];
+        if (u) {
+          var s = sep(g, u) + sep(g, v);
+          if (xV - xU < s)
+            console.log('Position phase: sep violation. Align: ' + align + '. Layer: ' + li + '. ' +
+              'U: ' + u + ' V: ' + v + '. Actual sep: ' + (xV - xU) + ' Expected sep: ' + s);
+        }
+        u = v;
+        xU = xV;
+      });
+    });
+  }
+};
+
+},{"./util":17}],10:[function(require,module,exports){
+var util = require('./util'),
+    acyclic = require('./rank/acyclic'),
+    initRank = require('./rank/initRank'),
+    feasibleTree = require('./rank/feasibleTree'),
+    constraints = require('./rank/constraints'),
+    simplex = require('./rank/simplex'),
+    components = require('graphlib').alg.components,
+    filter = require('graphlib').filter;
+
+exports.run = run;
+exports.restoreEdges = restoreEdges;
+
+/*
+ * Heuristic function that assigns a rank to each node of the input graph with
+ * the intent of minimizing edge lengths, while respecting the `minLen`
+ * attribute of incident edges.
+ *
+ * Prerequisites:
+ *
+ *  * Each edge in the input graph must have an assigned 'minLen' attribute
+ */
+function run(g, useSimplex) {
+  expandSelfLoops(g);
+
+  // If there are rank constraints on nodes, then build a new graph that
+  // encodes the constraints.
+  util.time('constraints.apply', constraints.apply)(g);
+
+  expandSidewaysEdges(g);
+
+  // Reverse edges to get an acyclic graph, we keep the graph in an acyclic
+  // state until the very end.
+  util.time('acyclic', acyclic)(g);
+
+  // Convert the graph into a flat graph for ranking
+  var flatGraph = g.filterNodes(util.filterNonSubgraphs(g));
+
+  // Assign an initial ranking using DFS.
+  initRank(flatGraph);
+
+  // For each component improve the assigned ranks.
+  components(flatGraph).forEach(function(cmpt) {
+    var subgraph = flatGraph.filterNodes(filter.nodesFromList(cmpt));
+    rankComponent(subgraph, useSimplex);
+  });
+
+  // Relax original constraints
+  util.time('constraints.relax', constraints.relax(g));
+
+  // When handling nodes with constrained ranks it is possible to end up with
+  // edges that point to previous ranks. Most of the subsequent algorithms assume
+  // that edges are pointing to successive ranks only. Here we reverse any "back
+  // edges" and mark them as such. The acyclic algorithm will reverse them as a
+  // post processing step.
+  util.time('reorientEdges', reorientEdges)(g);
+}
+
+function restoreEdges(g) {
+  acyclic.undo(g);
+}
+
+/*
+ * Expand self loops into three dummy nodes. One will sit above the incident
+ * node, one will be at the same level, and one below. The result looks like:
+ *
+ *         /--<--x--->--\
+ *     node              y
+ *         \--<--z--->--/
+ *
+ * Dummy nodes x, y, z give us the shape of a loop and node y is where we place
+ * the label.
+ *
+ * TODO: consolidate knowledge of dummy node construction.
+ * TODO: support minLen = 2
+ */
+function expandSelfLoops(g) {
+  g.eachEdge(function(e, u, v, a) {
+    if (u === v) {
+      var x = addDummyNode(g, e, u, v, a, 0, false),
+          y = addDummyNode(g, e, u, v, a, 1, true),
+          z = addDummyNode(g, e, u, v, a, 2, false);
+      g.addEdge(null, x, u, {minLen: 1, selfLoop: true});
+      g.addEdge(null, x, y, {minLen: 1, selfLoop: true});
+      g.addEdge(null, u, z, {minLen: 1, selfLoop: true});
+      g.addEdge(null, y, z, {minLen: 1, selfLoop: true});
+      g.delEdge(e);
+    }
+  });
+}
+
+function expandSidewaysEdges(g) {
+  g.eachEdge(function(e, u, v, a) {
+    if (u === v) {
+      var origEdge = a.originalEdge,
+          dummy = addDummyNode(g, origEdge.e, origEdge.u, origEdge.v, origEdge.value, 0, true);
+      g.addEdge(null, u, dummy, {minLen: 1});
+      g.addEdge(null, dummy, v, {minLen: 1});
+      g.delEdge(e);
+    }
+  });
+}
+
+function addDummyNode(g, e, u, v, a, index, isLabel) {
+  return g.addNode(null, {
+    width: isLabel ? a.width : 0,
+    height: isLabel ? a.height : 0,
+    edge: { id: e, source: u, target: v, attrs: a },
+    dummy: true,
+    index: index
+  });
+}
+
+function reorientEdges(g) {
+  g.eachEdge(function(e, u, v, value) {
+    if (g.node(u).rank > g.node(v).rank) {
+      g.delEdge(e);
+      value.reversed = true;
+      g.addEdge(e, v, u, value);
+    }
+  });
+}
+
+function rankComponent(subgraph, useSimplex) {
+  var spanningTree = feasibleTree(subgraph);
+
+  if (useSimplex) {
+    util.log(1, 'Using network simplex for ranking');
+    simplex(subgraph, spanningTree);
+  }
+  normalize(subgraph);
+}
+
+function normalize(g) {
+  var m = util.min(g.nodes().map(function(u) { return g.node(u).rank; }));
+  g.eachNode(function(u, node) { node.rank -= m; });
+}
+
+},{"./rank/acyclic":11,"./rank/constraints":12,"./rank/feasibleTree":13,"./rank/initRank":14,"./rank/simplex":16,"./util":17,"graphlib":24}],11:[function(require,module,exports){
+var util = require('../util');
+
+module.exports = acyclic;
+module.exports.undo = undo;
+
+/*
+ * This function takes a directed graph that may have cycles and reverses edges
+ * as appropriate to break these cycles. Each reversed edge is assigned a
+ * `reversed` attribute with the value `true`.
+ *
+ * There should be no self loops in the graph.
+ */
+function acyclic(g) {
+  var onStack = {},
+      visited = {},
+      reverseCount = 0;
+  
+  function dfs(u) {
+    if (u in visited) return;
+    visited[u] = onStack[u] = true;
+    g.outEdges(u).forEach(function(e) {
+      var t = g.target(e),
+          value;
+
+      if (u === t) {
+        console.error('Warning: found self loop "' + e + '" for node "' + u + '"');
+      } else if (t in onStack) {
+        value = g.edge(e);
+        g.delEdge(e);
+        value.reversed = true;
+        ++reverseCount;
+        g.addEdge(e, t, u, value);
+      } else {
+        dfs(t);
+      }
+    });
+
+    delete onStack[u];
+  }
+
+  g.eachNode(function(u) { dfs(u); });
+
+  util.log(2, 'Acyclic Phase: reversed ' + reverseCount + ' edge(s)');
+
+  return reverseCount;
+}
+
+/*
+ * Given a graph that has had the acyclic operation applied, this function
+ * undoes that operation. More specifically, any edge with the `reversed`
+ * attribute is again reversed to restore the original direction of the edge.
+ */
+function undo(g) {
+  g.eachEdge(function(e, s, t, a) {
+    if (a.reversed) {
+      delete a.reversed;
+      g.delEdge(e);
+      g.addEdge(e, t, s, a);
+    }
+  });
+}
+
+},{"../util":17}],12:[function(require,module,exports){
+exports.apply = function(g) {
+  function dfs(sg) {
+    var rankSets = {};
+    g.children(sg).forEach(function(u) {
+      if (g.children(u).length) {
+        dfs(u);
+        return;
+      }
+
+      var value = g.node(u),
+          prefRank = value.prefRank;
+      if (prefRank !== undefined) {
+        if (!checkSupportedPrefRank(prefRank)) { return; }
+
+        if (!(prefRank in rankSets)) {
+          rankSets.prefRank = [u];
+        } else {
+          rankSets.prefRank.push(u);
+        }
+
+        var newU = rankSets[prefRank];
+        if (newU === undefined) {
+          newU = rankSets[prefRank] = g.addNode(null, { originalNodes: [] });
+          g.parent(newU, sg);
+        }
+
+        redirectInEdges(g, u, newU, prefRank === 'min');
+        redirectOutEdges(g, u, newU, prefRank === 'max');
+
+        // Save original node and remove it from reduced graph
+        g.node(newU).originalNodes.push({ u: u, value: value, parent: sg });
+        g.delNode(u);
+      }
+    });
+
+    addLightEdgesFromMinNode(g, sg, rankSets.min);
+    addLightEdgesToMaxNode(g, sg, rankSets.max);
+  }
+
+  dfs(null);
+};
+
+function checkSupportedPrefRank(prefRank) {
+  if (prefRank !== 'min' && prefRank !== 'max' && prefRank.indexOf('same_') !== 0) {
+    console.error('Unsupported rank type: ' + prefRank);
+    return false;
+  }
+  return true;
+}
+
+function redirectInEdges(g, u, newU, reverse) {
+  g.inEdges(u).forEach(function(e) {
+    var origValue = g.edge(e),
+        value;
+    if (origValue.originalEdge) {
+      value = origValue;
+    } else {
+      value =  {
+        originalEdge: { e: e, u: g.source(e), v: g.target(e), value: origValue },
+        minLen: g.edge(e).minLen
+      };
+    }
+
+    // Do not reverse edges for self-loops.
+    if (origValue.selfLoop) {
+      reverse = false;
+    }
+
+    if (reverse) {
+      // Ensure that all edges to min are reversed
+      g.addEdge(null, newU, g.source(e), value);
+      value.reversed = true;
+    } else {
+      g.addEdge(null, g.source(e), newU, value);
+    }
+  });
+}
+
+function redirectOutEdges(g, u, newU, reverse) {
+  g.outEdges(u).forEach(function(e) {
+    var origValue = g.edge(e),
+        value;
+    if (origValue.originalEdge) {
+      value = origValue;
+    } else {
+      value =  {
+        originalEdge: { e: e, u: g.source(e), v: g.target(e), value: origValue },
+        minLen: g.edge(e).minLen
+      };
+    }
+
+    // Do not reverse edges for self-loops.
+    if (origValue.selfLoop) {
+      reverse = false;
+    }
+
+    if (reverse) {
+      // Ensure that all edges from max are reversed
+      g.addEdge(null, g.target(e), newU, value);
+      value.reversed = true;
+    } else {
+      g.addEdge(null, newU, g.target(e), value);
+    }
+  });
+}
+
+function addLightEdgesFromMinNode(g, sg, minNode) {
+  if (minNode !== undefined) {
+    g.children(sg).forEach(function(u) {
+      // The dummy check ensures we don't add an edge if the node is involved
+      // in a self loop or sideways edge.
+      if (u !== minNode && !g.outEdges(minNode, u).length && !g.node(u).dummy) {
+        g.addEdge(null, minNode, u, { minLen: 0 });
+      }
+    });
+  }
+}
+
+function addLightEdgesToMaxNode(g, sg, maxNode) {
+  if (maxNode !== undefined) {
+    g.children(sg).forEach(function(u) {
+      // The dummy check ensures we don't add an edge if the node is involved
+      // in a self loop or sideways edge.
+      if (u !== maxNode && !g.outEdges(u, maxNode).length && !g.node(u).dummy) {
+        g.addEdge(null, u, maxNode, { minLen: 0 });
+      }
+    });
+  }
+}
+
+/*
+ * This function "relaxes" the constraints applied previously by the "apply"
+ * function. It expands any nodes that were collapsed and assigns the rank of
+ * the collapsed node to each of the expanded nodes. It also restores the
+ * original edges and removes any dummy edges pointing at the collapsed nodes.
+ *
+ * Note that the process of removing collapsed nodes also removes dummy edges
+ * automatically.
+ */
+exports.relax = function(g) {
+  // Save original edges
+  var originalEdges = [];
+  g.eachEdge(function(e, u, v, value) {
+    var originalEdge = value.originalEdge;
+    if (originalEdge) {
+      originalEdges.push(originalEdge);
+    }
+  });
+
+  // Expand collapsed nodes
+  g.eachNode(function(u, value) {
+    var originalNodes = value.originalNodes;
+    if (originalNodes) {
+      originalNodes.forEach(function(originalNode) {
+        originalNode.value.rank = value.rank;
+        g.addNode(originalNode.u, originalNode.value);
+        g.parent(originalNode.u, originalNode.parent);
+      });
+      g.delNode(u);
+    }
+  });
+
+  // Restore original edges
+  originalEdges.forEach(function(edge) {
+    g.addEdge(edge.e, edge.u, edge.v, edge.value);
+  });
+};
+
+},{}],13:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require('cp-data').Set,
+/* jshint +W079 */
+    Digraph = require('graphlib').Digraph,
+    util = require('../util');
+
+module.exports = feasibleTree;
+
+/*
+ * Given an acyclic graph with each node assigned a `rank` attribute, this
+ * function constructs and returns a spanning tree. This function may reduce
+ * the length of some edges from the initial rank assignment while maintaining
+ * the `minLen` specified by each edge.
+ *
+ * Prerequisites:
+ *
+ * * The input graph is acyclic
+ * * Each node in the input graph has an assigned `rank` attribute
+ * * Each edge in the input graph has an assigned `minLen` attribute
+ *
+ * Outputs:
+ *
+ * A feasible spanning tree for the input graph (i.e. a spanning tree that
+ * respects each graph edge's `minLen` attribute) represented as a Digraph with
+ * a `root` attribute on graph.
+ *
+ * Nodes have the same id and value as that in the input graph.
+ *
+ * Edges in the tree have arbitrarily assigned ids. The attributes for edges
+ * include `reversed`. `reversed` indicates that the edge is a
+ * back edge in the input graph.
+ */
+function feasibleTree(g) {
+  var remaining = new Set(g.nodes()),
+      tree = new Digraph();
+
+  if (remaining.size() === 1) {
+    var root = g.nodes()[0];
+    tree.addNode(root, {});
+    tree.graph({ root: root });
+    return tree;
+  }
+
+  function addTightEdges(v) {
+    var continueToScan = true;
+    g.predecessors(v).forEach(function(u) {
+      if (remaining.has(u) && !slack(g, u, v)) {
+        if (remaining.has(v)) {
+          tree.addNode(v, {});
+          remaining.remove(v);
+          tree.graph({ root: v });
+        }
+
+        tree.addNode(u, {});
+        tree.addEdge(null, u, v, { reversed: true });
+        remaining.remove(u);
+        addTightEdges(u);
+        continueToScan = false;
+      }
+    });
+
+    g.successors(v).forEach(function(w)  {
+      if (remaining.has(w) && !slack(g, v, w)) {
+        if (remaining.has(v)) {
+          tree.addNode(v, {});
+          remaining.remove(v);
+          tree.graph({ root: v });
+        }
+
+        tree.addNode(w, {});
+        tree.addEdge(null, v, w, {});
+        remaining.remove(w);
+        addTightEdges(w);
+        continueToScan = false;
+      }
+    });
+    return continueToScan;
+  }
+
+  function createTightEdge() {
+    var minSlack = Number.MAX_VALUE;
+    remaining.keys().forEach(function(v) {
+      g.predecessors(v).forEach(function(u) {
+        if (!remaining.has(u)) {
+          var edgeSlack = slack(g, u, v);
+          if (Math.abs(edgeSlack) < Math.abs(minSlack)) {
+            minSlack = -edgeSlack;
+          }
+        }
+      });
+
+      g.successors(v).forEach(function(w) {
+        if (!remaining.has(w)) {
+          var edgeSlack = slack(g, v, w);
+          if (Math.abs(edgeSlack) < Math.abs(minSlack)) {
+            minSlack = edgeSlack;
+          }
+        }
+      });
+    });
+
+    tree.eachNode(function(u) { g.node(u).rank -= minSlack; });
+  }
+
+  while (remaining.size()) {
+    var nodesToSearch = !tree.order() ? remaining.keys() : tree.nodes();
+    for (var i = 0, il = nodesToSearch.length;
+         i < il && addTightEdges(nodesToSearch[i]);
+         ++i);
+    if (remaining.size()) {
+      createTightEdge();
+    }
+  }
+
+  return tree;
+}
+
+function slack(g, u, v) {
+  var rankDiff = g.node(v).rank - g.node(u).rank;
+  var maxMinLen = util.max(g.outEdges(u, v)
+                            .map(function(e) { return g.edge(e).minLen; }));
+  return rankDiff - maxMinLen;
+}
+
+},{"../util":17,"cp-data":19,"graphlib":24}],14:[function(require,module,exports){
+var util = require('../util'),
+    topsort = require('graphlib').alg.topsort;
+
+module.exports = initRank;
+
+/*
+ * Assigns a `rank` attribute to each node in the input graph and ensures that
+ * this rank respects the `minLen` attribute of incident edges.
+ *
+ * Prerequisites:
+ *
+ *  * The input graph must be acyclic
+ *  * Each edge in the input graph must have an assigned 'minLen' attribute
+ */
+function initRank(g) {
+  var sorted = topsort(g);
+
+  sorted.forEach(function(u) {
+    var inEdges = g.inEdges(u);
+    if (inEdges.length === 0) {
+      g.node(u).rank = 0;
+      return;
+    }
+
+    var minLens = inEdges.map(function(e) {
+      return g.node(g.source(e)).rank + g.edge(e).minLen;
+    });
+    g.node(u).rank = util.max(minLens);
+  });
+}
+
+},{"../util":17,"graphlib":24}],15:[function(require,module,exports){
+module.exports = {
+  slack: slack
+};
+
+/*
+ * A helper to calculate the slack between two nodes (`u` and `v`) given a
+ * `minLen` constraint. The slack represents how much the distance between `u`
+ * and `v` could shrink while maintaining the `minLen` constraint. If the value
+ * is negative then the constraint is currently violated.
+ *
+  This function requires that `u` and `v` are in `graph` and they both have a
+  `rank` attribute.
+ */
+function slack(graph, u, v, minLen) {
+  return Math.abs(graph.node(u).rank - graph.node(v).rank) - minLen;
+}
+
+},{}],16:[function(require,module,exports){
+var util = require('../util'),
+    rankUtil = require('./rankUtil');
+
+module.exports = simplex;
+
+function simplex(graph, spanningTree) {
+  // The network simplex algorithm repeatedly replaces edges of
+  // the spanning tree with negative cut values until no such
+  // edge exists.
+  initCutValues(graph, spanningTree);
+  while (true) {
+    var e = leaveEdge(spanningTree);
+    if (e === null) break;
+    var f = enterEdge(graph, spanningTree, e);
+    exchange(graph, spanningTree, e, f);
+  }
+}
+
+/*
+ * Set the cut values of edges in the spanning tree by a depth-first
+ * postorder traversal.  The cut value corresponds to the cost, in
+ * terms of a ranking's edge length sum, of lengthening an edge.
+ * Negative cut values typically indicate edges that would yield a
+ * smaller edge length sum if they were lengthened.
+ */
+function initCutValues(graph, spanningTree) {
+  computeLowLim(spanningTree);
+
+  spanningTree.eachEdge(function(id, u, v, treeValue) {
+    treeValue.cutValue = 0;
+  });
+
+  // Propagate cut values up the tree.
+  function dfs(n) {
+    var children = spanningTree.successors(n);
+    for (var c in children) {
+      var child = children[c];
+      dfs(child);
+    }
+    if (n !== spanningTree.graph().root) {
+      setCutValue(graph, spanningTree, n);
+    }
+  }
+  dfs(spanningTree.graph().root);
+}
+
+/*
+ * Perform a DFS postorder traversal, labeling each node v with
+ * its traversal order 'lim(v)' and the minimum traversal number
+ * of any of its descendants 'low(v)'.  This provides an efficient
+ * way to test whether u is an ancestor of v since
+ * low(u) <= lim(v) <= lim(u) if and only if u is an ancestor.
+ */
+function computeLowLim(tree) {
+  var postOrderNum = 0;
+  
+  function dfs(n) {
+    var children = tree.successors(n);
+    var low = postOrderNum;
+    for (var c in children) {
+      var child = children[c];
+      dfs(child);
+      low = Math.min(low, tree.node(child).low);
+    }
+    tree.node(n).low = low;
+    tree.node(n).lim = postOrderNum++;
+  }
+
+  dfs(tree.graph().root);
+}
+
+/*
+ * To compute the cut value of the edge parent -> child, we consider
+ * it and any other graph edges to or from the child.
+ *          parent
+ *             |
+ *           child
+ *          /      \
+ *         u        v
+ */
+function setCutValue(graph, tree, child) {
+  var parentEdge = tree.inEdges(child)[0];
+
+  // List of child's children in the spanning tree.
+  var grandchildren = [];
+  var grandchildEdges = tree.outEdges(child);
+  for (var gce in grandchildEdges) {
+    grandchildren.push(tree.target(grandchildEdges[gce]));
+  }
+
+  var cutValue = 0;
+
+  // TODO: Replace unit increment/decrement with edge weights.
+  var E = 0;    // Edges from child to grandchild's subtree.
+  var F = 0;    // Edges to child from grandchild's subtree.
+  var G = 0;    // Edges from child to nodes outside of child's subtree.
+  var H = 0;    // Edges from nodes outside of child's subtree to child.
+
+  // Consider all graph edges from child.
+  var outEdges = graph.outEdges(child);
+  var gc;
+  for (var oe in outEdges) {
+    var succ = graph.target(outEdges[oe]);
+    for (gc in grandchildren) {
+      if (inSubtree(tree, succ, grandchildren[gc])) {
+        E++;
+      }
+    }
+    if (!inSubtree(tree, succ, child)) {
+      G++;
+    }
+  }
+
+  // Consider all graph edges to child.
+  var inEdges = graph.inEdges(child);
+  for (var ie in inEdges) {
+    var pred = graph.source(inEdges[ie]);
+    for (gc in grandchildren) {
+      if (inSubtree(tree, pred, grandchildren[gc])) {
+        F++;
+      }
+    }
+    if (!inSubtree(tree, pred, child)) {
+      H++;
+    }
+  }
+
+  // Contributions depend on the alignment of the parent -> child edge
+  // and the child -> u or v edges.
+  var grandchildCutSum = 0;
+  for (gc in grandchildren) {
+    var cv = tree.edge(grandchildEdges[gc]).cutValue;
+    if (!tree.edge(grandchildEdges[gc]).reversed) {
+      grandchildCutSum += cv;
+    } else {
+      grandchildCutSum -= cv;
+    }
+  }
+
+  if (!tree.edge(parentEdge).reversed) {
+    cutValue += grandchildCutSum - E + F - G + H;
+  } else {
+    cutValue -= grandchildCutSum - E + F - G + H;
+  }
+
+  tree.edge(parentEdge).cutValue = cutValue;
+}
+
+/*
+ * Return whether n is a node in the subtree with the given
+ * root.
+ */
+function inSubtree(tree, n, root) {
+  return (tree.node(root).low <= tree.node(n).lim &&
+          tree.node(n).lim <= tree.node(root).lim);
+}
+
+/*
+ * Return an edge from the tree with a negative cut value, or null if there
+ * is none.
+ */
+function leaveEdge(tree) {
+  var edges = tree.edges();
+  for (var n in edges) {
+    var e = edges[n];
+    var treeValue = tree.edge(e);
+    if (treeValue.cutValue < 0) {
+      return e;
+    }
+  }
+  return null;
+}
+
+/*
+ * The edge e should be an edge in the tree, with an underlying edge
+ * in the graph, with a negative cut value.  Of the two nodes incident
+ * on the edge, take the lower one.  enterEdge returns an edge with
+ * minimum slack going from outside of that node's subtree to inside
+ * of that node's subtree.
+ */
+function enterEdge(graph, tree, e) {
+  var source = tree.source(e);
+  var target = tree.target(e);
+  var lower = tree.node(target).lim < tree.node(source).lim ? target : source;
+
+  // Is the tree edge aligned with the graph edge?
+  var aligned = !tree.edge(e).reversed;
+
+  var minSlack = Number.POSITIVE_INFINITY;
+  var minSlackEdge;
+  if (aligned) {
+    graph.eachEdge(function(id, u, v, value) {
+      if (id !== e && inSubtree(tree, u, lower) && !inSubtree(tree, v, lower)) {
+        var slack = rankUtil.slack(graph, u, v, value.minLen);
+        if (slack < minSlack) {
+          minSlack = slack;
+          minSlackEdge = id;
+        }
+      }
+    });
+  } else {
+    graph.eachEdge(function(id, u, v, value) {
+      if (id !== e && !inSubtree(tree, u, lower) && inSubtree(tree, v, lower)) {
+        var slack = rankUtil.slack(graph, u, v, value.minLen);
+        if (slack < minSlack) {
+          minSlack = slack;
+          minSlackEdge = id;
+        }
+      }
+    });
+  }
+
+  if (minSlackEdge === undefined) {
+    var outside = [];
+    var inside = [];
+    graph.eachNode(function(id) {
+      if (!inSubtree(tree, id, lower)) {
+        outside.push(id);
+      } else {
+        inside.push(id);
+      }
+    });
+    throw new Error('No edge found from outside of tree to inside');
+  }
+
+  return minSlackEdge;
+}
+
+/*
+ * Replace edge e with edge f in the tree, recalculating the tree root,
+ * the nodes' low and lim properties and the edges' cut values.
+ */
+function exchange(graph, tree, e, f) {
+  tree.delEdge(e);
+  var source = graph.source(f);
+  var target = graph.target(f);
+
+  // Redirect edges so that target is the root of its subtree.
+  function redirect(v) {
+    var edges = tree.inEdges(v);
+    for (var i in edges) {
+      var e = edges[i];
+      var u = tree.source(e);
+      var value = tree.edge(e);
+      redirect(u);
+      tree.delEdge(e);
+      value.reversed = !value.reversed;
+      tree.addEdge(e, v, u, value);
+    }
+  }
+
+  redirect(target);
+
+  var root = source;
+  var edges = tree.inEdges(root);
+  while (edges.length > 0) {
+    root = tree.source(edges[0]);
+    edges = tree.inEdges(root);
+  }
+
+  tree.graph().root = root;
+
+  tree.addEdge(null, source, target, {cutValue: 0});
+
+  initCutValues(graph, tree);
+
+  adjustRanks(graph, tree);
+}
+
+/*
+ * Reset the ranks of all nodes based on the current spanning tree.
+ * The rank of the tree's root remains unchanged, while all other
+ * nodes are set to the sum of minimum length constraints along
+ * the path from the root.
+ */
+function adjustRanks(graph, tree) {
+  function dfs(p) {
+    var children = tree.successors(p);
+    children.forEach(function(c) {
+      var minLen = minimumLength(graph, p, c);
+      graph.node(c).rank = graph.node(p).rank + minLen;
+      dfs(c);
+    });
+  }
+
+  dfs(tree.graph().root);
+}
+
+/*
+ * If u and v are connected by some edges in the graph, return the
+ * minimum length of those edges, as a positive number if v succeeds
+ * u and as a negative number if v precedes u.
+ */
+function minimumLength(graph, u, v) {
+  var outEdges = graph.outEdges(u, v);
+  if (outEdges.length > 0) {
+    return util.max(outEdges.map(function(e) {
+      return graph.edge(e).minLen;
+    }));
+  }
+
+  var inEdges = graph.inEdges(u, v);
+  if (inEdges.length > 0) {
+    return -util.max(inEdges.map(function(e) {
+      return graph.edge(e).minLen;
+    }));
+  }
+}
+
+},{"../util":17,"./rankUtil":15}],17:[function(require,module,exports){
+/*
+ * Returns the smallest value in the array.
+ */
+exports.min = function(values) {
+  return Math.min.apply(Math, values);
+};
+
+/*
+ * Returns the largest value in the array.
+ */
+exports.max = function(values) {
+  return Math.max.apply(Math, values);
+};
+
+/*
+ * Returns `true` only if `f(x)` is `true` for all `x` in `xs`. Otherwise
+ * returns `false`. This function will return immediately if it finds a
+ * case where `f(x)` does not hold.
+ */
+exports.all = function(xs, f) {
+  for (var i = 0; i < xs.length; ++i) {
+    if (!f(xs[i])) {
+      return false;
+    }
+  }
+  return true;
+};
+
+/*
+ * Accumulates the sum of elements in the given array using the `+` operator.
+ */
+exports.sum = function(values) {
+  return values.reduce(function(acc, x) { return acc + x; }, 0);
+};
+
+/*
+ * Returns an array of all values in the given object.
+ */
+exports.values = function(obj) {
+  return Object.keys(obj).map(function(k) { return obj[k]; });
+};
+
+exports.shuffle = function(array) {
+  for (i = array.length - 1; i > 0; --i) {
+    var j = Math.floor(Math.random() * (i + 1));
+    var aj = array[j];
+    array[j] = array[i];
+    array[i] = aj;
+  }
+};
+
+exports.propertyAccessor = function(self, config, field, setHook) {
+  return function(x) {
+    if (!arguments.length) return config[field];
+    config[field] = x;
+    if (setHook) setHook(x);
+    return self;
+  };
+};
+
+/*
+ * Given a layered, directed graph with `rank` and `order` node attributes,
+ * this function returns an array of ordered ranks. Each rank contains an array
+ * of the ids of the nodes in that rank in the order specified by the `order`
+ * attribute.
+ */
+exports.ordering = function(g) {
+  var ordering = [];
+  g.eachNode(function(u, value) {
+    var rank = ordering[value.rank] || (ordering[value.rank] = []);
+    rank[value.order] = u;
+  });
+  return ordering;
+};
+
+/*
+ * A filter that can be used with `filterNodes` to get a graph that only
+ * includes nodes that do not contain others nodes.
+ */
+exports.filterNonSubgraphs = function(g) {
+  return function(u) {
+    return g.children(u).length === 0;
+  };
+};
+
+/*
+ * Returns a new function that wraps `func` with a timer. The wrapper logs the
+ * time it takes to execute the function.
+ *
+ * The timer will be enabled provided `log.level >= 1`.
+ */
+function time(name, func) {
+  return function() {
+    var start = new Date().getTime();
+    try {
+      return func.apply(null, arguments);
+    } finally {
+      log(1, name + ' time: ' + (new Date().getTime() - start) + 'ms');
+    }
+  };
+}
+time.enabled = false;
+
+exports.time = time;
+
+/*
+ * A global logger with the specification `log(level, message, ...)` that
+ * will log a message to the console if `log.level >= level`.
+ */
+function log(level) {
+  if (log.level >= level) {
+    console.log.apply(console, Array.prototype.slice.call(arguments, 1));
+  }
+}
+log.level = 0;
+
+exports.log = log;
+
+},{}],18:[function(require,module,exports){
+module.exports = '0.4.5';
+
+},{}],19:[function(require,module,exports){
+exports.Set = require('./lib/Set');
+exports.PriorityQueue = require('./lib/PriorityQueue');
+exports.version = require('./lib/version');
+
+},{"./lib/PriorityQueue":20,"./lib/Set":21,"./lib/version":23}],20:[function(require,module,exports){
+module.exports = PriorityQueue;
+
+/**
+ * A min-priority queue data structure. This algorithm is derived from Cormen,
+ * et al., "Introduction to Algorithms". The basic idea of a min-priority
+ * queue is that you can efficiently (in O(1) time) get the smallest key in
+ * the queue. Adding and removing elements takes O(log n) time. A key can
+ * have its priority decreased in O(log n) time.
+ */
+function PriorityQueue() {
+  this._arr = [];
+  this._keyIndices = {};
+}
+
+/**
+ * Returns the number of elements in the queue. Takes `O(1)` time.
+ */
+PriorityQueue.prototype.size = function() {
+  return this._arr.length;
+};
+
+/**
+ * Returns the keys that are in the queue. Takes `O(n)` time.
+ */
+PriorityQueue.prototype.keys = function() {
+  return this._arr.map(function(x) { return x.key; });
+};
+
+/**
+ * Returns `true` if **key** is in the queue and `false` if not.
+ */
+PriorityQueue.prototype.has = function(key) {
+  return key in this._keyIndices;
+};
+
+/**
+ * Returns the priority for **key**. If **key** is not present in the queue
+ * then this function returns `undefined`. Takes `O(1)` time.
+ *
+ * @param {Object} key
+ */
+PriorityQueue.prototype.priority = function(key) {
+  var index = this._keyIndices[key];
+  if (index !== undefined) {
+    return this._arr[index].priority;
+  }
+};
+
+/**
+ * Returns the key for the minimum element in this queue. If the queue is
+ * empty this function throws an Error. Takes `O(1)` time.
+ */
+PriorityQueue.prototype.min = function() {
+  if (this.size() === 0) {
+    throw new Error("Queue underflow");
+  }
+  return this._arr[0].key;
+};
+
+/**
+ * Inserts a new key into the priority queue. If the key already exists in
+ * the queue this function returns `false`; otherwise it will return `true`.
+ * Takes `O(n)` time.
+ *
+ * @param {Object} key the key to add
+ * @param {Number} priority the initial priority for the key
+ */
+PriorityQueue.prototype.add = function(key, priority) {
+  var keyIndices = this._keyIndices;
+  if (!(key in keyIndices)) {
+    var arr = this._arr;
+    var index = arr.length;
+    keyIndices[key] = index;
+    arr.push({key: key, priority: priority});
+    this._decrease(index);
+    return true;
+  }
+  return false;
+};
+
+/**
+ * Removes and returns the smallest key in the queue. Takes `O(log n)` time.
+ */
+PriorityQueue.prototype.removeMin = function() {
+  this._swap(0, this._arr.length - 1);
+  var min = this._arr.pop();
+  delete this._keyIndices[min.key];
+  this._heapify(0);
+  return min.key;
+};
+
+/**
+ * Decreases the priority for **key** to **priority**. If the new priority is
+ * greater than the previous priority, this function will throw an Error.
+ *
+ * @param {Object} key the key for which to raise priority
+ * @param {Number} priority the new priority for the key
+ */
+PriorityQueue.prototype.decrease = function(key, priority) {
+  var index = this._keyIndices[key];
+  if (priority > this._arr[index].priority) {
+    throw new Error("New priority is greater than current priority. " +
+        "Key: " + key + " Old: " + this._arr[index].priority + " New: " + priority);
+  }
+  this._arr[index].priority = priority;
+  this._decrease(index);
+};
+
+PriorityQueue.prototype._heapify = function(i) {
+  var arr = this._arr;
+  var l = 2 * i,
+      r = l + 1,
+      largest = i;
+  if (l < arr.length) {
+    largest = arr[l].priority < arr[largest].priority ? l : largest;
+    if (r < arr.length) {
+      largest = arr[r].priority < arr[largest].priority ? r : largest;
+    }
+    if (largest !== i) {
+      this._swap(i, largest);
+      this._heapify(largest);
+    }
+  }
+};
+
+PriorityQueue.prototype._decrease = function(index) {
+  var arr = this._arr;
+  var priority = arr[index].priority;
+  var parent;
+  while (index !== 0) {
+    parent = index >> 1;
+    if (arr[parent].priority < priority) {
+      break;
+    }
+    this._swap(index, parent);
+    index = parent;
+  }
+};
+
+PriorityQueue.prototype._swap = function(i, j) {
+  var arr = this._arr;
+  var keyIndices = this._keyIndices;
+  var origArrI = arr[i];
+  var origArrJ = arr[j];
+  arr[i] = origArrJ;
+  arr[j] = origArrI;
+  keyIndices[origArrJ.key] = i;
+  keyIndices[origArrI.key] = j;
+};
+
+},{}],21:[function(require,module,exports){
+var util = require('./util');
+
+module.exports = Set;
+
+/**
+ * Constructs a new Set with an optional set of `initialKeys`.
+ *
+ * It is important to note that keys are coerced to String for most purposes
+ * with this object, similar to the behavior of JavaScript's Object. For
+ * example, the following will add only one key:
+ *
+ *     var s = new Set();
+ *     s.add(1);
+ *     s.add("1");
+ *
+ * However, the type of the key is preserved internally so that `keys` returns
+ * the original key set uncoerced. For the above example, `keys` would return
+ * `[1]`.
+ */
+function Set(initialKeys) {
+  this._size = 0;
+  this._keys = {};
+
+  if (initialKeys) {
+    for (var i = 0, il = initialKeys.length; i < il; ++i) {
+      this.add(initialKeys[i]);
+    }
+  }
+}
+
+/**
+ * Returns a new Set that represents the set intersection of the array of given
+ * sets.
+ */
+Set.intersect = function(sets) {
+  if (sets.length === 0) {
+    return new Set();
+  }
+
+  var result = new Set(!util.isArray(sets[0]) ? sets[0].keys() : sets[0]);
+  for (var i = 1, il = sets.length; i < il; ++i) {
+    var resultKeys = result.keys(),
+        other = !util.isArray(sets[i]) ? sets[i] : new Set(sets[i]);
+    for (var j = 0, jl = resultKeys.length; j < jl; ++j) {
+      var key = resultKeys[j];
+      if (!other.has(key)) {
+        result.remove(key);
+      }
+    }
+  }
+
+  return result;
+};
+
+/**
+ * Returns a new Set that represents the set union of the array of given sets.
+ */
+Set.union = function(sets) {
+  var totalElems = util.reduce(sets, function(lhs, rhs) {
+    return lhs + (rhs.size ? rhs.size() : rhs.length);
+  }, 0);
+  var arr = new Array(totalElems);
+
+  var k = 0;
+  for (var i = 0, il = sets.length; i < il; ++i) {
+    var cur = sets[i],
+        keys = !util.isArray(cur) ? cur.keys() : cur;
+    for (var j = 0, jl = keys.length; j < jl; ++j) {
+      arr[k++] = keys[j];
+    }
+  }
+
+  return new Set(arr);
+};
+
+/**
+ * Returns the size of this set in `O(1)` time.
+ */
+Set.prototype.size = function() {
+  return this._size;
+};
+
+/**
+ * Returns the keys in this set. Takes `O(n)` time.
+ */
+Set.prototype.keys = function() {
+  return values(this._keys);
+};
+
+/**
+ * Tests if a key is present in this Set. Returns `true` if it is and `false`
+ * if not. Takes `O(1)` time.
+ */
+Set.prototype.has = function(key) {
+  return key in this._keys;
+};
+
+/**
+ * Adds a new key to this Set if it is not already present. Returns `true` if
+ * the key was added and `false` if it was already present. Takes `O(1)` time.
+ */
+Set.prototype.add = function(key) {
+  if (!(key in this._keys)) {
+    this._keys[key] = key;
+    ++this._size;
+    return true;
+  }
+  return false;
+};
+
+/**
+ * Removes a key from this Set. If the key was removed this function returns
+ * `true`. If not, it returns `false`. Takes `O(1)` time.
+ */
+Set.prototype.remove = function(key) {
+  if (key in this._keys) {
+    delete this._keys[key];
+    --this._size;
+    return true;
+  }
+  return false;
+};
+
+/*
+ * Returns an array of all values for properties of **o**.
+ */
+function values(o) {
+  var ks = Object.keys(o),
+      len = ks.length,
+      result = new Array(len),
+      i;
+  for (i = 0; i < len; ++i) {
+    result[i] = o[ks[i]];
+  }
+  return result;
+}
+
+},{"./util":22}],22:[function(require,module,exports){
+/*
+ * This polyfill comes from
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
+ */
+if(!Array.isArray) {
+  exports.isArray = function (vArg) {
+    return Object.prototype.toString.call(vArg) === '[object Array]';
+  };
+} else {
+  exports.isArray = Array.isArray;
+}
+
+/*
+ * Slightly adapted polyfill from
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
+ */
+if ('function' !== typeof Array.prototype.reduce) {
+  exports.reduce = function(array, callback, opt_initialValue) {
+    'use strict';
+    if (null === array || 'undefined' === typeof array) {
+      // At the moment all modern browsers, that support strict mode, have
+      // native implementation of Array.prototype.reduce. For instance, IE8
+      // does not support strict mode, so this check is actually useless.
+      throw new TypeError(
+          'Array.prototype.reduce called on null or undefined');
+    }
+    if ('function' !== typeof callback) {
+      throw new TypeError(callback + ' is not a function');
+    }
+    var index, value,
+        length = array.length >>> 0,
+        isValueSet = false;
+    if (1 < arguments.length) {
+      value = opt_initialValue;
+      isValueSet = true;
+    }
+    for (index = 0; length > index; ++index) {
+      if (array.hasOwnProperty(index)) {
+        if (isValueSet) {
+          value = callback(value, array[index], index, array);
+        }
+        else {
+          value = array[index];
+          isValueSet = true;
+        }
+      }
+    }
+    if (!isValueSet) {
+      throw new TypeError('Reduce of empty array with no initial value');
+    }
+    return value;
+  };
+} else {
+  exports.reduce = function(array, callback, opt_initialValue) {
+    return array.reduce(callback, opt_initialValue);
+  };
+}
+
+},{}],23:[function(require,module,exports){
+module.exports = '1.1.3';
+
+},{}],24:[function(require,module,exports){
+exports.Graph = require("./lib/Graph");
+exports.Digraph = require("./lib/Digraph");
+exports.CGraph = require("./lib/CGraph");
+exports.CDigraph = require("./lib/CDigraph");
+require("./lib/graph-converters");
+
+exports.alg = {
+  isAcyclic: require("./lib/alg/isAcyclic"),
+  components: require("./lib/alg/components"),
+  dijkstra: require("./lib/alg/dijkstra"),
+  dijkstraAll: require("./lib/alg/dijkstraAll"),
+  findCycles: require("./lib/alg/findCycles"),
+  floydWarshall: require("./lib/alg/floydWarshall"),
+  postorder: require("./lib/alg/postorder"),
+  preorder: require("./lib/alg/preorder"),
+  prim: require("./lib/alg/prim"),
+  tarjan: require("./lib/alg/tarjan"),
+  topsort: require("./lib/alg/topsort")
+};
+
+exports.converter = {
+  json: require("./lib/converter/json.js")
+};
+
+var filter = require("./lib/filter");
+exports.filter = {
+  all: filter.all,
+  nodesFromList: filter.nodesFromList
+};
+
+exports.version = require("./lib/version");
+
+},{"./lib/CDigraph":26,"./lib/CGraph":27,"./lib/Digraph":28,"./lib/Graph":29,"./lib/alg/components":30,"./lib/alg/dijkstra":31,"./lib/alg/dijkstraAll":32,"./lib/alg/findCycles":33,"./lib/alg/floydWarshall":34,"./lib/alg/isAcyclic":35,"./lib/alg/postorder":36,"./lib/alg/preorder":37,"./lib/alg/prim":38,"./lib/alg/tarjan":39,"./lib/alg/topsort":40,"./lib/converter/json.js":42,"./lib/filter":43,"./lib/graph-converters":44,"./lib/version":46}],25:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = BaseGraph;
+
+function BaseGraph() {
+  // The value assigned to the graph itself.
+  this._value = undefined;
+
+  // Map of node id -> { id, value }
+  this._nodes = {};
+
+  // Map of edge id -> { id, u, v, value }
+  this._edges = {};
+
+  // Used to generate a unique id in the graph
+  this._nextId = 0;
+}
+
+// Number of nodes
+BaseGraph.prototype.order = function() {
+  return Object.keys(this._nodes).length;
+};
+
+// Number of edges
+BaseGraph.prototype.size = function() {
+  return Object.keys(this._edges).length;
+};
+
+// Accessor for graph level value
+BaseGraph.prototype.graph = function(value) {
+  if (arguments.length === 0) {
+    return this._value;
+  }
+  this._value = value;
+};
+
+BaseGraph.prototype.hasNode = function(u) {
+  return u in this._nodes;
+};
+
+BaseGraph.prototype.node = function(u, value) {
+  var node = this._strictGetNode(u);
+  if (arguments.length === 1) {
+    return node.value;
+  }
+  node.value = value;
+};
+
+BaseGraph.prototype.nodes = function() {
+  var nodes = [];
+  this.eachNode(function(id) { nodes.push(id); });
+  return nodes;
+};
+
+BaseGraph.prototype.eachNode = function(func) {
+  for (var k in this._nodes) {
+    var node = this._nodes[k];
+    func(node.id, node.value);
+  }
+};
+
+BaseGraph.prototype.hasEdge = function(e) {
+  return e in this._edges;
+};
+
+BaseGraph.prototype.edge = function(e, value) {
+  var edge = this._strictGetEdge(e);
+  if (arguments.length === 1) {
+    return edge.value;
+  }
+  edge.value = value;
+};
+
+BaseGraph.prototype.edges = function() {
+  var es = [];
+  this.eachEdge(function(id) { es.push(id); });
+  return es;
+};
+
+BaseGraph.prototype.eachEdge = function(func) {
+  for (var k in this._edges) {
+    var edge = this._edges[k];
+    func(edge.id, edge.u, edge.v, edge.value);
+  }
+};
+
+BaseGraph.prototype.incidentNodes = function(e) {
+  var edge = this._strictGetEdge(e);
+  return [edge.u, edge.v];
+};
+
+BaseGraph.prototype.addNode = function(u, value) {
+  if (u === undefined || u === null) {
+    do {
+      u = "_" + (++this._nextId);
+    } while (this.hasNode(u));
+  } else if (this.hasNode(u)) {
+    throw new Error("Graph already has node '" + u + "'");
+  }
+  this._nodes[u] = { id: u, value: value };
+  return u;
+};
+
+BaseGraph.prototype.delNode = function(u) {
+  this._strictGetNode(u);
+  this.incidentEdges(u).forEach(function(e) { this.delEdge(e); }, this);
+  delete this._nodes[u];
+};
+
+// inMap and outMap are opposite sides of an incidence map. For example, for
+// Graph these would both come from the _incidentEdges map, while for Digraph
+// they would come from _inEdges and _outEdges.
+BaseGraph.prototype._addEdge = function(e, u, v, value, inMap, outMap) {
+  this._strictGetNode(u);
+  this._strictGetNode(v);
+
+  if (e === undefined || e === null) {
+    do {
+      e = "_" + (++this._nextId);
+    } while (this.hasEdge(e));
+  }
+  else if (this.hasEdge(e)) {
+    throw new Error("Graph already has edge '" + e + "'");
+  }
+
+  this._edges[e] = { id: e, u: u, v: v, value: value };
+  addEdgeToMap(inMap[v], u, e);
+  addEdgeToMap(outMap[u], v, e);
+
+  return e;
+};
+
+// See note for _addEdge regarding inMap and outMap.
+BaseGraph.prototype._delEdge = function(e, inMap, outMap) {
+  var edge = this._strictGetEdge(e);
+  delEdgeFromMap(inMap[edge.v], edge.u, e);
+  delEdgeFromMap(outMap[edge.u], edge.v, e);
+  delete this._edges[e];
+};
+
+BaseGraph.prototype.copy = function() {
+  var copy = new this.constructor();
+  copy.graph(this.graph());
+  this.eachNode(function(u, value) { copy.addNode(u, value); });
+  this.eachEdge(function(e, u, v, value) { copy.addEdge(e, u, v, value); });
+  copy._nextId = this._nextId;
+  return copy;
+};
+
+BaseGraph.prototype.filterNodes = function(filter) {
+  var copy = new this.constructor();
+  copy.graph(this.graph());
+  this.eachNode(function(u, value) {
+    if (filter(u)) {
+      copy.addNode(u, value);
+    }
+  });
+  this.eachEdge(function(e, u, v, value) {
+    if (copy.hasNode(u) && copy.hasNode(v)) {
+      copy.addEdge(e, u, v, value);
+    }
+  });
+  return copy;
+};
+
+BaseGraph.prototype._strictGetNode = function(u) {
+  var node = this._nodes[u];
+  if (node === undefined) {
+    throw new Error("Node '" + u + "' is not in graph");
+  }
+  return node;
+};
+
+BaseGraph.prototype._strictGetEdge = function(e) {
+  var edge = this._edges[e];
+  if (edge === undefined) {
+    throw new Error("Edge '" + e + "' is not in graph");
+  }
+  return edge;
+};
+
+function addEdgeToMap(map, v, e) {
+  (map[v] || (map[v] = new Set())).add(e);
+}
+
+function delEdgeFromMap(map, v, e) {
+  var vEntry = map[v];
+  vEntry.remove(e);
+  if (vEntry.size() === 0) {
+    delete map[v];
+  }
+}
+
+
+},{"cp-data":19}],26:[function(require,module,exports){
+var Digraph = require("./Digraph"),
+    compoundify = require("./compoundify");
+
+var CDigraph = compoundify(Digraph);
+
+module.exports = CDigraph;
+
+CDigraph.fromDigraph = function(src) {
+  var g = new CDigraph(),
+      graphValue = src.graph();
+
+  if (graphValue !== undefined) {
+    g.graph(graphValue);
+  }
+
+  src.eachNode(function(u, value) {
+    if (value === undefined) {
+      g.addNode(u);
+    } else {
+      g.addNode(u, value);
+    }
+  });
+  src.eachEdge(function(e, u, v, value) {
+    if (value === undefined) {
+      g.addEdge(null, u, v);
+    } else {
+      g.addEdge(null, u, v, value);
+    }
+  });
+  return g;
+};
+
+CDigraph.prototype.toString = function() {
+  return "CDigraph " + JSON.stringify(this, null, 2);
+};
+
+},{"./Digraph":28,"./compoundify":41}],27:[function(require,module,exports){
+var Graph = require("./Graph"),
+    compoundify = require("./compoundify");
+
+var CGraph = compoundify(Graph);
+
+module.exports = CGraph;
+
+CGraph.fromGraph = function(src) {
+  var g = new CGraph(),
+      graphValue = src.graph();
+
+  if (graphValue !== undefined) {
+    g.graph(graphValue);
+  }
+
+  src.eachNode(function(u, value) {
+    if (value === undefined) {
+      g.addNode(u);
+    } else {
+      g.addNode(u, value);
+    }
+  });
+  src.eachEdge(function(e, u, v, value) {
+    if (value === undefined) {
+      g.addEdge(null, u, v);
+    } else {
+      g.addEdge(null, u, v, value);
+    }
+  });
+  return g;
+};
+
+CGraph.prototype.toString = function() {
+  return "CGraph " + JSON.stringify(this, null, 2);
+};
+
+},{"./Graph":29,"./compoundify":41}],28:[function(require,module,exports){
+/*
+ * This file is organized with in the following order:
+ *
+ * Exports
+ * Graph constructors
+ * Graph queries (e.g. nodes(), edges()
+ * Graph mutators
+ * Helper functions
+ */
+
+var util = require("./util"),
+    BaseGraph = require("./BaseGraph"),
+/* jshint -W079 */
+    Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = Digraph;
+
+/*
+ * Constructor to create a new directed multi-graph.
+ */
+function Digraph() {
+  BaseGraph.call(this);
+
+  /*! Map of sourceId -> {targetId -> Set of edge ids} */
+  this._inEdges = {};
+
+  /*! Map of targetId -> {sourceId -> Set of edge ids} */
+  this._outEdges = {};
+}
+
+Digraph.prototype = new BaseGraph();
+Digraph.prototype.constructor = Digraph;
+
+/*
+ * Always returns `true`.
+ */
+Digraph.prototype.isDirected = function() {
+  return true;
+};
+
+/*
+ * Returns all successors of the node with the id `u`. That is, all nodes
+ * that have the node `u` as their source are returned.
+ * 
+ * If no node `u` exists in the graph this function throws an Error.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.successors = function(u) {
+  this._strictGetNode(u);
+  return Object.keys(this._outEdges[u])
+               .map(function(v) { return this._nodes[v].id; }, this);
+};
+
+/*
+ * Returns all predecessors of the node with the id `u`. That is, all nodes
+ * that have the node `u` as their target are returned.
+ * 
+ * If no node `u` exists in the graph this function throws an Error.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.predecessors = function(u) {
+  this._strictGetNode(u);
+  return Object.keys(this._inEdges[u])
+               .map(function(v) { return this._nodes[v].id; }, this);
+};
+
+/*
+ * Returns all nodes that are adjacent to the node with the id `u`. In other
+ * words, this function returns the set of all successors and predecessors of
+ * node `u`.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.neighbors = function(u) {
+  return Set.union([this.successors(u), this.predecessors(u)]).keys();
+};
+
+/*
+ * Returns all nodes in the graph that have no in-edges.
+ */
+Digraph.prototype.sources = function() {
+  var self = this;
+  return this._filterNodes(function(u) {
+    // This could have better space characteristics if we had an inDegree function.
+    return self.inEdges(u).length === 0;
+  });
+};
+
+/*
+ * Returns all nodes in the graph that have no out-edges.
+ */
+Digraph.prototype.sinks = function() {
+  var self = this;
+  return this._filterNodes(function(u) {
+    // This could have better space characteristics if we have an outDegree function.
+    return self.outEdges(u).length === 0;
+  });
+};
+
+/*
+ * Returns the source node incident on the edge identified by the id `e`. If no
+ * such edge exists in the graph this function throws an Error.
+ *
+ * @param {String} e an edge id
+ */
+Digraph.prototype.source = function(e) {
+  return this._strictGetEdge(e).u;
+};
+
+/*
+ * Returns the target node incident on the edge identified by the id `e`. If no
+ * such edge exists in the graph this function throws an Error.
+ *
+ * @param {String} e an edge id
+ */
+Digraph.prototype.target = function(e) {
+  return this._strictGetEdge(e).v;
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that have the node
+ * `target` as their target. If the node `target` is not in the graph this
+ * function raises an Error.
+ *
+ * Optionally a `source` node can also be specified. This causes the results
+ * to be filtered such that only edges from `source` to `target` are included.
+ * If the node `source` is specified but is not in the graph then this function
+ * raises an Error.
+ *
+ * @param {String} target the target node id
+ * @param {String} [source] an optional source node id
+ */
+Digraph.prototype.inEdges = function(target, source) {
+  this._strictGetNode(target);
+  var results = Set.union(util.values(this._inEdges[target])).keys();
+  if (arguments.length > 1) {
+    this._strictGetNode(source);
+    results = results.filter(function(e) { return this.source(e) === source; }, this);
+  }
+  return results;
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that have the node
+ * `source` as their source. If the node `source` is not in the graph this
+ * function raises an Error.
+ *
+ * Optionally a `target` node may also be specified. This causes the results
+ * to be filtered such that only edges from `source` to `target` are included.
+ * If the node `target` is specified but is not in the graph then this function
+ * raises an Error.
+ *
+ * @param {String} source the source node id
+ * @param {String} [target] an optional target node id
+ */
+Digraph.prototype.outEdges = function(source, target) {
+  this._strictGetNode(source);
+  var results = Set.union(util.values(this._outEdges[source])).keys();
+  if (arguments.length > 1) {
+    this._strictGetNode(target);
+    results = results.filter(function(e) { return this.target(e) === target; }, this);
+  }
+  return results;
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that have the `u` as
+ * their source or their target. If the node `u` is not in the graph this
+ * function raises an Error.
+ *
+ * Optionally a `v` node may also be specified. This causes the results to be
+ * filtered such that only edges between `u` and `v` - in either direction -
+ * are included. IF the node `v` is specified but not in the graph then this
+ * function raises an Error.
+ *
+ * @param {String} u the node for which to find incident edges
+ * @param {String} [v] option node that must be adjacent to `u`
+ */
+Digraph.prototype.incidentEdges = function(u, v) {
+  if (arguments.length > 1) {
+    return Set.union([this.outEdges(u, v), this.outEdges(v, u)]).keys();
+  } else {
+    return Set.union([this.inEdges(u), this.outEdges(u)]).keys();
+  }
+};
+
+/*
+ * Returns a string representation of this graph.
+ */
+Digraph.prototype.toString = function() {
+  return "Digraph " + JSON.stringify(this, null, 2);
+};
+
+/*
+ * Adds a new node with the id `u` to the graph and assigns it the value
+ * `value`. If a node with the id is already a part of the graph this function
+ * throws an Error.
+ *
+ * @param {String} u a node id
+ * @param {Object} [value] an optional value to attach to the node
+ */
+Digraph.prototype.addNode = function(u, value) {
+  u = BaseGraph.prototype.addNode.call(this, u, value);
+  this._inEdges[u] = {};
+  this._outEdges[u] = {};
+  return u;
+};
+
+/*
+ * Removes a node from the graph that has the id `u`. Any edges incident on the
+ * node are also removed. If the graph does not contain a node with the id this
+ * function will throw an Error.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.delNode = function(u) {
+  BaseGraph.prototype.delNode.call(this, u);
+  delete this._inEdges[u];
+  delete this._outEdges[u];
+};
+
+/*
+ * Adds a new edge to the graph with the id `e` from a node with the id `source`
+ * to a node with an id `target` and assigns it the value `value`. This graph
+ * allows more than one edge from `source` to `target` as long as the id `e`
+ * is unique in the set of edges. If `e` is `null` the graph will assign a
+ * unique identifier to the edge.
+ *
+ * If `source` or `target` are not present in the graph this function will
+ * throw an Error.
+ *
+ * @param {String} [e] an edge id
+ * @param {String} source the source node id
+ * @param {String} target the target node id
+ * @param {Object} [value] an optional value to attach to the edge
+ */
+Digraph.prototype.addEdge = function(e, source, target, value) {
+  return BaseGraph.prototype._addEdge.call(this, e, source, target, value,
+                                           this._inEdges, this._outEdges);
+};
+
+/*
+ * Removes an edge in the graph with the id `e`. If no edge in the graph has
+ * the id `e` this function will throw an Error.
+ *
+ * @param {String} e an edge id
+ */
+Digraph.prototype.delEdge = function(e) {
+  BaseGraph.prototype._delEdge.call(this, e, this._inEdges, this._outEdges);
+};
+
+// Unlike BaseGraph.filterNodes, this helper just returns nodes that
+// satisfy a predicate.
+Digraph.prototype._filterNodes = function(pred) {
+  var filtered = [];
+  this.eachNode(function(u) {
+    if (pred(u)) {
+      filtered.push(u);
+    }
+  });
+  return filtered;
+};
+
+
+},{"./BaseGraph":25,"./util":45,"cp-data":19}],29:[function(require,module,exports){
+/*
+ * This file is organized with in the following order:
+ *
+ * Exports
+ * Graph constructors
+ * Graph queries (e.g. nodes(), edges()
+ * Graph mutators
+ * Helper functions
+ */
+
+var util = require("./util"),
+    BaseGraph = require("./BaseGraph"),
+/* jshint -W079 */
+    Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = Graph;
+
+/*
+ * Constructor to create a new undirected multi-graph.
+ */
+function Graph() {
+  BaseGraph.call(this);
+
+  /*! Map of nodeId -> { otherNodeId -> Set of edge ids } */
+  this._incidentEdges = {};
+}
+
+Graph.prototype = new BaseGraph();
+Graph.prototype.constructor = Graph;
+
+/*
+ * Always returns `false`.
+ */
+Graph.prototype.isDirected = function() {
+  return false;
+};
+
+/*
+ * Returns all nodes that are adjacent to the node with the id `u`.
+ *
+ * @param {String} u a node id
+ */
+Graph.prototype.neighbors = function(u) {
+  this._strictGetNode(u);
+  return Object.keys(this._incidentEdges[u])
+               .map(function(v) { return this._nodes[v].id; }, this);
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that are incident on `u`.
+ * If the node `u` is not in the graph this function raises an Error.
+ *
+ * Optionally a `v` node may also be specified. This causes the results to be
+ * filtered such that only edges between `u` and `v` are included. If the node
+ * `v` is specified but not in the graph then this function raises an Error.
+ *
+ * @param {String} u the node for which to find incident edges
+ * @param {String} [v] option node that must be adjacent to `u`
+ */
+Graph.prototype.incidentEdges = function(u, v) {
+  this._strictGetNode(u);
+  if (arguments.length > 1) {
+    this._strictGetNode(v);
+    return v in this._incidentEdges[u] ? this._incidentEdges[u][v].keys() : [];
+  } else {
+    return Set.union(util.values(this._incidentEdges[u])).keys();
+  }
+};
+
+/*
+ * Returns a string representation of this graph.
+ */
+Graph.prototype.toString = function() {
+  return "Graph " + JSON.stringify(this, null, 2);
+};
+
+/*
+ * Adds a new node with the id `u` to the graph and assigns it the value
+ * `value`. If a node with the id is already a part of the graph this function
+ * throws an Error.
+ *
+ * @param {String} u a node id
+ * @param {Object} [value] an optional value to attach to the node
+ */
+Graph.prototype.addNode = function(u, value) {
+  u = BaseGraph.prototype.addNode.call(this, u, value);
+  this._incidentEdges[u] = {};
+  return u;
+};
+
+/*
+ * Removes a node from the graph that has the id `u`. Any edges incident on the
+ * node are also removed. If the graph does not contain a node with the id this
+ * function will throw an Error.
+ *
+ * @param {String} u a node id
+ */
+Graph.prototype.delNode = function(u) {
+  BaseGraph.prototype.delNode.call(this, u);
+  delete this._incidentEdges[u];
+};
+
+/*
+ * Adds a new edge to the graph with the id `e` between a node with the id `u`
+ * and a node with an id `v` and assigns it the value `value`. This graph
+ * allows more than one edge between `u` and `v` as long as the id `e`
+ * is unique in the set of edges. If `e` is `null` the graph will assign a
+ * unique identifier to the edge.
+ *
+ * If `u` or `v` are not present in the graph this function will throw an
+ * Error.
+ *
+ * @param {String} [e] an edge id
+ * @param {String} u the node id of one of the adjacent nodes
+ * @param {String} v the node id of the other adjacent node
+ * @param {Object} [value] an optional value to attach to the edge
+ */
+Graph.prototype.addEdge = function(e, u, v, value) {
+  return BaseGraph.prototype._addEdge.call(this, e, u, v, value,
+                                           this._incidentEdges, this._incidentEdges);
+};
+
+/*
+ * Removes an edge in the graph with the id `e`. If no edge in the graph has
+ * the id `e` this function will throw an Error.
+ *
+ * @param {String} e an edge id
+ */
+Graph.prototype.delEdge = function(e) {
+  BaseGraph.prototype._delEdge.call(this, e, this._incidentEdges, this._incidentEdges);
+};
+
+
+},{"./BaseGraph":25,"./util":45,"cp-data":19}],30:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = components;
+
+/**
+ * Finds all [connected components][] in a graph and returns an array of these
+ * components. Each component is itself an array that contains the ids of nodes
+ * in the component.
+ *
+ * This function only works with undirected Graphs.
+ *
+ * [connected components]: http://en.wikipedia.org/wiki/Connected_component_(graph_theory)
+ *
+ * @param {Graph} g the graph to search for components
+ */
+function components(g) {
+  var results = [];
+  var visited = new Set();
+
+  function dfs(v, component) {
+    if (!visited.has(v)) {
+      visited.add(v);
+      component.push(v);
+      g.neighbors(v).forEach(function(w) {
+        dfs(w, component);
+      });
+    }
+  }
+
+  g.nodes().forEach(function(v) {
+    var component = [];
+    dfs(v, component);
+    if (component.length > 0) {
+      results.push(component);
+    }
+  });
+
+  return results;
+}
+
+},{"cp-data":19}],31:[function(require,module,exports){
+var PriorityQueue = require("cp-data").PriorityQueue;
+
+module.exports = dijkstra;
+
+/**
+ * This function is an implementation of [Dijkstra's algorithm][] which finds
+ * the shortest path from **source** to all other nodes in **g**. This
+ * function returns a map of `u -> { distance, predecessor }`. The distance
+ * property holds the sum of the weights from **source** to `u` along the
+ * shortest path or `Number.POSITIVE_INFINITY` if there is no path from
+ * **source**. The predecessor property can be used to walk the individual
+ * elements of the path from **source** to **u** in reverse order.
+ *
+ * This function takes an optional `weightFunc(e)` which returns the
+ * weight of the edge `e`. If no weightFunc is supplied then each edge is
+ * assumed to have a weight of 1. This function throws an Error if any of
+ * the traversed edges have a negative edge weight.
+ *
+ * This function takes an optional `incidentFunc(u)` which returns the ids of
+ * all edges incident to the node `u` for the purposes of shortest path
+ * traversal. By default this function uses the `g.outEdges` for Digraphs and
+ * `g.incidentEdges` for Graphs.
+ *
+ * This function takes `O((|E| + |V|) * log |V|)` time.
+ *
+ * [Dijkstra's algorithm]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
+ *
+ * @param {Graph} g the graph to search for shortest paths from **source**
+ * @param {Object} source the source from which to start the search
+ * @param {Function} [weightFunc] optional weight function
+ * @param {Function} [incidentFunc] optional incident function
+ */
+function dijkstra(g, source, weightFunc, incidentFunc) {
+  var results = {},
+      pq = new PriorityQueue();
+
+  function updateNeighbors(e) {
+    var incidentNodes = g.incidentNodes(e),
+        v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1],
+        vEntry = results[v],
+        weight = weightFunc(e),
+        distance = uEntry.distance + weight;
+
+    if (weight < 0) {
+      throw new Error("dijkstra does not allow negative edge weights. Bad edge: " + e + " Weight: " + weight);
+    }
+
+    if (distance < vEntry.distance) {
+      vEntry.distance = distance;
+      vEntry.predecessor = u;
+      pq.decrease(v, distance);
+    }
+  }
+
+  weightFunc = weightFunc || function() { return 1; };
+  incidentFunc = incidentFunc || (g.isDirected()
+      ? function(u) { return g.outEdges(u); }
+      : function(u) { return g.incidentEdges(u); });
+
+  g.eachNode(function(u) {
+    var distance = u === source ? 0 : Number.POSITIVE_INFINITY;
+    results[u] = { distance: distance };
+    pq.add(u, distance);
+  });
+
+  var u, uEntry;
+  while (pq.size() > 0) {
+    u = pq.removeMin();
+    uEntry = results[u];
+    if (uEntry.distance === Number.POSITIVE_INFINITY) {
+      break;
+    }
+
+    incidentFunc(u).forEach(updateNeighbors);
+  }
+
+  return results;
+}
+
+},{"cp-data":19}],32:[function(require,module,exports){
+var dijkstra = require("./dijkstra");
+
+module.exports = dijkstraAll;
+
+/**
+ * This function finds the shortest path from each node to every other
+ * reachable node in the graph. It is similar to [alg.dijkstra][], but
+ * instead of returning a single-source array, it returns a mapping of
+ * of `source -> alg.dijksta(g, source, weightFunc, incidentFunc)`.
+ *
+ * This function takes an optional `weightFunc(e)` which returns the
+ * weight of the edge `e`. If no weightFunc is supplied then each edge is
+ * assumed to have a weight of 1. This function throws an Error if any of
+ * the traversed edges have a negative edge weight.
+ *
+ * This function takes an optional `incidentFunc(u)` which returns the ids of
+ * all edges incident to the node `u` for the purposes of shortest path
+ * traversal. By default this function uses the `outEdges` function on the
+ * supplied graph.
+ *
+ * This function takes `O(|V| * (|E| + |V|) * log |V|)` time.
+ *
+ * [alg.dijkstra]: dijkstra.js.html#dijkstra
+ *
+ * @param {Graph} g the graph to search for shortest paths from **source**
+ * @param {Function} [weightFunc] optional weight function
+ * @param {Function} [incidentFunc] optional incident function
+ */
+function dijkstraAll(g, weightFunc, incidentFunc) {
+  var results = {};
+  g.eachNode(function(u) {
+    results[u] = dijkstra(g, u, weightFunc, incidentFunc);
+  });
+  return results;
+}
+
+},{"./dijkstra":31}],33:[function(require,module,exports){
+var tarjan = require("./tarjan");
+
+module.exports = findCycles;
+
+/*
+ * Given a Digraph **g** this function returns all nodes that are part of a
+ * cycle. Since there may be more than one cycle in a graph this function
+ * returns an array of these cycles, where each cycle is itself represented
+ * by an array of ids for each node involved in that cycle.
+ *
+ * [alg.isAcyclic][] is more efficient if you only need to determine whether
+ * a graph has a cycle or not.
+ *
+ * [alg.isAcyclic]: isAcyclic.js.html#isAcyclic
+ *
+ * @param {Digraph} g the graph to search for cycles.
+ */
+function findCycles(g) {
+  return tarjan(g).filter(function(cmpt) { return cmpt.length > 1; });
+}
+
+},{"./tarjan":39}],34:[function(require,module,exports){
+module.exports = floydWarshall;
+
+/**
+ * This function is an implementation of the [Floyd-Warshall algorithm][],
+ * which finds the shortest path from each node to every other reachable node
+ * in the graph. It is similar to [alg.dijkstraAll][], but it handles negative
+ * edge weights and is more efficient for some types of graphs. This function
+ * returns a map of `source -> { target -> { distance, predecessor }`. The
+ * distance property holds the sum of the weights from `source` to `target`
+ * along the shortest path of `Number.POSITIVE_INFINITY` if there is no path
+ * from `source`. The predecessor property can be used to walk the individual
+ * elements of the path from `source` to `target` in reverse order.
+ *
+ * This function takes an optional `weightFunc(e)` which returns the
+ * weight of the edge `e`. If no weightFunc is supplied then each edge is
+ * assumed to have a weight of 1.
+ *
+ * This function takes an optional `incidentFunc(u)` which returns the ids of
+ * all edges incident to the node `u` for the purposes of shortest path
+ * traversal. By default this function uses the `outEdges` function on the
+ * supplied graph.
+ *
+ * This algorithm takes O(|V|^3) time.
+ *
+ * [Floyd-Warshall algorithm]: https://en.wikipedia.org/wiki/Floyd-Warshall_algorithm
+ * [alg.dijkstraAll]: dijkstraAll.js.html#dijkstraAll
+ *
+ * @param {Graph} g the graph to search for shortest paths from **source**
+ * @param {Function} [weightFunc] optional weight function
+ * @param {Function} [incidentFunc] optional incident function
+ */
+function floydWarshall(g, weightFunc, incidentFunc) {
+  var results = {},
+      nodes = g.nodes();
+
+  weightFunc = weightFunc || function() { return 1; };
+  incidentFunc = incidentFunc || (g.isDirected()
+      ? function(u) { return g.outEdges(u); }
+      : function(u) { return g.incidentEdges(u); });
+
+  nodes.forEach(function(u) {
+    results[u] = {};
+    results[u][u] = { distance: 0 };
+    nodes.forEach(function(v) {
+      if (u !== v) {
+        results[u][v] = { distance: Number.POSITIVE_INFINITY };
+      }
+    });
+    incidentFunc(u).forEach(function(e) {
+      var incidentNodes = g.incidentNodes(e),
+          v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1],
+          d = weightFunc(e);
+      if (d < results[u][v].distance) {
+        results[u][v] = { distance: d, predecessor: u };
+      }
+    });
+  });
+
+  nodes.forEach(function(k) {
+    var rowK = results[k];
+    nodes.forEach(function(i) {
+      var rowI = results[i];
+      nodes.forEach(function(j) {
+        var ik = rowI[k];
+        var kj = rowK[j];
+        var ij = rowI[j];
+        var altDistance = ik.distance + kj.distance;
+        if (altDistance < ij.distance) {
+          ij.distance = altDistance;
+          ij.predecessor = kj.predecessor;
+        }
+      });
+    });
+  });
+
+  return results;
+}
+
+},{}],35:[function(require,module,exports){
+var topsort = require("./topsort");
+
+module.exports = isAcyclic;
+
+/*
+ * Given a Digraph **g** this function returns `true` if the graph has no
+ * cycles and returns `false` if it does. This algorithm returns as soon as it
+ * detects the first cycle.
+ *
+ * Use [alg.findCycles][] if you need the actual list of cycles in a graph.
+ *
+ * [alg.findCycles]: findCycles.js.html#findCycles
+ *
+ * @param {Digraph} g the graph to test for cycles
+ */
+function isAcyclic(g) {
+  try {
+    topsort(g);
+  } catch (e) {
+    if (e instanceof topsort.CycleException) return false;
+    throw e;
+  }
+  return true;
+}
+
+},{"./topsort":40}],36:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = postorder;
+
+// Postorder traversal of g, calling f for each visited node. Assumes the graph
+// is a tree.
+function postorder(g, root, f) {
+  var visited = new Set();
+  if (g.isDirected()) {
+    throw new Error("This function only works for undirected graphs");
+  }
+  function dfs(u, prev) {
+    if (visited.has(u)) {
+      throw new Error("The input graph is not a tree: " + g);
+    }
+    visited.add(u);
+    g.neighbors(u).forEach(function(v) {
+      if (v !== prev) dfs(v, u);
+    });
+    f(u);
+  }
+  dfs(root);
+}
+
+},{"cp-data":19}],37:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = preorder;
+
+// Preorder traversal of g, calling f for each visited node. Assumes the graph
+// is a tree.
+function preorder(g, root, f) {
+  var visited = new Set();
+  if (g.isDirected()) {
+    throw new Error("This function only works for undirected graphs");
+  }
+  function dfs(u, prev) {
+    if (visited.has(u)) {
+      throw new Error("The input graph is not a tree: " + g);
+    }
+    visited.add(u);
+    f(u);
+    g.neighbors(u).forEach(function(v) {
+      if (v !== prev) dfs(v, u);
+    });
+  }
+  dfs(root);
+}
+
+},{"cp-data":19}],38:[function(require,module,exports){
+var Graph = require("../Graph"),
+    PriorityQueue = require("cp-data").PriorityQueue;
+
+module.exports = prim;
+
+/**
+ * [Prim's algorithm][] takes a connected undirected graph and generates a
+ * [minimum spanning tree][]. This function returns the minimum spanning
+ * tree as an undirected graph. This algorithm is derived from the description
+ * in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634.
+ *
+ * This function takes a `weightFunc(e)` which returns the weight of the edge
+ * `e`. It throws an Error if the graph is not connected.
+ *
+ * This function takes `O(|E| log |V|)` time.
+ *
+ * [Prim's algorithm]: https://en.wikipedia.org/wiki/Prim's_algorithm
+ * [minimum spanning tree]: https://en.wikipedia.org/wiki/Minimum_spanning_tree
+ *
+ * @param {Graph} g the graph used to generate the minimum spanning tree
+ * @param {Function} weightFunc the weight function to use
+ */
+function prim(g, weightFunc) {
+  var result = new Graph(),
+      parents = {},
+      pq = new PriorityQueue(),
+      u;
+
+  function updateNeighbors(e) {
+    var incidentNodes = g.incidentNodes(e),
+        v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1],
+        pri = pq.priority(v);
+    if (pri !== undefined) {
+      var edgeWeight = weightFunc(e);
+      if (edgeWeight < pri) {
+        parents[v] = u;
+        pq.decrease(v, edgeWeight);
+      }
+    }
+  }
+
+  if (g.order() === 0) {
+    return result;
+  }
+
+  g.eachNode(function(u) {
+    pq.add(u, Number.POSITIVE_INFINITY);
+    result.addNode(u);
+  });
+
+  // Start from an arbitrary node
+  pq.decrease(g.nodes()[0], 0);
+
+  var init = false;
+  while (pq.size() > 0) {
+    u = pq.removeMin();
+    if (u in parents) {
+      result.addEdge(null, u, parents[u]);
+    } else if (init) {
+      throw new Error("Input graph is not connected: " + g);
+    } else {
+      init = true;
+    }
+
+    g.incidentEdges(u).forEach(updateNeighbors);
+  }
+
+  return result;
+}
+
+},{"../Graph":29,"cp-data":19}],39:[function(require,module,exports){
+module.exports = tarjan;
+
+/**
+ * This function is an implementation of [Tarjan's algorithm][] which finds
+ * all [strongly connected components][] in the directed graph **g**. Each
+ * strongly connected component is composed of nodes that can reach all other
+ * nodes in the component via directed edges. A strongly connected component
+ * can consist of a single node if that node cannot both reach and be reached
+ * by any other specific node in the graph. Components of more than one node
+ * are guaranteed to have at least one cycle.
+ *
+ * This function returns an array of components. Each component is itself an
+ * array that contains the ids of all nodes in the component.
+ *
+ * [Tarjan's algorithm]: http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
+ * [strongly connected components]: http://en.wikipedia.org/wiki/Strongly_connected_component
+ *
+ * @param {Digraph} g the graph to search for strongly connected components
+ */
+function tarjan(g) {
+  if (!g.isDirected()) {
+    throw new Error("tarjan can only be applied to a directed graph. Bad input: " + g);
+  }
+
+  var index = 0,
+      stack = [],
+      visited = {}, // node id -> { onStack, lowlink, index }
+      results = [];
+
+  function dfs(u) {
+    var entry = visited[u] = {
+      onStack: true,
+      lowlink: index,
+      index: index++
+    };
+    stack.push(u);
+
+    g.successors(u).forEach(function(v) {
+      if (!(v in visited)) {
+        dfs(v);
+        entry.lowlink = Math.min(entry.lowlink, visited[v].lowlink);
+      } else if (visited[v].onStack) {
+        entry.lowlink = Math.min(entry.lowlink, visited[v].index);
+      }
+    });
+
+    if (entry.lowlink === entry.index) {
+      var cmpt = [],
+          v;
+      do {
+        v = stack.pop();
+        visited[v].onStack = false;
+        cmpt.push(v);
+      } while (u !== v);
+      results.push(cmpt);
+    }
+  }
+
+  g.nodes().forEach(function(u) {
+    if (!(u in visited)) {
+      dfs(u);
+    }
+  });
+
+  return results;
+}
+
+},{}],40:[function(require,module,exports){
+module.exports = topsort;
+topsort.CycleException = CycleException;
+
+/*
+ * Given a graph **g**, this function returns an ordered list of nodes such
+ * that for each edge `u -> v`, `u` appears before `v` in the list. If the
+ * graph has a cycle it is impossible to generate such a list and
+ * **CycleException** is thrown.
+ *
+ * See [topological sorting](https://en.wikipedia.org/wiki/Topological_sorting)
+ * for more details about how this algorithm works.
+ *
+ * @param {Digraph} g the graph to sort
+ */
+function topsort(g) {
+  if (!g.isDirected()) {
+    throw new Error("topsort can only be applied to a directed graph. Bad input: " + g);
+  }
+
+  var visited = {};
+  var stack = {};
+  var results = [];
+
+  function visit(node) {
+    if (node in stack) {
+      throw new CycleException();
+    }
+
+    if (!(node in visited)) {
+      stack[node] = true;
+      visited[node] = true;
+      g.predecessors(node).forEach(function(pred) {
+        visit(pred);
+      });
+      delete stack[node];
+      results.push(node);
+    }
+  }
+
+  var sinks = g.sinks();
+  if (g.order() !== 0 && sinks.length === 0) {
+    throw new CycleException();
+  }
+
+  g.sinks().forEach(function(sink) {
+    visit(sink);
+  });
+
+  return results;
+}
+
+function CycleException() {}
+
+CycleException.prototype.toString = function() {
+  return "Graph has at least one cycle";
+};
+
+},{}],41:[function(require,module,exports){
+// This file provides a helper function that mixes-in Dot behavior to an
+// existing graph prototype.
+
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = compoundify;
+
+// Extends the given SuperConstructor with the ability for nodes to contain
+// other nodes. A special node id `null` is used to indicate the root graph.
+function compoundify(SuperConstructor) {
+  function Constructor() {
+    SuperConstructor.call(this);
+
+    // Map of object id -> parent id (or null for root graph)
+    this._parents = {};
+
+    // Map of id (or null) -> children set
+    this._children = {};
+    this._children[null] = new Set();
+  }
+
+  Constructor.prototype = new SuperConstructor();
+  Constructor.prototype.constructor = Constructor;
+
+  Constructor.prototype.parent = function(u, parent) {
+    this._strictGetNode(u);
+
+    if (arguments.length < 2) {
+      return this._parents[u];
+    }
+
+    if (u === parent) {
+      throw new Error("Cannot make " + u + " a parent of itself");
+    }
+    if (parent !== null) {
+      this._strictGetNode(parent);
+    }
+
+    this._children[this._parents[u]].remove(u);
+    this._parents[u] = parent;
+    this._children[parent].add(u);
+  };
+
+  Constructor.prototype.children = function(u) {
+    if (u !== null) {
+      this._strictGetNode(u);
+    }
+    return this._children[u].keys();
+  };
+
+  Constructor.prototype.addNode = function(u, value) {
+    u = SuperConstructor.prototype.addNode.call(this, u, value);
+    this._parents[u] = null;
+    this._children[u] = new Set();
+    this._children[null].add(u);
+    return u;
+  };
+
+  Constructor.prototype.delNode = function(u) {
+    // Promote all children to the parent of the subgraph
+    var parent = this.parent(u);
+    this._children[u].keys().forEach(function(child) {
+      this.parent(child, parent);
+    }, this);
+
+    this._children[parent].remove(u);
+    delete this._parents[u];
+    delete this._children[u];
+
+    return SuperConstructor.prototype.delNode.call(this, u);
+  };
+
+  Constructor.prototype.copy = function() {
+    var copy = SuperConstructor.prototype.copy.call(this);
+    this.nodes().forEach(function(u) {
+      copy.parent(u, this.parent(u));
+    }, this);
+    return copy;
+  };
+
+  Constructor.prototype.filterNodes = function(filter) {
+    var self = this,
+        copy = SuperConstructor.prototype.filterNodes.call(this, filter);
+
+    var parents = {};
+    function findParent(u) {
+      var parent = self.parent(u);
+      if (parent === null || copy.hasNode(parent)) {
+        parents[u] = parent;
+        return parent;
+      } else if (parent in parents) {
+        return parents[parent];
+      } else {
+        return findParent(parent);
+      }
+    }
+
+    copy.eachNode(function(u) { copy.parent(u, findParent(u)); });
+
+    return copy;
+  };
+
+  return Constructor;
+}
+
+},{"cp-data":19}],42:[function(require,module,exports){
+var Graph = require("../Graph"),
+    Digraph = require("../Digraph"),
+    CGraph = require("../CGraph"),
+    CDigraph = require("../CDigraph");
+
+exports.decode = function(nodes, edges, Ctor) {
+  Ctor = Ctor || Digraph;
+
+  if (typeOf(nodes) !== "Array") {
+    throw new Error("nodes is not an Array");
+  }
+
+  if (typeOf(edges) !== "Array") {
+    throw new Error("edges is not an Array");
+  }
+
+  if (typeof Ctor === "string") {
+    switch(Ctor) {
+      case "graph": Ctor = Graph; break;
+      case "digraph": Ctor = Digraph; break;
+      case "cgraph": Ctor = CGraph; break;
+      case "cdigraph": Ctor = CDigraph; break;
+      default: throw new Error("Unrecognized graph type: " + Ctor);
+    }
+  }
+
+  var graph = new Ctor();
+
+  nodes.forEach(function(u) {
+    graph.addNode(u.id, u.value);
+  });
+
+  // If the graph is compound, set up children...
+  if (graph.parent) {
+    nodes.forEach(function(u) {
+      if (u.children) {
+        u.children.forEach(function(v) {
+          graph.parent(v, u.id);
+        });
+      }
+    });
+  }
+
+  edges.forEach(function(e) {
+    graph.addEdge(e.id, e.u, e.v, e.value);
+  });
+
+  return graph;
+};
+
+exports.encode = function(graph) {
+  var nodes = [];
+  var edges = [];
+
+  graph.eachNode(function(u, value) {
+    var node = {id: u, value: value};
+    if (graph.children) {
+      var children = graph.children(u);
+      if (children.length) {
+        node.children = children;
+      }
+    }
+    nodes.push(node);
+  });
+
+  graph.eachEdge(function(e, u, v, value) {
+    edges.push({id: e, u: u, v: v, value: value});
+  });
+
+  var type;
+  if (graph instanceof CDigraph) {
+    type = "cdigraph";
+  } else if (graph instanceof CGraph) {
+    type = "cgraph";
+  } else if (graph instanceof Digraph) {
+    type = "digraph";
+  } else if (graph instanceof Graph) {
+    type = "graph";
+  } else {
+    throw new Error("Couldn't determine type of graph: " + graph);
+  }
+
+  return { nodes: nodes, edges: edges, type: type };
+};
+
+function typeOf(obj) {
+  return Object.prototype.toString.call(obj).slice(8, -1);
+}
+
+},{"../CDigraph":26,"../CGraph":27,"../Digraph":28,"../Graph":29}],43:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+exports.all = function() {
+  return function() { return true; };
+};
+
+exports.nodesFromList = function(nodes) {
+  var set = new Set(nodes);
+  return function(u) {
+    return set.has(u);
+  };
+};
+
+},{"cp-data":19}],44:[function(require,module,exports){
+var Graph = require("./Graph"),
+    Digraph = require("./Digraph");
+
+// Side-effect based changes are lousy, but node doesn't seem to resolve the
+// requires cycle.
+
+/**
+ * Returns a new directed graph using the nodes and edges from this graph. The
+ * new graph will have the same nodes, but will have twice the number of edges:
+ * each edge is split into two edges with opposite directions. Edge ids,
+ * consequently, are not preserved by this transformation.
+ */
+Graph.prototype.toDigraph =
+Graph.prototype.asDirected = function() {
+  var g = new Digraph();
+  this.eachNode(function(u, value) { g.addNode(u, value); });
+  this.eachEdge(function(e, u, v, value) {
+    g.addEdge(null, u, v, value);
+    g.addEdge(null, v, u, value);
+  });
+  return g;
+};
+
+/**
+ * Returns a new undirected graph using the nodes and edges from this graph.
+ * The new graph will have the same nodes, but the edges will be made
+ * undirected. Edge ids are preserved in this transformation.
+ */
+Digraph.prototype.toGraph =
+Digraph.prototype.asUndirected = function() {
+  var g = new Graph();
+  this.eachNode(function(u, value) { g.addNode(u, value); });
+  this.eachEdge(function(e, u, v, value) {
+    g.addEdge(e, u, v, value);
+  });
+  return g;
+};
+
+},{"./Digraph":28,"./Graph":29}],45:[function(require,module,exports){
+// Returns an array of all values for properties of **o**.
+exports.values = function(o) {
+  var ks = Object.keys(o),
+      len = ks.length,
+      result = new Array(len),
+      i;
+  for (i = 0; i < len; ++i) {
+    result[i] = o[ks[i]];
+  }
+  return result;
+};
+
+},{}],46:[function(require,module,exports){
+module.exports = '0.7.4';
+
+},{}]},{},[1])
+;
+joint.layout.DirectedGraph = {
+
+    layout: function(graph, opt) {
+
+        opt = opt || {};
+
+        var inputGraph = this._prepareData(graph);
+        var runner = dagre.layout();
+
+        if (opt.debugLevel) { runner.debugLevel(opt.debugLevel); }
+        if (opt.rankDir) { runner.rankDir(opt.rankDir); }
+        if (opt.rankSep) { runner.rankSep(opt.rankSep); }
+        if (opt.edgeSep) { runner.edgeSep(opt.edgeSep); }
+        if (opt.nodeSep) { runner.nodeSep(opt.nodeSep); }
+
+        var layoutGraph = runner.run(inputGraph);
+        
+        layoutGraph.eachNode(function(u, value) {
+            if (!value.dummy) {
+                graph.get('cells').get(u).set('position', {
+                    x: value.x - value.width/2,
+                    y: value.y - value.height/2
+                });
+            }
+        });
+
+        if (opt.setLinkVertices) {
+
+            layoutGraph.eachEdge(function(e, u, v, value) {
+                var link = graph.get('cells').get(e);
+                if (link) {
+                    graph.get('cells').get(e).set('vertices', value.points);
+                }
+            });
+        }
+
+        return { width: layoutGraph.graph().width, height: layoutGraph.graph().height };
+    },
+    
+    _prepareData: function(graph) {
+
+        var dagreGraph = new dagre.Digraph();
+
+        // For each element.
+        _.each(graph.getElements(), function(cell) {
+
+            if (dagreGraph.hasNode(cell.id)) return;
+
+            dagreGraph.addNode(cell.id, {
+                width: cell.get('size').width,
+                height: cell.get('size').height,
+                rank: cell.get('rank')
+            });
+        });
+
+        // For each link.
+        _.each(graph.getLinks(), function(cell) {
+
+            if (dagreGraph.hasEdge(cell.id)) return;
+
+            var sourceId = cell.get('source').id;
+            var targetId = cell.get('target').id;
+
+            dagreGraph.addEdge(cell.id, sourceId, targetId, { minLen: cell.get('minLen') || 1 });
+        });
+
+        return dagreGraph;
+    }
+};
diff --git a/js/joint.all.min.js b/js/joint.all.min.js
new file mode 100644 (file)
index 0000000..2064759
--- /dev/null
@@ -0,0 +1,30 @@
+/*! Rappid - the diagramming toolkit
+
+Copyright (c) 2014 client IO
+
+ 2014-05-13 
+
+
+This Source Code Form is subject to the terms of the Rappid Academic License
+, v. 1.0. If a copy of the Rappid License was not distributed with this
+file, You can obtain one at http://jointjs.com/license/rappid_academic_v1.txt
+ or from the Rappid archive as was distributed by client IO. See the LICENSE file.*/
+
+
+function RGBColor(t){this.ok=!1,"#"==t.charAt(0)&&(t=t.substr(1,6)),t=t.replace(/ /g,""),t=t.toLowerCase();var e={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"};for(var i in e)t==i&&(t=e[i]);for(var n=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(t){return[parseInt(t[1]),parseInt(t[2]),parseInt(t[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}}],r=0;n.length>r;r++){var a=n[r].re,s=n[r].process,o=a.exec(t);o&&(channels=s(o),this.r=channels[0],this.g=channels[1],this.b=channels[2],this.ok=!0)}this.r=0>this.r||isNaN(this.r)?0:this.r>255?255:this.r,this.g=0>this.g||isNaN(this.g)?0:this.g>255?255:this.g,this.b=0>this.b||isNaN(this.b)?0:this.b>255?255:this.b,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toHex=function(){var t=this.r.toString(16),e=this.g.toString(16),i=this.b.toString(16);return 1==t.length&&(t="0"+t),1==e.length&&(e="0"+e),1==i.length&&(i="0"+i),"#"+t+e+i},this.getHelpXML=function(){for(var t=[],i=0;n.length>i;i++)for(var r=n[i].example,a=0;r.length>a;a++)t[t.length]=r[a];for(var s in e)t[t.length]=s;var o=document.createElement("ul");o.setAttribute("id","rgbcolor-examples");for(var i=0;t.length>i;i++)try{var l=document.createElement("li"),c=new RGBColor(t[i]),h=document.createElement("div");h.style.cssText="margin: 3px; border: 1px solid black; background:"+c.toHex()+"; "+"color:"+c.toHex(),h.appendChild(document.createTextNode("test"));var u=document.createTextNode(" "+t[i]+" -> "+c.toRGB()+" -> "+c.toHex());l.appendChild(h),l.appendChild(u),o.appendChild(l)}catch(p){}return o}}function stackBlurImage(t,e,i,n){var r=document.getElementById(t),a=r.naturalWidth,s=r.naturalHeight,o=document.getElementById(e);o.style.width=a+"px",o.style.height=s+"px",o.width=a,o.height=s;var l=o.getContext("2d");l.clearRect(0,0,a,s),l.drawImage(r,0,0),isNaN(i)||1>i||(n?stackBlurCanvasRGBA(e,0,0,a,s,i):stackBlurCanvasRGB(e,0,0,a,s,i))}function stackBlurCanvasRGBA(t,e,i,n,r,a){if(!(isNaN(a)||1>a)){a|=0;var s,o=document.getElementById(t),l=o.getContext("2d");try{try{s=l.getImageData(e,i,n,r)}catch(c){try{netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"),s=l.getImageData(e,i,n,r)}catch(c){throw alert("Cannot access local image"),Error("unable to access local image data: "+c)}}}catch(c){throw alert("Cannot access image"),Error("unable to access image data: "+c)}var h,u,p,g,d,f,m,I,y,v,C,b,A,w,x,M,j,N,k,D,z,S,T,E,G=s.data,L=a+a+1,B=n-1,Z=r-1,_=a+1,P=_*(_+1)/2,O=new BlurStack,Y=O;for(p=1;L>p;p++)if(Y=Y.next=new BlurStack,p==_)var W=Y;Y.next=O;var V=null,R=null;m=f=0;var X=mul_table[a],U=shg_table[a];for(u=0;r>u;u++){for(M=j=N=k=I=y=v=C=0,b=_*(D=G[f]),A=_*(z=G[f+1]),w=_*(S=G[f+2]),x=_*(T=G[f+3]),I+=P*D,y+=P*z,v+=P*S,C+=P*T,Y=O,p=0;_>p;p++)Y.r=D,Y.g=z,Y.b=S,Y.a=T,Y=Y.next;for(p=1;_>p;p++)g=f+((p>B?B:p)<<2),I+=(Y.r=D=G[g])*(E=_-p),y+=(Y.g=z=G[g+1])*E,v+=(Y.b=S=G[g+2])*E,C+=(Y.a=T=G[g+3])*E,M+=D,j+=z,N+=S,k+=T,Y=Y.next;for(V=O,R=W,h=0;n>h;h++)G[f+3]=T=C*X>>U,0!=T?(T=255/T,G[f]=(I*X>>U)*T,G[f+1]=(y*X>>U)*T,G[f+2]=(v*X>>U)*T):G[f]=G[f+1]=G[f+2]=0,I-=b,y-=A,v-=w,C-=x,b-=V.r,A-=V.g,w-=V.b,x-=V.a,g=m+(B>(g=h+a+1)?g:B)<<2,M+=V.r=G[g],j+=V.g=G[g+1],N+=V.b=G[g+2],k+=V.a=G[g+3],I+=M,y+=j,v+=N,C+=k,V=V.next,b+=D=R.r,A+=z=R.g,w+=S=R.b,x+=T=R.a,M-=D,j-=z,N-=S,k-=T,R=R.next,f+=4;m+=n}for(h=0;n>h;h++){for(j=N=k=M=y=v=C=I=0,f=h<<2,b=_*(D=G[f]),A=_*(z=G[f+1]),w=_*(S=G[f+2]),x=_*(T=G[f+3]),I+=P*D,y+=P*z,v+=P*S,C+=P*T,Y=O,p=0;_>p;p++)Y.r=D,Y.g=z,Y.b=S,Y.a=T,Y=Y.next;for(d=n,p=1;a>=p;p++)f=d+h<<2,I+=(Y.r=D=G[f])*(E=_-p),y+=(Y.g=z=G[f+1])*E,v+=(Y.b=S=G[f+2])*E,C+=(Y.a=T=G[f+3])*E,M+=D,j+=z,N+=S,k+=T,Y=Y.next,Z>p&&(d+=n);for(f=h,V=O,R=W,u=0;r>u;u++)g=f<<2,G[g+3]=T=C*X>>U,T>0?(T=255/T,G[g]=(I*X>>U)*T,G[g+1]=(y*X>>U)*T,G[g+2]=(v*X>>U)*T):G[g]=G[g+1]=G[g+2]=0,I-=b,y-=A,v-=w,C-=x,b-=V.r,A-=V.g,w-=V.b,x-=V.a,g=h+(Z>(g=u+_)?g:Z)*n<<2,I+=M+=V.r=G[g],y+=j+=V.g=G[g+1],v+=N+=V.b=G[g+2],C+=k+=V.a=G[g+3],V=V.next,b+=D=R.r,A+=z=R.g,w+=S=R.b,x+=T=R.a,M-=D,j-=z,N-=S,k-=T,R=R.next,f+=n}l.putImageData(s,e,i)}}function stackBlurCanvasRGB(t,e,i,n,r,a){if(!(isNaN(a)||1>a)){a|=0;var s,o=document.getElementById(t),l=o.getContext("2d");try{try{s=l.getImageData(e,i,n,r)}catch(c){try{netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"),s=l.getImageData(e,i,n,r)}catch(c){throw alert("Cannot access local image"),Error("unable to access local image data: "+c)}}}catch(c){throw alert("Cannot access image"),Error("unable to access image data: "+c)}var h,u,p,g,d,f,m,I,y,v,C,b,A,w,x,M,j,N,k,D,z=s.data,S=a+a+1,T=n-1,E=r-1,G=a+1,L=G*(G+1)/2,B=new BlurStack,Z=B;for(p=1;S>p;p++)if(Z=Z.next=new BlurStack,p==G)var _=Z;Z.next=B;var P=null,O=null;m=f=0;var Y=mul_table[a],W=shg_table[a];for(u=0;r>u;u++){for(w=x=M=I=y=v=0,C=G*(j=z[f]),b=G*(N=z[f+1]),A=G*(k=z[f+2]),I+=L*j,y+=L*N,v+=L*k,Z=B,p=0;G>p;p++)Z.r=j,Z.g=N,Z.b=k,Z=Z.next;for(p=1;G>p;p++)g=f+((p>T?T:p)<<2),I+=(Z.r=j=z[g])*(D=G-p),y+=(Z.g=N=z[g+1])*D,v+=(Z.b=k=z[g+2])*D,w+=j,x+=N,M+=k,Z=Z.next;for(P=B,O=_,h=0;n>h;h++)z[f]=I*Y>>W,z[f+1]=y*Y>>W,z[f+2]=v*Y>>W,I-=C,y-=b,v-=A,C-=P.r,b-=P.g,A-=P.b,g=m+(T>(g=h+a+1)?g:T)<<2,w+=P.r=z[g],x+=P.g=z[g+1],M+=P.b=z[g+2],I+=w,y+=x,v+=M,P=P.next,C+=j=O.r,b+=N=O.g,A+=k=O.b,w-=j,x-=N,M-=k,O=O.next,f+=4;m+=n}for(h=0;n>h;h++){for(x=M=w=y=v=I=0,f=h<<2,C=G*(j=z[f]),b=G*(N=z[f+1]),A=G*(k=z[f+2]),I+=L*j,y+=L*N,v+=L*k,Z=B,p=0;G>p;p++)Z.r=j,Z.g=N,Z.b=k,Z=Z.next;for(d=n,p=1;a>=p;p++)f=d+h<<2,I+=(Z.r=j=z[f])*(D=G-p),y+=(Z.g=N=z[f+1])*D,v+=(Z.b=k=z[f+2])*D,w+=j,x+=N,M+=k,Z=Z.next,E>p&&(d+=n);for(f=h,P=B,O=_,u=0;r>u;u++)g=f<<2,z[g]=I*Y>>W,z[g+1]=y*Y>>W,z[g+2]=v*Y>>W,I-=C,y-=b,v-=A,C-=P.r,b-=P.g,A-=P.b,g=h+(E>(g=u+G)?g:E)*n<<2,I+=w+=P.r=z[g],y+=x+=P.g=z[g+1],v+=M+=P.b=z[g+2],P=P.next,C+=j=O.r,b+=N=O.g,A+=k=O.b,w-=j,x-=N,M-=k,O=O.next,f+=n}l.putImageData(s,e,i)}}function BlurStack(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}if(function(t,e){function i(t){var e=t.length,i=ae.type(t);return ae.isWindow(t)?!1:1===t.nodeType&&e?!0:"array"===i||"function"!==i&&(0===e||"number"==typeof e&&e>0&&e-1 in t)}function n(t){var e=de[t]={};return ae.each(t.match(oe)||[],function(t,i){e[i]=!0}),e}function r(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=ae.expando+Math.random()}function a(t,i,n){var r;if(n===e&&1===t.nodeType)if(r="data-"+i.replace(ye,"-$1").toLowerCase(),n=t.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Ie.test(n)?JSON.parse(n):n}catch(a){}fe.set(t,i,n)}else n=e;return n}function s(){return!0}function o(){return!1}function l(){try{return X.activeElement}catch(t){}}function c(t,e){for(;(t=t[e])&&1!==t.nodeType;);return t}function h(t,e,i){if(ae.isFunction(e))return ae.grep(t,function(t,n){return!!e.call(t,n,t)!==i});if(e.nodeType)return ae.grep(t,function(t){return t===e!==i});if("string"==typeof e){if(ke.test(e))return ae.filter(e,t,i);e=ae.filter(e,t)}return ae.grep(t,function(t){return ee.call(e,t)>=0!==i})}function u(t,e){return ae.nodeName(t,"table")&&ae.nodeName(1===e.nodeType?e:e.firstChild,"tr")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}function p(t){return t.type=(null!==t.getAttribute("type"))+"/"+t.type,t}function g(t){var e=Pe.exec(t.type);return e?t.type=e[1]:t.removeAttribute("type"),t}function d(t,e){for(var i=t.length,n=0;i>n;n++)me.set(t[n],"globalEval",!e||me.get(e[n],"globalEval"))}function f(t,e){var i,n,r,a,s,o,l,c;if(1===e.nodeType){if(me.hasData(t)&&(a=me.access(t),s=me.set(e,a),c=a.events)){delete s.handle,s.events={};for(r in c)for(i=0,n=c[r].length;n>i;i++)ae.event.add(e,r,c[r][i])}fe.hasData(t)&&(o=fe.access(t),l=ae.extend({},o),fe.set(e,l))}}function m(t,i){var n=t.getElementsByTagName?t.getElementsByTagName(i||"*"):t.querySelectorAll?t.querySelectorAll(i||"*"):[];return i===e||i&&ae.nodeName(t,i)?ae.merge([t],n):n}function I(t,e){var i=e.nodeName.toLowerCase();"input"===i&&Be.test(t.type)?e.checked=t.checked:("input"===i||"textarea"===i)&&(e.defaultValue=t.defaultValue)}function y(t,e){if(e in t)return e;for(var i=e.charAt(0).toUpperCase()+e.slice(1),n=e,r=qe.length;r--;)if(e=qe[r]+i,e in t)return e;return n}function v(t,e){return t=e||t,"none"===ae.css(t,"display")||!ae.contains(t.ownerDocument,t)}function C(e){return t.getComputedStyle(e,null)}function b(t,e){for(var i,n,r,a=[],s=0,o=t.length;o>s;s++)n=t[s],n.style&&(a[s]=me.get(n,"olddisplay"),i=n.style.display,e?(a[s]||"none"!==i||(n.style.display=""),""===n.style.display&&v(n)&&(a[s]=me.access(n,"olddisplay",M(n.nodeName)))):a[s]||(r=v(n),(i&&"none"!==i||!r)&&me.set(n,"olddisplay",r?i:ae.css(n,"display"))));for(s=0;o>s;s++)n=t[s],n.style&&(e&&"none"!==n.style.display&&""!==n.style.display||(n.style.display=e?a[s]||"":"none"));return t}function A(t,e,i){var n=Ue.exec(e);return n?Math.max(0,n[1]-(i||0))+(n[2]||"px"):e}function w(t,e,i,n,r){for(var a=i===(n?"border":"content")?4:"width"===e?1:0,s=0;4>a;a+=2)"margin"===i&&(s+=ae.css(t,i+Ke[a],!0,r)),n?("content"===i&&(s-=ae.css(t,"padding"+Ke[a],!0,r)),"margin"!==i&&(s-=ae.css(t,"border"+Ke[a]+"Width",!0,r))):(s+=ae.css(t,"padding"+Ke[a],!0,r),"padding"!==i&&(s+=ae.css(t,"border"+Ke[a]+"Width",!0,r)));return s}function x(t,e,i){var n=!0,r="width"===e?t.offsetWidth:t.offsetHeight,a=C(t),s=ae.support.boxSizing&&"border-box"===ae.css(t,"boxSizing",!1,a);if(0>=r||null==r){if(r=We(t,e,a),(0>r||null==r)&&(r=t.style[e]),He.test(r))return r;n=s&&(ae.support.boxSizingReliable||r===t.style[e]),r=parseFloat(r)||0}return r+w(t,e,i||(s?"border":"content"),n,a)+"px"}function M(t){var e=X,i=Je[t];return i||(i=j(t,e),"none"!==i&&i||(Ve=(Ve||ae("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(e.documentElement),e=(Ve[0].contentWindow||Ve[0].contentDocument).document,e.write("<!doctype html><html><body>"),e.close(),i=j(t,e),Ve.detach()),Je[t]=i),i}function j(t,e){var i=ae(e.createElement(t)).appendTo(e.body),n=ae.css(i[0],"display");return i.remove(),n}function N(t,e,i,n){var r;if(ae.isArray(e))ae.each(e,function(e,r){i||ei.test(t)?n(t,r):N(t+"["+("object"==typeof r?e:"")+"]",r,i,n)});else if(i||"object"!==ae.type(e))n(t,e);else for(r in e)N(t+"["+r+"]",e[r],i,n)}function k(t){return function(e,i){"string"!=typeof e&&(i=e,e="*");var n,r=0,a=e.toLowerCase().match(oe)||[];if(ae.isFunction(i))for(;n=a[r++];)"+"===n[0]?(n=n.slice(1)||"*",(t[n]=t[n]||[]).unshift(i)):(t[n]=t[n]||[]).push(i)}}function D(t,i,n,r){function a(l){var c;return s[l]=!0,ae.each(t[l]||[],function(t,l){var h=l(i,n,r);return"string"!=typeof h||o||s[h]?o?!(c=h):e:(i.dataTypes.unshift(h),a(h),!1)}),c}var s={},o=t===yi;return a(i.dataTypes[0])||!s["*"]&&a("*")}function z(t,i){var n,r,a=ae.ajaxSettings.flatOptions||{};for(n in i)i[n]!==e&&((a[n]?t:r||(r={}))[n]=i[n]);return r&&ae.extend(!0,t,r),t}function S(t,i,n){for(var r,a,s,o,l=t.contents,c=t.dataTypes;"*"===c[0];)c.shift(),r===e&&(r=t.mimeType||i.getResponseHeader("Content-Type"));if(r)for(a in l)if(l[a]&&l[a].test(r)){c.unshift(a);break}if(c[0]in n)s=c[0];else{for(a in n){if(!c[0]||t.converters[a+" "+c[0]]){s=a;break}o||(o=a)}s=s||o}return s?(s!==c[0]&&c.unshift(s),n[s]):e}function T(t,e,i,n){var r,a,s,o,l,c={},h=t.dataTypes.slice();if(h[1])for(s in t.converters)c[s.toLowerCase()]=t.converters[s];for(a=h.shift();a;)if(t.responseFields[a]&&(i[t.responseFields[a]]=e),!l&&n&&t.dataFilter&&(e=t.dataFilter(e,t.dataType)),l=a,a=h.shift())if("*"===a)a=l;else if("*"!==l&&l!==a){if(s=c[l+" "+a]||c["* "+a],!s)for(r in c)if(o=r.split(" "),o[1]===a&&(s=c[l+" "+o[0]]||c["* "+o[0]])){s===!0?s=c[r]:c[r]!==!0&&(a=o[0],h.unshift(o[1]));break}if(s!==!0)if(s&&t["throws"])e=s(e);else try{e=s(e)}catch(u){return{state:"parsererror",error:s?u:"No conversion from "+l+" to "+a}}}return{state:"success",data:e}}function E(){return setTimeout(function(){Ni=e}),Ni=ae.now()}function G(t,e,i){for(var n,r=(Ei[e]||[]).concat(Ei["*"]),a=0,s=r.length;s>a;a++)if(n=r[a].call(i,e,t))return n}function L(t,e,i){var n,r,a=0,s=Ti.length,o=ae.Deferred().always(function(){delete l.elem}),l=function(){if(r)return!1;for(var e=Ni||E(),i=Math.max(0,c.startTime+c.duration-e),n=i/c.duration||0,a=1-n,s=0,l=c.tweens.length;l>s;s++)c.tweens[s].run(a);return o.notifyWith(t,[c,a,i]),1>a&&l?i:(o.resolveWith(t,[c]),!1)},c=o.promise({elem:t,props:ae.extend({},e),opts:ae.extend(!0,{specialEasing:{}},i),originalProperties:e,originalOptions:i,startTime:Ni||E(),duration:i.duration,tweens:[],createTween:function(e,i){var n=ae.Tween(t,c.opts,e,i,c.opts.specialEasing[e]||c.opts.easing);return c.tweens.push(n),n},stop:function(e){var i=0,n=e?c.tweens.length:0;if(r)return this;for(r=!0;n>i;i++)c.tweens[i].run(1);return e?o.resolveWith(t,[c,e]):o.rejectWith(t,[c,e]),this}}),h=c.props;for(B(h,c.opts.specialEasing);s>a;a++)if(n=Ti[a].call(c,t,h,c.opts))return n;return ae.map(h,G,c),ae.isFunction(c.opts.start)&&c.opts.start.call(t,c),ae.fx.timer(ae.extend(l,{elem:t,anim:c,queue:c.opts.queue})),c.progress(c.opts.progress).done(c.opts.done,c.opts.complete).fail(c.opts.fail).always(c.opts.always)}function B(t,e){var i,n,r,a,s;for(i in t)if(n=ae.camelCase(i),r=e[n],a=t[i],ae.isArray(a)&&(r=a[1],a=t[i]=a[0]),i!==n&&(t[n]=a,delete t[i]),s=ae.cssHooks[n],s&&"expand"in s){a=s.expand(a),delete t[n];for(i in a)i in t||(t[i]=a[i],e[i]=r)}else e[n]=r}function Z(t,i,n){var r,a,s,o,l,c,h=this,u={},p=t.style,g=t.nodeType&&v(t),d=me.get(t,"fxshow");n.queue||(l=ae._queueHooks(t,"fx"),null==l.unqueued&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,ae.queue(t,"fx").length||l.empty.fire()})})),1===t.nodeType&&("height"in i||"width"in i)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===ae.css(t,"display")&&"none"===ae.css(t,"float")&&(p.display="inline-block")),n.overflow&&(p.overflow="hidden",h.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in i)if(a=i[r],Di.exec(a)){if(delete i[r],s=s||"toggle"===a,a===(g?"hide":"show")){if("show"!==a||!d||d[r]===e)continue;g=!0}u[r]=d&&d[r]||ae.style(t,r)}if(!ae.isEmptyObject(u)){d?"hidden"in d&&(g=d.hidden):d=me.access(t,"fxshow",{}),s&&(d.hidden=!g),g?ae(t).show():h.done(function(){ae(t).hide()}),h.done(function(){var e;me.remove(t,"fxshow");for(e in u)ae.style(t,e,u[e])});for(r in u)o=G(g?d[r]:0,r,h),r in d||(d[r]=o.start,g&&(o.end=o.start,o.start="width"===r||"height"===r?1:0))}}function _(t,e,i,n,r){return new _.prototype.init(t,e,i,n,r)}function P(t,e){var i,n={height:t},r=0;for(e=e?1:0;4>r;r+=2-e)i=Ke[r],n["margin"+i]=n["padding"+i]=t;return e&&(n.opacity=n.width=t),n}function O(t){return ae.isWindow(t)?t:9===t.nodeType&&t.defaultView}var Y,W,V=typeof e,R=t.location,X=t.document,U=X.documentElement,H=t.jQuery,F=t.$,J={},Q=[],$="2.0.3",K=Q.concat,q=Q.push,te=Q.slice,ee=Q.indexOf,ie=J.toString,ne=J.hasOwnProperty,re=$.trim,ae=function(t,e){return new ae.fn.init(t,e,Y)},se=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,oe=/\S+/g,le=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,ce=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,he=/^-ms-/,ue=/-([\da-z])/gi,pe=function(t,e){return e.toUpperCase()},ge=function(){X.removeEventListener("DOMContentLoaded",ge,!1),t.removeEventListener("load",ge,!1),ae.ready()};ae.fn=ae.prototype={jquery:$,constructor:ae,init:function(t,i,n){var r,a;if(!t)return this;if("string"==typeof t){if(r="<"===t.charAt(0)&&">"===t.charAt(t.length-1)&&t.length>=3?[null,t,null]:le.exec(t),!r||!r[1]&&i)return!i||i.jquery?(i||n).find(t):this.constructor(i).find(t);if(r[1]){if(i=i instanceof ae?i[0]:i,ae.merge(this,ae.parseHTML(r[1],i&&i.nodeType?i.ownerDocument||i:X,!0)),ce.test(r[1])&&ae.isPlainObject(i))for(r in i)ae.isFunction(this[r])?this[r](i[r]):this.attr(r,i[r]);return this}return a=X.getElementById(r[2]),a&&a.parentNode&&(this.length=1,this[0]=a),this.context=X,this.selector=t,this}return t.nodeType?(this.context=this[0]=t,this.length=1,this):ae.isFunction(t)?n.ready(t):(t.selector!==e&&(this.selector=t.selector,this.context=t.context),ae.makeArray(t,this))},selector:"",length:0,toArray:function(){return te.call(this)},get:function(t){return null==t?this.toArray():0>t?this[this.length+t]:this[t]},pushStack:function(t){var e=ae.merge(this.constructor(),t);return e.prevObject=this,e.context=this.context,e},each:function(t,e){return ae.each(this,t,e)},ready:function(t){return ae.ready.promise().done(t),this},slice:function(){return this.pushStack(te.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(t){var e=this.length,i=+t+(0>t?e:0);return this.pushStack(i>=0&&e>i?[this[i]]:[])},map:function(t){return this.pushStack(ae.map(this,function(e,i){return t.call(e,i,e)}))},end:function(){return this.prevObject||this.constructor(null)},push:q,sort:[].sort,splice:[].splice},ae.fn.init.prototype=ae.fn,ae.extend=ae.fn.extend=function(){var t,i,n,r,a,s,o=arguments[0]||{},l=1,c=arguments.length,h=!1;for("boolean"==typeof o&&(h=o,o=arguments[1]||{},l=2),"object"==typeof o||ae.isFunction(o)||(o={}),c===l&&(o=this,--l);c>l;l++)if(null!=(t=arguments[l]))for(i in t)n=o[i],r=t[i],o!==r&&(h&&r&&(ae.isPlainObject(r)||(a=ae.isArray(r)))?(a?(a=!1,s=n&&ae.isArray(n)?n:[]):s=n&&ae.isPlainObject(n)?n:{},o[i]=ae.extend(h,s,r)):r!==e&&(o[i]=r));return o},ae.extend({expando:"jQuery"+($+Math.random()).replace(/\D/g,""),noConflict:function(e){return t.$===ae&&(t.$=F),e&&t.jQuery===ae&&(t.jQuery=H),ae},isReady:!1,readyWait:1,holdReady:function(t){t?ae.readyWait++:ae.ready(!0)},ready:function(t){(t===!0?--ae.readyWait:ae.isReady)||(ae.isReady=!0,t!==!0&&--ae.readyWait>0||(W.resolveWith(X,[ae]),ae.fn.trigger&&ae(X).trigger("ready").off("ready")))},isFunction:function(t){return"function"===ae.type(t)},isArray:Array.isArray,isWindow:function(t){return null!=t&&t===t.window},isNumeric:function(t){return!isNaN(parseFloat(t))&&isFinite(t)},type:function(t){return null==t?t+"":"object"==typeof t||"function"==typeof t?J[ie.call(t)]||"object":typeof t},isPlainObject:function(t){if("object"!==ae.type(t)||t.nodeType||ae.isWindow(t))return!1;try{if(t.constructor&&!ne.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(e){return!1}return!0},isEmptyObject:function(t){var e;for(e in t)return!1;return!0},error:function(t){throw Error(t)},parseHTML:function(t,e,i){if(!t||"string"!=typeof t)return null;"boolean"==typeof e&&(i=e,e=!1),e=e||X;var n=ce.exec(t),r=!i&&[];return n?[e.createElement(n[1])]:(n=ae.buildFragment([t],e,r),r&&ae(r).remove(),ae.merge([],n.childNodes))},parseJSON:JSON.parse,parseXML:function(t){var i,n;if(!t||"string"!=typeof t)return null;try{n=new DOMParser,i=n.parseFromString(t,"text/xml")}catch(r){i=e}return(!i||i.getElementsByTagName("parsererror").length)&&ae.error("Invalid XML: "+t),i},noop:function(){},globalEval:function(t){var e,i=eval;t=ae.trim(t),t&&(1===t.indexOf("use strict")?(e=X.createElement("script"),e.text=t,X.head.appendChild(e).parentNode.removeChild(e)):i(t))},camelCase:function(t){return t.replace(he,"ms-").replace(ue,pe)},nodeName:function(t,e){return t.nodeName&&t.nodeName.toLowerCase()===e.toLowerCase()},each:function(t,e,n){var r,a=0,s=t.length,o=i(t);if(n){if(o)for(;s>a&&(r=e.apply(t[a],n),r!==!1);a++);else for(a in t)if(r=e.apply(t[a],n),r===!1)break}else if(o)for(;s>a&&(r=e.call(t[a],a,t[a]),r!==!1);a++);else for(a in t)if(r=e.call(t[a],a,t[a]),r===!1)break;return t},trim:function(t){return null==t?"":re.call(t)},makeArray:function(t,e){var n=e||[];return null!=t&&(i(Object(t))?ae.merge(n,"string"==typeof t?[t]:t):q.call(n,t)),n},inArray:function(t,e,i){return null==e?-1:ee.call(e,t,i)},merge:function(t,i){var n=i.length,r=t.length,a=0;if("number"==typeof n)for(;n>a;a++)t[r++]=i[a];else for(;i[a]!==e;)t[r++]=i[a++];return t.length=r,t},grep:function(t,e,i){var n,r=[],a=0,s=t.length;for(i=!!i;s>a;a++)n=!!e(t[a],a),i!==n&&r.push(t[a]);return r},map:function(t,e,n){var r,a=0,s=t.length,o=i(t),l=[];if(o)for(;s>a;a++)r=e(t[a],a,n),null!=r&&(l[l.length]=r);else for(a in t)r=e(t[a],a,n),null!=r&&(l[l.length]=r);return K.apply([],l)},guid:1,proxy:function(t,i){var n,r,a;return"string"==typeof i&&(n=t[i],i=t,t=n),ae.isFunction(t)?(r=te.call(arguments,2),a=function(){return t.apply(i||this,r.concat(te.call(arguments)))},a.guid=t.guid=t.guid||ae.guid++,a):e},access:function(t,i,n,r,a,s,o){var l=0,c=t.length,h=null==n;if("object"===ae.type(n)){a=!0;for(l in n)ae.access(t,i,l,n[l],!0,s,o)}else if(r!==e&&(a=!0,ae.isFunction(r)||(o=!0),h&&(o?(i.call(t,r),i=null):(h=i,i=function(t,e,i){return h.call(ae(t),i)})),i))for(;c>l;l++)i(t[l],n,o?r:r.call(t[l],l,i(t[l],n)));return a?t:h?i.call(t):c?i(t[0],n):s},now:Date.now,swap:function(t,e,i,n){var r,a,s={};for(a in e)s[a]=t.style[a],t.style[a]=e[a];r=i.apply(t,n||[]);for(a in e)t.style[a]=s[a];return r}}),ae.ready.promise=function(e){return W||(W=ae.Deferred(),"complete"===X.readyState?setTimeout(ae.ready):(X.addEventListener("DOMContentLoaded",ge,!1),t.addEventListener("load",ge,!1))),W.promise(e)},ae.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(t,e){J["[object "+e+"]"]=e.toLowerCase()}),Y=ae(X),function(t,e){function i(t,e,i,n){var r,a,s,o,l,c,h,u,d,f;if((e?e.ownerDocument||e:O)!==T&&S(e),e=e||T,i=i||[],!t||"string"!=typeof t)return i;if(1!==(o=e.nodeType)&&9!==o)return[];if(G&&!n){if(r=ve.exec(t))if(s=r[1]){if(9===o){if(a=e.getElementById(s),!a||!a.parentNode)return i;if(a.id===s)return i.push(a),i}else if(e.ownerDocument&&(a=e.ownerDocument.getElementById(s))&&_(e,a)&&a.id===s)return i.push(a),i}else{if(r[2])return te.apply(i,e.getElementsByTagName(t)),i;if((s=r[3])&&w.getElementsByClassName&&e.getElementsByClassName)return te.apply(i,e.getElementsByClassName(s)),i}if(w.qsa&&(!L||!L.test(t))){if(u=h=P,d=e,f=9===o&&t,1===o&&"object"!==e.nodeName.toLowerCase()){for(c=p(t),(h=e.getAttribute("id"))?u=h.replace(Ae,"\\$&"):e.setAttribute("id",u),u="[id='"+u+"'] ",l=c.length;l--;)c[l]=u+g(c[l]);d=ge.test(t)&&e.parentNode||e,f=c.join(",")}if(f)try{return te.apply(i,d.querySelectorAll(f)),i}catch(m){}finally{h||e.removeAttribute("id")}}}return b(t.replace(he,"$1"),e,i,n)}function n(){function t(i,n){return e.push(i+=" ")>M.cacheLength&&delete t[e.shift()],t[i]=n}var e=[];return t}function r(t){return t[P]=!0,t}function a(t){var e=T.createElement("div");try{return!!t(e)}catch(i){return!1}finally{e.parentNode&&e.parentNode.removeChild(e),e=null}}function s(t,e){for(var i=t.split("|"),n=t.length;n--;)M.attrHandle[i[n]]=e}function o(t,e){var i=e&&t,n=i&&1===t.nodeType&&1===e.nodeType&&(~e.sourceIndex||J)-(~t.sourceIndex||J);if(n)return n;if(i)for(;i=i.nextSibling;)if(i===e)return-1;return t?1:-1}function l(t){return function(e){var i=e.nodeName.toLowerCase();return"input"===i&&e.type===t}}function c(t){return function(e){var i=e.nodeName.toLowerCase();return("input"===i||"button"===i)&&e.type===t}}function h(t){return r(function(e){return e=+e,r(function(i,n){for(var r,a=t([],i.length,e),s=a.length;s--;)i[r=a[s]]&&(i[r]=!(n[r]=i[r]))})})}function u(){}function p(t,e){var n,r,a,s,o,l,c,h=R[t+" "];if(h)return e?0:h.slice(0);for(o=t,l=[],c=M.preFilter;o;){(!n||(r=ue.exec(o)))&&(r&&(o=o.slice(r[0].length)||o),l.push(a=[])),n=!1,(r=pe.exec(o))&&(n=r.shift(),a.push({value:n,type:r[0].replace(he," ")}),o=o.slice(n.length));for(s in M.filter)!(r=Ie[s].exec(o))||c[s]&&!(r=c[s](r))||(n=r.shift(),a.push({value:n,type:s,matches:r}),o=o.slice(n.length));if(!n)break}return e?o.length:o?i.error(t):R(t,l).slice(0)}function g(t){for(var e=0,i=t.length,n="";i>e;e++)n+=t[e].value;return n}function d(t,e,i){var n=e.dir,r=i&&"parentNode"===n,a=W++;return e.first?function(e,i,a){for(;e=e[n];)if(1===e.nodeType||r)return t(e,i,a)}:function(e,i,s){var o,l,c,h=Y+" "+a;if(s){for(;e=e[n];)if((1===e.nodeType||r)&&t(e,i,s))return!0}else for(;e=e[n];)if(1===e.nodeType||r)if(c=e[P]||(e[P]={}),(l=c[n])&&l[0]===h){if((o=l[1])===!0||o===x)return o===!0}else if(l=c[n]=[h],l[1]=t(e,i,s)||x,l[1]===!0)return!0}}function f(t){return t.length>1?function(e,i,n){for(var r=t.length;r--;)if(!t[r](e,i,n))return!1;return!0}:t[0]}function m(t,e,i,n,r){for(var a,s=[],o=0,l=t.length,c=null!=e;l>o;o++)(a=t[o])&&(!i||i(a,n,r))&&(s.push(a),c&&e.push(o));return s}function I(t,e,i,n,a,s){return n&&!n[P]&&(n=I(n)),a&&!a[P]&&(a=I(a,s)),r(function(r,s,o,l){var c,h,u,p=[],g=[],d=s.length,f=r||C(e||"*",o.nodeType?[o]:o,[]),I=!t||!r&&e?f:m(f,p,t,o,l),y=i?a||(r?t:d||n)?[]:s:I;if(i&&i(I,y,o,l),n)for(c=m(y,g),n(c,[],o,l),h=c.length;h--;)(u=c[h])&&(y[g[h]]=!(I[g[h]]=u));if(r){if(a||t){if(a){for(c=[],h=y.length;h--;)(u=y[h])&&c.push(I[h]=u);a(null,y=[],c,l)}for(h=y.length;h--;)(u=y[h])&&(c=a?ie.call(r,u):p[h])>-1&&(r[c]=!(s[c]=u))}}else y=m(y===s?y.splice(d,y.length):y),a?a(null,s,y,l):te.apply(s,y)})}function y(t){for(var e,i,n,r=t.length,a=M.relative[t[0].type],s=a||M.relative[" "],o=a?1:0,l=d(function(t){return t===e},s,!0),c=d(function(t){return ie.call(e,t)>-1},s,!0),h=[function(t,i,n){return!a&&(n||i!==D)||((e=i).nodeType?l(t,i,n):c(t,i,n))}];r>o;o++)if(i=M.relative[t[o].type])h=[d(f(h),i)];else{if(i=M.filter[t[o].type].apply(null,t[o].matches),i[P]){for(n=++o;r>n&&!M.relative[t[n].type];n++);return I(o>1&&f(h),o>1&&g(t.slice(0,o-1).concat({value:" "===t[o-2].type?"*":""})).replace(he,"$1"),i,n>o&&y(t.slice(o,n)),r>n&&y(t=t.slice(n)),r>n&&g(t))}h.push(i)}return f(h)}function v(t,e){var n=0,a=e.length>0,s=t.length>0,o=function(r,o,l,c,h){var u,p,g,d=[],f=0,I="0",y=r&&[],v=null!=h,C=D,b=r||s&&M.find.TAG("*",h&&o.parentNode||o),A=Y+=null==C?1:Math.random()||.1;for(v&&(D=o!==T&&o,x=n);null!=(u=b[I]);I++){if(s&&u){for(p=0;g=t[p++];)if(g(u,o,l)){c.push(u);break}v&&(Y=A,x=++n)}a&&((u=!g&&u)&&f--,r&&y.push(u))}if(f+=I,a&&I!==f){for(p=0;g=e[p++];)g(y,d,o,l);if(r){if(f>0)for(;I--;)y[I]||d[I]||(d[I]=K.call(c));d=m(d)}te.apply(c,d),v&&!r&&d.length>0&&f+e.length>1&&i.uniqueSort(c)}return v&&(Y=A,D=C),y};return a?r(o):o}function C(t,e,n){for(var r=0,a=e.length;a>r;r++)i(t,e[r],n);return n}function b(t,e,i,n){var r,a,s,o,l,c=p(t);if(!n&&1===c.length){if(a=c[0]=c[0].slice(0),a.length>2&&"ID"===(s=a[0]).type&&w.getById&&9===e.nodeType&&G&&M.relative[a[1].type]){if(e=(M.find.ID(s.matches[0].replace(we,xe),e)||[])[0],!e)return i;t=t.slice(a.shift().value.length)}for(r=Ie.needsContext.test(t)?0:a.length;r--&&(s=a[r],!M.relative[o=s.type]);)if((l=M.find[o])&&(n=l(s.matches[0].replace(we,xe),ge.test(a[0].type)&&e.parentNode||e))){if(a.splice(r,1),t=n.length&&g(a),!t)return te.apply(i,n),i;break}}return k(t,c)(n,e,!G,i,ge.test(t)),i}var A,w,x,M,j,N,k,D,z,S,T,E,G,L,B,Z,_,P="sizzle"+-new Date,O=t.document,Y=0,W=0,V=n(),R=n(),X=n(),U=!1,H=function(t,e){return t===e?(U=!0,0):0},F=typeof e,J=1<<31,Q={}.hasOwnProperty,$=[],K=$.pop,q=$.push,te=$.push,ee=$.slice,ie=$.indexOf||function(t){for(var e=0,i=this.length;i>e;e++)if(this[e]===t)return e;return-1},ne="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",re="[\\x20\\t\\r\\n\\f]",se="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",oe=se.replace("w","w#"),le="\\["+re+"*("+se+")"+re+"*(?:([*^$|!~]?=)"+re+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+oe+")|)|)"+re+"*\\]",ce=":("+se+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+le.replace(3,8)+")*)|.*)\\)|)",he=RegExp("^"+re+"+|((?:^|[^\\\\])(?:\\\\.)*)"+re+"+$","g"),ue=RegExp("^"+re+"*,"+re+"*"),pe=RegExp("^"+re+"*([>+~]|"+re+")"+re+"*"),ge=RegExp(re+"*[+~]"),de=RegExp("="+re+"*([^\\]'\"]*)"+re+"*\\]","g"),fe=RegExp(ce),me=RegExp("^"+oe+"$"),Ie={ID:RegExp("^#("+se+")"),CLASS:RegExp("^\\.("+se+")"),TAG:RegExp("^("+se.replace("w","w*")+")"),ATTR:RegExp("^"+le),PSEUDO:RegExp("^"+ce),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+re+"*(even|odd|(([+-]|)(\\d*)n|)"+re+"*(?:([+-]|)"+re+"*(\\d+)|))"+re+"*\\)|)","i"),bool:RegExp("^(?:"+ne+")$","i"),needsContext:RegExp("^"+re+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+re+"*((?:-\\d)?\\d*)"+re+"*\\)|)(?=[^-]|$)","i")},ye=/^[^{]+\{\s*\[native \w/,ve=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Ce=/^(?:input|select|textarea|button)$/i,be=/^h\d$/i,Ae=/'|\\/g,we=RegExp("\\\\([\\da-f]{1,6}"+re+"?|("+re+")|.)","ig"),xe=function(t,e,i){var n="0x"+e-65536;return n!==n||i?e:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{te.apply($=ee.call(O.childNodes),O.childNodes),$[O.childNodes.length].nodeType}catch(Me){te={apply:$.length?function(t,e){q.apply(t,ee.call(e))}:function(t,e){for(var i=t.length,n=0;t[i++]=e[n++];);t.length=i-1}}}N=i.isXML=function(t){var e=t&&(t.ownerDocument||t).documentElement;return e?"HTML"!==e.nodeName:!1},w=i.support={},S=i.setDocument=function(t){var i=t?t.ownerDocument||t:O,n=i.defaultView;return i!==T&&9===i.nodeType&&i.documentElement?(T=i,E=i.documentElement,G=!N(i),n&&n.attachEvent&&n!==n.top&&n.attachEvent("onbeforeunload",function(){S()}),w.attributes=a(function(t){return t.className="i",!t.getAttribute("className")}),w.getElementsByTagName=a(function(t){return t.appendChild(i.createComment("")),!t.getElementsByTagName("*").length}),w.getElementsByClassName=a(function(t){return t.innerHTML="<div class='a'></div><div class='a i'></div>",t.firstChild.className="i",2===t.getElementsByClassName("i").length
+}),w.getById=a(function(t){return E.appendChild(t).id=P,!i.getElementsByName||!i.getElementsByName(P).length}),w.getById?(M.find.ID=function(t,e){if(typeof e.getElementById!==F&&G){var i=e.getElementById(t);return i&&i.parentNode?[i]:[]}},M.filter.ID=function(t){var e=t.replace(we,xe);return function(t){return t.getAttribute("id")===e}}):(delete M.find.ID,M.filter.ID=function(t){var e=t.replace(we,xe);return function(t){var i=typeof t.getAttributeNode!==F&&t.getAttributeNode("id");return i&&i.value===e}}),M.find.TAG=w.getElementsByTagName?function(t,i){return typeof i.getElementsByTagName!==F?i.getElementsByTagName(t):e}:function(t,e){var i,n=[],r=0,a=e.getElementsByTagName(t);if("*"===t){for(;i=a[r++];)1===i.nodeType&&n.push(i);return n}return a},M.find.CLASS=w.getElementsByClassName&&function(t,i){return typeof i.getElementsByClassName!==F&&G?i.getElementsByClassName(t):e},B=[],L=[],(w.qsa=ye.test(i.querySelectorAll))&&(a(function(t){t.innerHTML="<select><option selected=''></option></select>",t.querySelectorAll("[selected]").length||L.push("\\["+re+"*(?:value|"+ne+")"),t.querySelectorAll(":checked").length||L.push(":checked")}),a(function(t){var e=i.createElement("input");e.setAttribute("type","hidden"),t.appendChild(e).setAttribute("t",""),t.querySelectorAll("[t^='']").length&&L.push("[*^$]="+re+"*(?:''|\"\")"),t.querySelectorAll(":enabled").length||L.push(":enabled",":disabled"),t.querySelectorAll("*,:x"),L.push(",.*:")})),(w.matchesSelector=ye.test(Z=E.webkitMatchesSelector||E.mozMatchesSelector||E.oMatchesSelector||E.msMatchesSelector))&&a(function(t){w.disconnectedMatch=Z.call(t,"div"),Z.call(t,"[s!='']:x"),B.push("!=",ce)}),L=L.length&&RegExp(L.join("|")),B=B.length&&RegExp(B.join("|")),_=ye.test(E.contains)||E.compareDocumentPosition?function(t,e){var i=9===t.nodeType?t.documentElement:t,n=e&&e.parentNode;return t===n||!(!n||1!==n.nodeType||!(i.contains?i.contains(n):t.compareDocumentPosition&&16&t.compareDocumentPosition(n)))}:function(t,e){if(e)for(;e=e.parentNode;)if(e===t)return!0;return!1},H=E.compareDocumentPosition?function(t,e){if(t===e)return U=!0,0;var n=e.compareDocumentPosition&&t.compareDocumentPosition&&t.compareDocumentPosition(e);return n?1&n||!w.sortDetached&&e.compareDocumentPosition(t)===n?t===i||_(O,t)?-1:e===i||_(O,e)?1:z?ie.call(z,t)-ie.call(z,e):0:4&n?-1:1:t.compareDocumentPosition?-1:1}:function(t,e){var n,r=0,a=t.parentNode,s=e.parentNode,l=[t],c=[e];if(t===e)return U=!0,0;if(!a||!s)return t===i?-1:e===i?1:a?-1:s?1:z?ie.call(z,t)-ie.call(z,e):0;if(a===s)return o(t,e);for(n=t;n=n.parentNode;)l.unshift(n);for(n=e;n=n.parentNode;)c.unshift(n);for(;l[r]===c[r];)r++;return r?o(l[r],c[r]):l[r]===O?-1:c[r]===O?1:0},i):T},i.matches=function(t,e){return i(t,null,null,e)},i.matchesSelector=function(t,e){if((t.ownerDocument||t)!==T&&S(t),e=e.replace(de,"='$1']"),!(!w.matchesSelector||!G||B&&B.test(e)||L&&L.test(e)))try{var n=Z.call(t,e);if(n||w.disconnectedMatch||t.document&&11!==t.document.nodeType)return n}catch(r){}return i(e,T,null,[t]).length>0},i.contains=function(t,e){return(t.ownerDocument||t)!==T&&S(t),_(t,e)},i.attr=function(t,i){(t.ownerDocument||t)!==T&&S(t);var n=M.attrHandle[i.toLowerCase()],r=n&&Q.call(M.attrHandle,i.toLowerCase())?n(t,i,!G):e;return r===e?w.attributes||!G?t.getAttribute(i):(r=t.getAttributeNode(i))&&r.specified?r.value:null:r},i.error=function(t){throw Error("Syntax error, unrecognized expression: "+t)},i.uniqueSort=function(t){var e,i=[],n=0,r=0;if(U=!w.detectDuplicates,z=!w.sortStable&&t.slice(0),t.sort(H),U){for(;e=t[r++];)e===t[r]&&(n=i.push(r));for(;n--;)t.splice(i[n],1)}return t},j=i.getText=function(t){var e,i="",n=0,r=t.nodeType;if(r){if(1===r||9===r||11===r){if("string"==typeof t.textContent)return t.textContent;for(t=t.firstChild;t;t=t.nextSibling)i+=j(t)}else if(3===r||4===r)return t.nodeValue}else for(;e=t[n];n++)i+=j(e);return i},M=i.selectors={cacheLength:50,createPseudo:r,match:Ie,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){return t[1]=t[1].replace(we,xe),t[3]=(t[4]||t[5]||"").replace(we,xe),"~="===t[2]&&(t[3]=" "+t[3]+" "),t.slice(0,4)},CHILD:function(t){return t[1]=t[1].toLowerCase(),"nth"===t[1].slice(0,3)?(t[3]||i.error(t[0]),t[4]=+(t[4]?t[5]+(t[6]||1):2*("even"===t[3]||"odd"===t[3])),t[5]=+(t[7]+t[8]||"odd"===t[3])):t[3]&&i.error(t[0]),t},PSEUDO:function(t){var i,n=!t[5]&&t[2];return Ie.CHILD.test(t[0])?null:(t[3]&&t[4]!==e?t[2]=t[4]:n&&fe.test(n)&&(i=p(n,!0))&&(i=n.indexOf(")",n.length-i)-n.length)&&(t[0]=t[0].slice(0,i),t[2]=n.slice(0,i)),t.slice(0,3))}},filter:{TAG:function(t){var e=t.replace(we,xe).toLowerCase();return"*"===t?function(){return!0}:function(t){return t.nodeName&&t.nodeName.toLowerCase()===e}},CLASS:function(t){var e=V[t+" "];return e||(e=RegExp("(^|"+re+")"+t+"("+re+"|$)"))&&V(t,function(t){return e.test("string"==typeof t.className&&t.className||typeof t.getAttribute!==F&&t.getAttribute("class")||"")})},ATTR:function(t,e,n){return function(r){var a=i.attr(r,t);return null==a?"!="===e:e?(a+="","="===e?a===n:"!="===e?a!==n:"^="===e?n&&0===a.indexOf(n):"*="===e?n&&a.indexOf(n)>-1:"$="===e?n&&a.slice(-n.length)===n:"~="===e?(" "+a+" ").indexOf(n)>-1:"|="===e?a===n||a.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(t,e,i,n,r){var a="nth"!==t.slice(0,3),s="last"!==t.slice(-4),o="of-type"===e;return 1===n&&0===r?function(t){return!!t.parentNode}:function(e,i,l){var c,h,u,p,g,d,f=a!==s?"nextSibling":"previousSibling",m=e.parentNode,I=o&&e.nodeName.toLowerCase(),y=!l&&!o;if(m){if(a){for(;f;){for(u=e;u=u[f];)if(o?u.nodeName.toLowerCase()===I:1===u.nodeType)return!1;d=f="only"===t&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&y){for(h=m[P]||(m[P]={}),c=h[t]||[],g=c[0]===Y&&c[1],p=c[0]===Y&&c[2],u=g&&m.childNodes[g];u=++g&&u&&u[f]||(p=g=0)||d.pop();)if(1===u.nodeType&&++p&&u===e){h[t]=[Y,g,p];break}}else if(y&&(c=(e[P]||(e[P]={}))[t])&&c[0]===Y)p=c[1];else for(;(u=++g&&u&&u[f]||(p=g=0)||d.pop())&&((o?u.nodeName.toLowerCase()!==I:1!==u.nodeType)||!++p||(y&&((u[P]||(u[P]={}))[t]=[Y,p]),u!==e)););return p-=r,p===n||0===p%n&&p/n>=0}}},PSEUDO:function(t,e){var n,a=M.pseudos[t]||M.setFilters[t.toLowerCase()]||i.error("unsupported pseudo: "+t);return a[P]?a(e):a.length>1?(n=[t,t,"",e],M.setFilters.hasOwnProperty(t.toLowerCase())?r(function(t,i){for(var n,r=a(t,e),s=r.length;s--;)n=ie.call(t,r[s]),t[n]=!(i[n]=r[s])}):function(t){return a(t,0,n)}):a}},pseudos:{not:r(function(t){var e=[],i=[],n=k(t.replace(he,"$1"));return n[P]?r(function(t,e,i,r){for(var a,s=n(t,null,r,[]),o=t.length;o--;)(a=s[o])&&(t[o]=!(e[o]=a))}):function(t,r,a){return e[0]=t,n(e,null,a,i),!i.pop()}}),has:r(function(t){return function(e){return i(t,e).length>0}}),contains:r(function(t){return function(e){return(e.textContent||e.innerText||j(e)).indexOf(t)>-1}}),lang:r(function(t){return me.test(t||"")||i.error("unsupported lang: "+t),t=t.replace(we,xe).toLowerCase(),function(e){var i;do if(i=G?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return i=i.toLowerCase(),i===t||0===i.indexOf(t+"-");while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var i=t.location&&t.location.hash;return i&&i.slice(1)===e.id},root:function(t){return t===E},focus:function(t){return t===T.activeElement&&(!T.hasFocus||T.hasFocus())&&!!(t.type||t.href||~t.tabIndex)},enabled:function(t){return t.disabled===!1},disabled:function(t){return t.disabled===!0},checked:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&!!t.checked||"option"===e&&!!t.selected},selected:function(t){return t.parentNode&&t.parentNode.selectedIndex,t.selected===!0},empty:function(t){for(t=t.firstChild;t;t=t.nextSibling)if(t.nodeName>"@"||3===t.nodeType||4===t.nodeType)return!1;return!0},parent:function(t){return!M.pseudos.empty(t)},header:function(t){return be.test(t.nodeName)},input:function(t){return Ce.test(t.nodeName)},button:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&"button"===t.type||"button"===e},text:function(t){var e;return"input"===t.nodeName.toLowerCase()&&"text"===t.type&&(null==(e=t.getAttribute("type"))||e.toLowerCase()===t.type)},first:h(function(){return[0]}),last:h(function(t,e){return[e-1]}),eq:h(function(t,e,i){return[0>i?i+e:i]}),even:h(function(t,e){for(var i=0;e>i;i+=2)t.push(i);return t}),odd:h(function(t,e){for(var i=1;e>i;i+=2)t.push(i);return t}),lt:h(function(t,e,i){for(var n=0>i?i+e:i;--n>=0;)t.push(n);return t}),gt:h(function(t,e,i){for(var n=0>i?i+e:i;e>++n;)t.push(n);return t})}},M.pseudos.nth=M.pseudos.eq;for(A in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})M.pseudos[A]=l(A);for(A in{submit:!0,reset:!0})M.pseudos[A]=c(A);u.prototype=M.filters=M.pseudos,M.setFilters=new u,k=i.compile=function(t,e){var i,n=[],r=[],a=X[t+" "];if(!a){for(e||(e=p(t)),i=e.length;i--;)a=y(e[i]),a[P]?n.push(a):r.push(a);a=X(t,v(r,n))}return a},w.sortStable=P.split("").sort(H).join("")===P,w.detectDuplicates=U,S(),w.sortDetached=a(function(t){return 1&t.compareDocumentPosition(T.createElement("div"))}),a(function(t){return t.innerHTML="<a href='#'></a>","#"===t.firstChild.getAttribute("href")})||s("type|href|height|width",function(t,i,n){return n?e:t.getAttribute(i,"type"===i.toLowerCase()?1:2)}),w.attributes&&a(function(t){return t.innerHTML="<input/>",t.firstChild.setAttribute("value",""),""===t.firstChild.getAttribute("value")})||s("value",function(t,i,n){return n||"input"!==t.nodeName.toLowerCase()?e:t.defaultValue}),a(function(t){return null==t.getAttribute("disabled")})||s(ne,function(t,i,n){var r;return n?e:(r=t.getAttributeNode(i))&&r.specified?r.value:t[i]===!0?i.toLowerCase():null}),ae.find=i,ae.expr=i.selectors,ae.expr[":"]=ae.expr.pseudos,ae.unique=i.uniqueSort,ae.text=i.getText,ae.isXMLDoc=i.isXML,ae.contains=i.contains}(t);var de={};ae.Callbacks=function(t){t="string"==typeof t?de[t]||n(t):ae.extend({},t);var i,r,a,s,o,l,c=[],h=!t.once&&[],u=function(e){for(i=t.memory&&e,r=!0,l=s||0,s=0,o=c.length,a=!0;c&&o>l;l++)if(c[l].apply(e[0],e[1])===!1&&t.stopOnFalse){i=!1;break}a=!1,c&&(h?h.length&&u(h.shift()):i?c=[]:p.disable())},p={add:function(){if(c){var e=c.length;(function n(e){ae.each(e,function(e,i){var r=ae.type(i);"function"===r?t.unique&&p.has(i)||c.push(i):i&&i.length&&"string"!==r&&n(i)})})(arguments),a?o=c.length:i&&(s=e,u(i))}return this},remove:function(){return c&&ae.each(arguments,function(t,e){for(var i;(i=ae.inArray(e,c,i))>-1;)c.splice(i,1),a&&(o>=i&&o--,l>=i&&l--)}),this},has:function(t){return t?ae.inArray(t,c)>-1:!(!c||!c.length)},empty:function(){return c=[],o=0,this},disable:function(){return c=h=i=e,this},disabled:function(){return!c},lock:function(){return h=e,i||p.disable(),this},locked:function(){return!h},fireWith:function(t,e){return!c||r&&!h||(e=e||[],e=[t,e.slice?e.slice():e],a?h.push(e):u(e)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!r}};return p},ae.extend({Deferred:function(t){var e=[["resolve","done",ae.Callbacks("once memory"),"resolved"],["reject","fail",ae.Callbacks("once memory"),"rejected"],["notify","progress",ae.Callbacks("memory")]],i="pending",n={state:function(){return i},always:function(){return r.done(arguments).fail(arguments),this},then:function(){var t=arguments;return ae.Deferred(function(i){ae.each(e,function(e,a){var s=a[0],o=ae.isFunction(t[e])&&t[e];r[a[1]](function(){var t=o&&o.apply(this,arguments);t&&ae.isFunction(t.promise)?t.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[s+"With"](this===n?i.promise():this,o?[t]:arguments)})}),t=null}).promise()},promise:function(t){return null!=t?ae.extend(t,n):n}},r={};return n.pipe=n.then,ae.each(e,function(t,a){var s=a[2],o=a[3];n[a[1]]=s.add,o&&s.add(function(){i=o},e[1^t][2].disable,e[2][2].lock),r[a[0]]=function(){return r[a[0]+"With"](this===r?n:this,arguments),this},r[a[0]+"With"]=s.fireWith}),n.promise(r),t&&t.call(r,r),r},when:function(t){var e,i,n,r=0,a=te.call(arguments),s=a.length,o=1!==s||t&&ae.isFunction(t.promise)?s:0,l=1===o?t:ae.Deferred(),c=function(t,i,n){return function(r){i[t]=this,n[t]=arguments.length>1?te.call(arguments):r,n===e?l.notifyWith(i,n):--o||l.resolveWith(i,n)}};if(s>1)for(e=Array(s),i=Array(s),n=Array(s);s>r;r++)a[r]&&ae.isFunction(a[r].promise)?a[r].promise().done(c(r,n,a)).fail(l.reject).progress(c(r,i,e)):--o;return o||l.resolveWith(n,a),l.promise()}}),ae.support=function(e){var i=X.createElement("input"),n=X.createDocumentFragment(),r=X.createElement("div"),a=X.createElement("select"),s=a.appendChild(X.createElement("option"));return i.type?(i.type="checkbox",e.checkOn=""!==i.value,e.optSelected=s.selected,e.reliableMarginRight=!0,e.boxSizingReliable=!0,e.pixelPosition=!1,i.checked=!0,e.noCloneChecked=i.cloneNode(!0).checked,a.disabled=!0,e.optDisabled=!s.disabled,i=X.createElement("input"),i.value="t",i.type="radio",e.radioValue="t"===i.value,i.setAttribute("checked","t"),i.setAttribute("name","t"),n.appendChild(i),e.checkClone=n.cloneNode(!0).cloneNode(!0).lastChild.checked,e.focusinBubbles="onfocusin"in t,r.style.backgroundClip="content-box",r.cloneNode(!0).style.backgroundClip="",e.clearCloneStyle="content-box"===r.style.backgroundClip,ae(function(){var i,n,a="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",s=X.getElementsByTagName("body")[0];s&&(i=X.createElement("div"),i.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",s.appendChild(i).appendChild(r),r.innerHTML="",r.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",ae.swap(s,null!=s.style.zoom?{zoom:1}:{},function(){e.boxSizing=4===r.offsetWidth}),t.getComputedStyle&&(e.pixelPosition="1%"!==(t.getComputedStyle(r,null)||{}).top,e.boxSizingReliable="4px"===(t.getComputedStyle(r,null)||{width:"4px"}).width,n=r.appendChild(X.createElement("div")),n.style.cssText=r.style.cssText=a,n.style.marginRight=n.style.width="0",r.style.width="1px",e.reliableMarginRight=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight)),s.removeChild(i))}),e):e}({});var fe,me,Ie=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,ye=/([A-Z])/g;r.uid=1,r.accepts=function(t){return t.nodeType?1===t.nodeType||9===t.nodeType:!0},r.prototype={key:function(t){if(!r.accepts(t))return 0;var e={},i=t[this.expando];if(!i){i=r.uid++;try{e[this.expando]={value:i},Object.defineProperties(t,e)}catch(n){e[this.expando]=i,ae.extend(t,e)}}return this.cache[i]||(this.cache[i]={}),i},set:function(t,e,i){var n,r=this.key(t),a=this.cache[r];if("string"==typeof e)a[e]=i;else if(ae.isEmptyObject(a))ae.extend(this.cache[r],e);else for(n in e)a[n]=e[n];return a},get:function(t,i){var n=this.cache[this.key(t)];return i===e?n:n[i]},access:function(t,i,n){var r;return i===e||i&&"string"==typeof i&&n===e?(r=this.get(t,i),r!==e?r:this.get(t,ae.camelCase(i))):(this.set(t,i,n),n!==e?n:i)},remove:function(t,i){var n,r,a,s=this.key(t),o=this.cache[s];if(i===e)this.cache[s]={};else{ae.isArray(i)?r=i.concat(i.map(ae.camelCase)):(a=ae.camelCase(i),i in o?r=[i,a]:(r=a,r=r in o?[r]:r.match(oe)||[])),n=r.length;for(;n--;)delete o[r[n]]}},hasData:function(t){return!ae.isEmptyObject(this.cache[t[this.expando]]||{})},discard:function(t){t[this.expando]&&delete this.cache[t[this.expando]]}},fe=new r,me=new r,ae.extend({acceptData:r.accepts,hasData:function(t){return fe.hasData(t)||me.hasData(t)},data:function(t,e,i){return fe.access(t,e,i)},removeData:function(t,e){fe.remove(t,e)},_data:function(t,e,i){return me.access(t,e,i)},_removeData:function(t,e){me.remove(t,e)}}),ae.fn.extend({data:function(t,i){var n,r,s=this[0],o=0,l=null;if(t===e){if(this.length&&(l=fe.get(s),1===s.nodeType&&!me.get(s,"hasDataAttrs"))){for(n=s.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=ae.camelCase(r.slice(5)),a(s,r,l[r]));me.set(s,"hasDataAttrs",!0)}return l}return"object"==typeof t?this.each(function(){fe.set(this,t)}):ae.access(this,function(i){var n,r=ae.camelCase(t);if(s&&i===e){if(n=fe.get(s,t),n!==e)return n;if(n=fe.get(s,r),n!==e)return n;if(n=a(s,r,e),n!==e)return n}else this.each(function(){var n=fe.get(this,r);fe.set(this,r,i),-1!==t.indexOf("-")&&n!==e&&fe.set(this,t,i)})},null,i,arguments.length>1,null,!0)},removeData:function(t){return this.each(function(){fe.remove(this,t)})}}),ae.extend({queue:function(t,i,n){var r;return t?(i=(i||"fx")+"queue",r=me.get(t,i),n&&(!r||ae.isArray(n)?r=me.access(t,i,ae.makeArray(n)):r.push(n)),r||[]):e},dequeue:function(t,e){e=e||"fx";var i=ae.queue(t,e),n=i.length,r=i.shift(),a=ae._queueHooks(t,e),s=function(){ae.dequeue(t,e)};"inprogress"===r&&(r=i.shift(),n--),r&&("fx"===e&&i.unshift("inprogress"),delete a.stop,r.call(t,s,a)),!n&&a&&a.empty.fire()},_queueHooks:function(t,e){var i=e+"queueHooks";return me.get(t,i)||me.access(t,i,{empty:ae.Callbacks("once memory").add(function(){me.remove(t,[e+"queue",i])})})}}),ae.fn.extend({queue:function(t,i){var n=2;return"string"!=typeof t&&(i=t,t="fx",n--),n>arguments.length?ae.queue(this[0],t):i===e?this:this.each(function(){var e=ae.queue(this,t,i);ae._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&ae.dequeue(this,t)})},dequeue:function(t){return this.each(function(){ae.dequeue(this,t)})},delay:function(t,e){return t=ae.fx?ae.fx.speeds[t]||t:t,e=e||"fx",this.queue(e,function(e,i){var n=setTimeout(e,t);i.stop=function(){clearTimeout(n)}})},clearQueue:function(t){return this.queue(t||"fx",[])},promise:function(t,i){var n,r=1,a=ae.Deferred(),s=this,o=this.length,l=function(){--r||a.resolveWith(s,[s])};for("string"!=typeof t&&(i=t,t=e),t=t||"fx";o--;)n=me.get(s[o],t+"queueHooks"),n&&n.empty&&(r++,n.empty.add(l));return l(),a.promise(i)}});var ve,Ce,be=/[\t\r\n\f]/g,Ae=/\r/g,we=/^(?:input|select|textarea|button)$/i;ae.fn.extend({attr:function(t,e){return ae.access(this,ae.attr,t,e,arguments.length>1)},removeAttr:function(t){return this.each(function(){ae.removeAttr(this,t)})},prop:function(t,e){return ae.access(this,ae.prop,t,e,arguments.length>1)},removeProp:function(t){return this.each(function(){delete this[ae.propFix[t]||t]})},addClass:function(t){var e,i,n,r,a,s=0,o=this.length,l="string"==typeof t&&t;if(ae.isFunction(t))return this.each(function(e){ae(this).addClass(t.call(this,e,this.className))});if(l)for(e=(t||"").match(oe)||[];o>s;s++)if(i=this[s],n=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(be," "):" ")){for(a=0;r=e[a++];)0>n.indexOf(" "+r+" ")&&(n+=r+" ");i.className=ae.trim(n)}return this},removeClass:function(t){var e,i,n,r,a,s=0,o=this.length,l=0===arguments.length||"string"==typeof t&&t;if(ae.isFunction(t))return this.each(function(e){ae(this).removeClass(t.call(this,e,this.className))});if(l)for(e=(t||"").match(oe)||[];o>s;s++)if(i=this[s],n=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(be," "):"")){for(a=0;r=e[a++];)for(;n.indexOf(" "+r+" ")>=0;)n=n.replace(" "+r+" "," ");i.className=t?ae.trim(n):""}return this},toggleClass:function(t,e){var i=typeof t;return"boolean"==typeof e&&"string"===i?e?this.addClass(t):this.removeClass(t):ae.isFunction(t)?this.each(function(i){ae(this).toggleClass(t.call(this,i,this.className,e),e)}):this.each(function(){if("string"===i)for(var e,n=0,r=ae(this),a=t.match(oe)||[];e=a[n++];)r.hasClass(e)?r.removeClass(e):r.addClass(e);else(i===V||"boolean"===i)&&(this.className&&me.set(this,"__className__",this.className),this.className=this.className||t===!1?"":me.get(this,"__className__")||"")})},hasClass:function(t){for(var e=" "+t+" ",i=0,n=this.length;n>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(be," ").indexOf(e)>=0)return!0;return!1},val:function(t){var i,n,r,a=this[0];{if(arguments.length)return r=ae.isFunction(t),this.each(function(n){var a;1===this.nodeType&&(a=r?t.call(this,n,ae(this).val()):t,null==a?a="":"number"==typeof a?a+="":ae.isArray(a)&&(a=ae.map(a,function(t){return null==t?"":t+""})),i=ae.valHooks[this.type]||ae.valHooks[this.nodeName.toLowerCase()],i&&"set"in i&&i.set(this,a,"value")!==e||(this.value=a))});if(a)return i=ae.valHooks[a.type]||ae.valHooks[a.nodeName.toLowerCase()],i&&"get"in i&&(n=i.get(a,"value"))!==e?n:(n=a.value,"string"==typeof n?n.replace(Ae,""):null==n?"":n)}}}),ae.extend({valHooks:{option:{get:function(t){var e=t.attributes.value;return!e||e.specified?t.value:t.text}},select:{get:function(t){for(var e,i,n=t.options,r=t.selectedIndex,a="select-one"===t.type||0>r,s=a?null:[],o=a?r+1:n.length,l=0>r?o:a?r:0;o>l;l++)if(i=n[l],!(!i.selected&&l!==r||(ae.support.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ae.nodeName(i.parentNode,"optgroup"))){if(e=ae(i).val(),a)return e;s.push(e)}return s},set:function(t,e){for(var i,n,r=t.options,a=ae.makeArray(e),s=r.length;s--;)n=r[s],(n.selected=ae.inArray(ae(n).val(),a)>=0)&&(i=!0);return i||(t.selectedIndex=-1),a}}},attr:function(t,i,n){var r,a,s=t.nodeType;if(t&&3!==s&&8!==s&&2!==s)return typeof t.getAttribute===V?ae.prop(t,i,n):(1===s&&ae.isXMLDoc(t)||(i=i.toLowerCase(),r=ae.attrHooks[i]||(ae.expr.match.bool.test(i)?Ce:ve)),n===e?r&&"get"in r&&null!==(a=r.get(t,i))?a:(a=ae.find.attr(t,i),null==a?e:a):null!==n?r&&"set"in r&&(a=r.set(t,n,i))!==e?a:(t.setAttribute(i,n+""),n):(ae.removeAttr(t,i),e))},removeAttr:function(t,e){var i,n,r=0,a=e&&e.match(oe);if(a&&1===t.nodeType)for(;i=a[r++];)n=ae.propFix[i]||i,ae.expr.match.bool.test(i)&&(t[n]=!1),t.removeAttribute(i)},attrHooks:{type:{set:function(t,e){if(!ae.support.radioValue&&"radio"===e&&ae.nodeName(t,"input")){var i=t.value;return t.setAttribute("type",e),i&&(t.value=i),e}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(t,i,n){var r,a,s,o=t.nodeType;if(t&&3!==o&&8!==o&&2!==o)return s=1!==o||!ae.isXMLDoc(t),s&&(i=ae.propFix[i]||i,a=ae.propHooks[i]),n!==e?a&&"set"in a&&(r=a.set(t,n,i))!==e?r:t[i]=n:a&&"get"in a&&null!==(r=a.get(t,i))?r:t[i]},propHooks:{tabIndex:{get:function(t){return t.hasAttribute("tabindex")||we.test(t.nodeName)||t.href?t.tabIndex:-1}}}}),Ce={set:function(t,e,i){return e===!1?ae.removeAttr(t,i):t.setAttribute(i,i),i}},ae.each(ae.expr.match.bool.source.match(/\w+/g),function(t,i){var n=ae.expr.attrHandle[i]||ae.find.attr;ae.expr.attrHandle[i]=function(t,i,r){var a=ae.expr.attrHandle[i],s=r?e:(ae.expr.attrHandle[i]=e)!=n(t,i,r)?i.toLowerCase():null;return ae.expr.attrHandle[i]=a,s}}),ae.support.optSelected||(ae.propHooks.selected={get:function(t){var e=t.parentNode;return e&&e.parentNode&&e.parentNode.selectedIndex,null}}),ae.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ae.propFix[this.toLowerCase()]=this}),ae.each(["radio","checkbox"],function(){ae.valHooks[this]={set:function(t,i){return ae.isArray(i)?t.checked=ae.inArray(ae(t).val(),i)>=0:e}},ae.support.checkOn||(ae.valHooks[this].get=function(t){return null===t.getAttribute("value")?"on":t.value})});var xe=/^key/,Me=/^(?:mouse|contextmenu)|click/,je=/^(?:focusinfocus|focusoutblur)$/,Ne=/^([^.]*)(?:\.(.+)|)$/;ae.event={global:{},add:function(t,i,n,r,a){var s,o,l,c,h,u,p,g,d,f,m,I=me.get(t);if(I){for(n.handler&&(s=n,n=s.handler,a=s.selector),n.guid||(n.guid=ae.guid++),(c=I.events)||(c=I.events={}),(o=I.handle)||(o=I.handle=function(t){return typeof ae===V||t&&ae.event.triggered===t.type?e:ae.event.dispatch.apply(o.elem,arguments)},o.elem=t),i=(i||"").match(oe)||[""],h=i.length;h--;)l=Ne.exec(i[h])||[],d=m=l[1],f=(l[2]||"").split(".").sort(),d&&(p=ae.event.special[d]||{},d=(a?p.delegateType:p.bindType)||d,p=ae.event.special[d]||{},u=ae.extend({type:d,origType:m,data:r,handler:n,guid:n.guid,selector:a,needsContext:a&&ae.expr.match.needsContext.test(a),namespace:f.join(".")},s),(g=c[d])||(g=c[d]=[],g.delegateCount=0,p.setup&&p.setup.call(t,r,f,o)!==!1||t.addEventListener&&t.addEventListener(d,o,!1)),p.add&&(p.add.call(t,u),u.handler.guid||(u.handler.guid=n.guid)),a?g.splice(g.delegateCount++,0,u):g.push(u),ae.event.global[d]=!0);t=null}},remove:function(t,e,i,n,r){var a,s,o,l,c,h,u,p,g,d,f,m=me.hasData(t)&&me.get(t);if(m&&(l=m.events)){for(e=(e||"").match(oe)||[""],c=e.length;c--;)if(o=Ne.exec(e[c])||[],g=f=o[1],d=(o[2]||"").split(".").sort(),g){for(u=ae.event.special[g]||{},g=(n?u.delegateType:u.bindType)||g,p=l[g]||[],o=o[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=a=p.length;a--;)h=p[a],!r&&f!==h.origType||i&&i.guid!==h.guid||o&&!o.test(h.namespace)||n&&n!==h.selector&&("**"!==n||!h.selector)||(p.splice(a,1),h.selector&&p.delegateCount--,u.remove&&u.remove.call(t,h));s&&!p.length&&(u.teardown&&u.teardown.call(t,d,m.handle)!==!1||ae.removeEvent(t,g,m.handle),delete l[g])}else for(g in l)ae.event.remove(t,g+e[c],i,n,!0);ae.isEmptyObject(l)&&(delete m.handle,me.remove(t,"events"))}},trigger:function(i,n,r,a){var s,o,l,c,h,u,p,g=[r||X],d=ne.call(i,"type")?i.type:i,f=ne.call(i,"namespace")?i.namespace.split("."):[];if(o=l=r=r||X,3!==r.nodeType&&8!==r.nodeType&&!je.test(d+ae.event.triggered)&&(d.indexOf(".")>=0&&(f=d.split("."),d=f.shift(),f.sort()),h=0>d.indexOf(":")&&"on"+d,i=i[ae.expando]?i:new ae.Event(d,"object"==typeof i&&i),i.isTrigger=a?2:3,i.namespace=f.join("."),i.namespace_re=i.namespace?RegExp("(^|\\.)"+f.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,i.result=e,i.target||(i.target=r),n=null==n?[i]:ae.makeArray(n,[i]),p=ae.event.special[d]||{},a||!p.trigger||p.trigger.apply(r,n)!==!1)){if(!a&&!p.noBubble&&!ae.isWindow(r)){for(c=p.delegateType||d,je.test(c+d)||(o=o.parentNode);o;o=o.parentNode)g.push(o),l=o;l===(r.ownerDocument||X)&&g.push(l.defaultView||l.parentWindow||t)}for(s=0;(o=g[s++])&&!i.isPropagationStopped();)i.type=s>1?c:p.bindType||d,u=(me.get(o,"events")||{})[i.type]&&me.get(o,"handle"),u&&u.apply(o,n),u=h&&o[h],u&&ae.acceptData(o)&&u.apply&&u.apply(o,n)===!1&&i.preventDefault();return i.type=d,a||i.isDefaultPrevented()||p._default&&p._default.apply(g.pop(),n)!==!1||!ae.acceptData(r)||h&&ae.isFunction(r[d])&&!ae.isWindow(r)&&(l=r[h],l&&(r[h]=null),ae.event.triggered=d,r[d](),ae.event.triggered=e,l&&(r[h]=l)),i.result}},dispatch:function(t){t=ae.event.fix(t);var i,n,r,a,s,o=[],l=te.call(arguments),c=(me.get(this,"events")||{})[t.type]||[],h=ae.event.special[t.type]||{};if(l[0]=t,t.delegateTarget=this,!h.preDispatch||h.preDispatch.call(this,t)!==!1){for(o=ae.event.handlers.call(this,t,c),i=0;(a=o[i++])&&!t.isPropagationStopped();)for(t.currentTarget=a.elem,n=0;(s=a.handlers[n++])&&!t.isImmediatePropagationStopped();)(!t.namespace_re||t.namespace_re.test(s.namespace))&&(t.handleObj=s,t.data=s.data,r=((ae.event.special[s.origType]||{}).handle||s.handler).apply(a.elem,l),r!==e&&(t.result=r)===!1&&(t.preventDefault(),t.stopPropagation()));return h.postDispatch&&h.postDispatch.call(this,t),t.result}},handlers:function(t,i){var n,r,a,s,o=[],l=i.delegateCount,c=t.target;if(l&&c.nodeType&&(!t.button||"click"!==t.type))for(;c!==this;c=c.parentNode||this)if(c.disabled!==!0||"click"!==t.type){for(r=[],n=0;l>n;n++)s=i[n],a=s.selector+" ",r[a]===e&&(r[a]=s.needsContext?ae(a,this).index(c)>=0:ae.find(a,this,null,[c]).length),r[a]&&r.push(s);r.length&&o.push({elem:c,handlers:r})}return i.length>l&&o.push({elem:this,handlers:i.slice(l)}),o},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(t,e){return null==t.which&&(t.which=null!=e.charCode?e.charCode:e.keyCode),t}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(t,i){var n,r,a,s=i.button;return null==t.pageX&&null!=i.clientX&&(n=t.target.ownerDocument||X,r=n.documentElement,a=n.body,t.pageX=i.clientX+(r&&r.scrollLeft||a&&a.scrollLeft||0)-(r&&r.clientLeft||a&&a.clientLeft||0),t.pageY=i.clientY+(r&&r.scrollTop||a&&a.scrollTop||0)-(r&&r.clientTop||a&&a.clientTop||0)),t.which||s===e||(t.which=1&s?1:2&s?3:4&s?2:0),t}},fix:function(t){if(t[ae.expando])return t;var e,i,n,r=t.type,a=t,s=this.fixHooks[r];for(s||(this.fixHooks[r]=s=Me.test(r)?this.mouseHooks:xe.test(r)?this.keyHooks:{}),n=s.props?this.props.concat(s.props):this.props,t=new ae.Event(a),e=n.length;e--;)i=n[e],t[i]=a[i];return t.target||(t.target=X),3===t.target.nodeType&&(t.target=t.target.parentNode),s.filter?s.filter(t,a):t},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==l()&&this.focus?(this.focus(),!1):e},delegateType:"focusin"},blur:{trigger:function(){return this===l()&&this.blur?(this.blur(),!1):e},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&ae.nodeName(this,"input")?(this.click(),!1):e},_default:function(t){return ae.nodeName(t.target,"a")}},beforeunload:{postDispatch:function(t){t.result!==e&&(t.originalEvent.returnValue=t.result)}}},simulate:function(t,e,i,n){var r=ae.extend(new ae.Event,i,{type:t,isSimulated:!0,originalEvent:{}});n?ae.event.trigger(r,null,e):ae.event.dispatch.call(e,r),r.isDefaultPrevented()&&i.preventDefault()}},ae.removeEvent=function(t,e,i){t.removeEventListener&&t.removeEventListener(e,i,!1)},ae.Event=function(t,i){return this instanceof ae.Event?(t&&t.type?(this.originalEvent=t,this.type=t.type,this.isDefaultPrevented=t.defaultPrevented||t.getPreventDefault&&t.getPreventDefault()?s:o):this.type=t,i&&ae.extend(this,i),this.timeStamp=t&&t.timeStamp||ae.now(),this[ae.expando]=!0,e):new ae.Event(t,i)},ae.Event.prototype={isDefaultPrevented:o,isPropagationStopped:o,isImmediatePropagationStopped:o,preventDefault:function(){var t=this.originalEvent;this.isDefaultPrevented=s,t&&t.preventDefault&&t.preventDefault()},stopPropagation:function(){var t=this.originalEvent;this.isPropagationStopped=s,t&&t.stopPropagation&&t.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=s,this.stopPropagation()}},ae.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(t,e){ae.event.special[t]={delegateType:e,bindType:e,handle:function(t){var i,n=this,r=t.relatedTarget,a=t.handleObj;return(!r||r!==n&&!ae.contains(n,r))&&(t.type=a.origType,i=a.handler.apply(this,arguments),t.type=e),i}}}),ae.support.focusinBubbles||ae.each({focus:"focusin",blur:"focusout"},function(t,e){var i=0,n=function(t){ae.event.simulate(e,t.target,ae.event.fix(t),!0)};ae.event.special[e]={setup:function(){0===i++&&X.addEventListener(t,n,!0)},teardown:function(){0===--i&&X.removeEventListener(t,n,!0)}}}),ae.fn.extend({on:function(t,i,n,r,a){var s,l;if("object"==typeof t){"string"!=typeof i&&(n=n||i,i=e);for(l in t)this.on(l,i,n,t[l],a);return this}if(null==n&&null==r?(r=i,n=i=e):null==r&&("string"==typeof i?(r=n,n=e):(r=n,n=i,i=e)),r===!1)r=o;else if(!r)return this;return 1===a&&(s=r,r=function(t){return ae().off(t),s.apply(this,arguments)},r.guid=s.guid||(s.guid=ae.guid++)),this.each(function(){ae.event.add(this,t,r,n,i)})},one:function(t,e,i,n){return this.on(t,e,i,n,1)},off:function(t,i,n){var r,a;if(t&&t.preventDefault&&t.handleObj)return r=t.handleObj,ae(t.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof t){for(a in t)this.off(a,i,t[a]);return this}return(i===!1||"function"==typeof i)&&(n=i,i=e),n===!1&&(n=o),this.each(function(){ae.event.remove(this,t,n,i)})},trigger:function(t,e){return this.each(function(){ae.event.trigger(t,e,this)})},triggerHandler:function(t,i){var n=this[0];return n?ae.event.trigger(t,i,n,!0):e}});var ke=/^.[^:#\[\.,]*$/,De=/^(?:parents|prev(?:Until|All))/,ze=ae.expr.match.needsContext,Se={children:!0,contents:!0,next:!0,prev:!0};ae.fn.extend({find:function(t){var e,i=[],n=this,r=n.length;if("string"!=typeof t)return this.pushStack(ae(t).filter(function(){for(e=0;r>e;e++)if(ae.contains(n[e],this))return!0}));for(e=0;r>e;e++)ae.find(t,n[e],i);return i=this.pushStack(r>1?ae.unique(i):i),i.selector=this.selector?this.selector+" "+t:t,i},has:function(t){var e=ae(t,this),i=e.length;return this.filter(function(){for(var t=0;i>t;t++)if(ae.contains(this,e[t]))return!0
+})},not:function(t){return this.pushStack(h(this,t||[],!0))},filter:function(t){return this.pushStack(h(this,t||[],!1))},is:function(t){return!!h(this,"string"==typeof t&&ze.test(t)?ae(t):t||[],!1).length},closest:function(t,e){for(var i,n=0,r=this.length,a=[],s=ze.test(t)||"string"!=typeof t?ae(t,e||this.context):0;r>n;n++)for(i=this[n];i&&i!==e;i=i.parentNode)if(11>i.nodeType&&(s?s.index(i)>-1:1===i.nodeType&&ae.find.matchesSelector(i,t))){i=a.push(i);break}return this.pushStack(a.length>1?ae.unique(a):a)},index:function(t){return t?"string"==typeof t?ee.call(ae(t),this[0]):ee.call(this,t.jquery?t[0]:t):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(t,e){var i="string"==typeof t?ae(t,e):ae.makeArray(t&&t.nodeType?[t]:t),n=ae.merge(this.get(),i);return this.pushStack(ae.unique(n))},addBack:function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}}),ae.each({parent:function(t){var e=t.parentNode;return e&&11!==e.nodeType?e:null},parents:function(t){return ae.dir(t,"parentNode")},parentsUntil:function(t,e,i){return ae.dir(t,"parentNode",i)},next:function(t){return c(t,"nextSibling")},prev:function(t){return c(t,"previousSibling")},nextAll:function(t){return ae.dir(t,"nextSibling")},prevAll:function(t){return ae.dir(t,"previousSibling")},nextUntil:function(t,e,i){return ae.dir(t,"nextSibling",i)},prevUntil:function(t,e,i){return ae.dir(t,"previousSibling",i)},siblings:function(t){return ae.sibling((t.parentNode||{}).firstChild,t)},children:function(t){return ae.sibling(t.firstChild)},contents:function(t){return t.contentDocument||ae.merge([],t.childNodes)}},function(t,e){ae.fn[t]=function(i,n){var r=ae.map(this,e,i);return"Until"!==t.slice(-5)&&(n=i),n&&"string"==typeof n&&(r=ae.filter(n,r)),this.length>1&&(Se[t]||ae.unique(r),De.test(t)&&r.reverse()),this.pushStack(r)}}),ae.extend({filter:function(t,e,i){var n=e[0];return i&&(t=":not("+t+")"),1===e.length&&1===n.nodeType?ae.find.matchesSelector(n,t)?[n]:[]:ae.find.matches(t,ae.grep(e,function(t){return 1===t.nodeType}))},dir:function(t,i,n){for(var r=[],a=n!==e;(t=t[i])&&9!==t.nodeType;)if(1===t.nodeType){if(a&&ae(t).is(n))break;r.push(t)}return r},sibling:function(t,e){for(var i=[];t;t=t.nextSibling)1===t.nodeType&&t!==e&&i.push(t);return i}});var Te=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ee=/<([\w:]+)/,Ge=/<|&#?\w+;/,Le=/<(?:script|style|link)/i,Be=/^(?:checkbox|radio)$/i,Ze=/checked\s*(?:[^=]|=\s*.checked.)/i,_e=/^$|\/(?:java|ecma)script/i,Pe=/^true\/(.*)/,Oe=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Ye={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};Ye.optgroup=Ye.option,Ye.tbody=Ye.tfoot=Ye.colgroup=Ye.caption=Ye.thead,Ye.th=Ye.td,ae.fn.extend({text:function(t){return ae.access(this,function(t){return t===e?ae.text(this):this.empty().append((this[0]&&this[0].ownerDocument||X).createTextNode(t))},null,t,arguments.length)},append:function(){return this.domManip(arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=u(this,t);e.appendChild(t)}})},prepend:function(){return this.domManip(arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=u(this,t);e.insertBefore(t,e.firstChild)}})},before:function(){return this.domManip(arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this)})},after:function(){return this.domManip(arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this.nextSibling)})},remove:function(t,e){for(var i,n=t?ae.filter(t,this):this,r=0;null!=(i=n[r]);r++)e||1!==i.nodeType||ae.cleanData(m(i)),i.parentNode&&(e&&ae.contains(i.ownerDocument,i)&&d(m(i,"script")),i.parentNode.removeChild(i));return this},empty:function(){for(var t,e=0;null!=(t=this[e]);e++)1===t.nodeType&&(ae.cleanData(m(t,!1)),t.textContent="");return this},clone:function(t,e){return t=null==t?!1:t,e=null==e?t:e,this.map(function(){return ae.clone(this,t,e)})},html:function(t){return ae.access(this,function(t){var i=this[0]||{},n=0,r=this.length;if(t===e&&1===i.nodeType)return i.innerHTML;if("string"==typeof t&&!Le.test(t)&&!Ye[(Ee.exec(t)||["",""])[1].toLowerCase()]){t=t.replace(Te,"<$1></$2>");try{for(;r>n;n++)i=this[n]||{},1===i.nodeType&&(ae.cleanData(m(i,!1)),i.innerHTML=t);i=0}catch(a){}}i&&this.empty().append(t)},null,t,arguments.length)},replaceWith:function(){var t=ae.map(this,function(t){return[t.nextSibling,t.parentNode]}),e=0;return this.domManip(arguments,function(i){var n=t[e++],r=t[e++];r&&(n&&n.parentNode!==r&&(n=this.nextSibling),ae(this).remove(),r.insertBefore(i,n))},!0),e?this:this.remove()},detach:function(t){return this.remove(t,!0)},domManip:function(t,e,i){t=K.apply([],t);var n,r,a,s,o,l,c=0,h=this.length,u=this,d=h-1,f=t[0],I=ae.isFunction(f);if(I||!(1>=h||"string"!=typeof f||ae.support.checkClone)&&Ze.test(f))return this.each(function(n){var r=u.eq(n);I&&(t[0]=f.call(this,n,r.html())),r.domManip(t,e,i)});if(h&&(n=ae.buildFragment(t,this[0].ownerDocument,!1,!i&&this),r=n.firstChild,1===n.childNodes.length&&(n=r),r)){for(a=ae.map(m(n,"script"),p),s=a.length;h>c;c++)o=n,c!==d&&(o=ae.clone(o,!0,!0),s&&ae.merge(a,m(o,"script"))),e.call(this[c],o,c);if(s)for(l=a[a.length-1].ownerDocument,ae.map(a,g),c=0;s>c;c++)o=a[c],_e.test(o.type||"")&&!me.access(o,"globalEval")&&ae.contains(l,o)&&(o.src?ae._evalUrl(o.src):ae.globalEval(o.textContent.replace(Oe,"")))}return this}}),ae.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(t,e){ae.fn[t]=function(t){for(var i,n=[],r=ae(t),a=r.length-1,s=0;a>=s;s++)i=s===a?this:this.clone(!0),ae(r[s])[e](i),q.apply(n,i.get());return this.pushStack(n)}}),ae.extend({clone:function(t,e,i){var n,r,a,s,o=t.cloneNode(!0),l=ae.contains(t.ownerDocument,t);if(!(ae.support.noCloneChecked||1!==t.nodeType&&11!==t.nodeType||ae.isXMLDoc(t)))for(s=m(o),a=m(t),n=0,r=a.length;r>n;n++)I(a[n],s[n]);if(e)if(i)for(a=a||m(t),s=s||m(o),n=0,r=a.length;r>n;n++)f(a[n],s[n]);else f(t,o);return s=m(o,"script"),s.length>0&&d(s,!l&&m(t,"script")),o},buildFragment:function(t,e,i,n){for(var r,a,s,o,l,c,h=0,u=t.length,p=e.createDocumentFragment(),g=[];u>h;h++)if(r=t[h],r||0===r)if("object"===ae.type(r))ae.merge(g,r.nodeType?[r]:r);else if(Ge.test(r)){for(a=a||p.appendChild(e.createElement("div")),s=(Ee.exec(r)||["",""])[1].toLowerCase(),o=Ye[s]||Ye._default,a.innerHTML=o[1]+r.replace(Te,"<$1></$2>")+o[2],c=o[0];c--;)a=a.lastChild;ae.merge(g,a.childNodes),a=p.firstChild,a.textContent=""}else g.push(e.createTextNode(r));for(p.textContent="",h=0;r=g[h++];)if((!n||-1===ae.inArray(r,n))&&(l=ae.contains(r.ownerDocument,r),a=m(p.appendChild(r),"script"),l&&d(a),i))for(c=0;r=a[c++];)_e.test(r.type||"")&&i.push(r);return p},cleanData:function(t){for(var i,n,a,s,o,l,c=ae.event.special,h=0;(n=t[h])!==e;h++){if(r.accepts(n)&&(o=n[me.expando],o&&(i=me.cache[o]))){if(a=Object.keys(i.events||{}),a.length)for(l=0;(s=a[l])!==e;l++)c[s]?ae.event.remove(n,s):ae.removeEvent(n,s,i.handle);me.cache[o]&&delete me.cache[o]}delete fe.cache[n[fe.expando]]}},_evalUrl:function(t){return ae.ajax({url:t,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),ae.fn.extend({wrapAll:function(t){var e;return ae.isFunction(t)?this.each(function(e){ae(this).wrapAll(t.call(this,e))}):(this[0]&&(e=ae(t,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&e.insertBefore(this[0]),e.map(function(){for(var t=this;t.firstElementChild;)t=t.firstElementChild;return t}).append(this)),this)},wrapInner:function(t){return ae.isFunction(t)?this.each(function(e){ae(this).wrapInner(t.call(this,e))}):this.each(function(){var e=ae(this),i=e.contents();i.length?i.wrapAll(t):e.append(t)})},wrap:function(t){var e=ae.isFunction(t);return this.each(function(i){ae(this).wrapAll(e?t.call(this,i):t)})},unwrap:function(){return this.parent().each(function(){ae.nodeName(this,"body")||ae(this).replaceWith(this.childNodes)}).end()}});var We,Ve,Re=/^(none|table(?!-c[ea]).+)/,Xe=/^margin/,Ue=RegExp("^("+se+")(.*)$","i"),He=RegExp("^("+se+")(?!px)[a-z%]+$","i"),Fe=RegExp("^([+-])=("+se+")","i"),Je={BODY:"block"},Qe={position:"absolute",visibility:"hidden",display:"block"},$e={letterSpacing:0,fontWeight:400},Ke=["Top","Right","Bottom","Left"],qe=["Webkit","O","Moz","ms"];ae.fn.extend({css:function(t,i){return ae.access(this,function(t,i,n){var r,a,s={},o=0;if(ae.isArray(i)){for(r=C(t),a=i.length;a>o;o++)s[i[o]]=ae.css(t,i[o],!1,r);return s}return n!==e?ae.style(t,i,n):ae.css(t,i)},t,i,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(t){return"boolean"==typeof t?t?this.show():this.hide():this.each(function(){v(this)?ae(this).show():ae(this).hide()})}}),ae.extend({cssHooks:{opacity:{get:function(t,e){if(e){var i=We(t,"opacity");return""===i?"1":i}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(t,i,n,r){if(t&&3!==t.nodeType&&8!==t.nodeType&&t.style){var a,s,o,l=ae.camelCase(i),c=t.style;return i=ae.cssProps[l]||(ae.cssProps[l]=y(c,l)),o=ae.cssHooks[i]||ae.cssHooks[l],n===e?o&&"get"in o&&(a=o.get(t,!1,r))!==e?a:c[i]:(s=typeof n,"string"===s&&(a=Fe.exec(n))&&(n=(a[1]+1)*a[2]+parseFloat(ae.css(t,i)),s="number"),null==n||"number"===s&&isNaN(n)||("number"!==s||ae.cssNumber[l]||(n+="px"),ae.support.clearCloneStyle||""!==n||0!==i.indexOf("background")||(c[i]="inherit"),o&&"set"in o&&(n=o.set(t,n,r))===e||(c[i]=n)),e)}},css:function(t,i,n,r){var a,s,o,l=ae.camelCase(i);return i=ae.cssProps[l]||(ae.cssProps[l]=y(t.style,l)),o=ae.cssHooks[i]||ae.cssHooks[l],o&&"get"in o&&(a=o.get(t,!0,n)),a===e&&(a=We(t,i,r)),"normal"===a&&i in $e&&(a=$e[i]),""===n||n?(s=parseFloat(a),n===!0||ae.isNumeric(s)?s||0:a):a}}),We=function(t,i,n){var r,a,s,o=n||C(t),l=o?o.getPropertyValue(i)||o[i]:e,c=t.style;return o&&(""!==l||ae.contains(t.ownerDocument,t)||(l=ae.style(t,i)),He.test(l)&&Xe.test(i)&&(r=c.width,a=c.minWidth,s=c.maxWidth,c.minWidth=c.maxWidth=c.width=l,l=o.width,c.width=r,c.minWidth=a,c.maxWidth=s)),l},ae.each(["height","width"],function(t,i){ae.cssHooks[i]={get:function(t,n,r){return n?0===t.offsetWidth&&Re.test(ae.css(t,"display"))?ae.swap(t,Qe,function(){return x(t,i,r)}):x(t,i,r):e},set:function(t,e,n){var r=n&&C(t);return A(t,e,n?w(t,i,n,ae.support.boxSizing&&"border-box"===ae.css(t,"boxSizing",!1,r),r):0)}}}),ae(function(){ae.support.reliableMarginRight||(ae.cssHooks.marginRight={get:function(t,i){return i?ae.swap(t,{display:"inline-block"},We,[t,"marginRight"]):e}}),!ae.support.pixelPosition&&ae.fn.position&&ae.each(["top","left"],function(t,i){ae.cssHooks[i]={get:function(t,n){return n?(n=We(t,i),He.test(n)?ae(t).position()[i]+"px":n):e}}})}),ae.expr&&ae.expr.filters&&(ae.expr.filters.hidden=function(t){return 0>=t.offsetWidth&&0>=t.offsetHeight},ae.expr.filters.visible=function(t){return!ae.expr.filters.hidden(t)}),ae.each({margin:"",padding:"",border:"Width"},function(t,e){ae.cssHooks[t+e]={expand:function(i){for(var n=0,r={},a="string"==typeof i?i.split(" "):[i];4>n;n++)r[t+Ke[n]+e]=a[n]||a[n-2]||a[0];return r}},Xe.test(t)||(ae.cssHooks[t+e].set=A)});var ti=/%20/g,ei=/\[\]$/,ii=/\r?\n/g,ni=/^(?:submit|button|image|reset|file)$/i,ri=/^(?:input|select|textarea|keygen)/i;ae.fn.extend({serialize:function(){return ae.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var t=ae.prop(this,"elements");return t?ae.makeArray(t):this}).filter(function(){var t=this.type;return this.name&&!ae(this).is(":disabled")&&ri.test(this.nodeName)&&!ni.test(t)&&(this.checked||!Be.test(t))}).map(function(t,e){var i=ae(this).val();return null==i?null:ae.isArray(i)?ae.map(i,function(t){return{name:e.name,value:t.replace(ii,"\r\n")}}):{name:e.name,value:i.replace(ii,"\r\n")}}).get()}}),ae.param=function(t,i){var n,r=[],a=function(t,e){e=ae.isFunction(e)?e():null==e?"":e,r[r.length]=encodeURIComponent(t)+"="+encodeURIComponent(e)};if(i===e&&(i=ae.ajaxSettings&&ae.ajaxSettings.traditional),ae.isArray(t)||t.jquery&&!ae.isPlainObject(t))ae.each(t,function(){a(this.name,this.value)});else for(n in t)N(n,t[n],i,a);return r.join("&").replace(ti,"+")},ae.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(t,e){ae.fn[e]=function(t,i){return arguments.length>0?this.on(e,null,t,i):this.trigger(e)}}),ae.fn.extend({hover:function(t,e){return this.mouseenter(t).mouseleave(e||t)},bind:function(t,e,i){return this.on(t,null,e,i)},unbind:function(t,e){return this.off(t,null,e)},delegate:function(t,e,i,n){return this.on(e,t,i,n)},undelegate:function(t,e,i){return 1===arguments.length?this.off(t,"**"):this.off(e,t||"**",i)}});var ai,si,oi=ae.now(),li=/\?/,ci=/#.*$/,hi=/([?&])_=[^&]*/,ui=/^(.*?):[ \t]*([^\r\n]*)$/gm,pi=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,gi=/^(?:GET|HEAD)$/,di=/^\/\//,fi=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,mi=ae.fn.load,Ii={},yi={},vi="*/".concat("*");try{si=R.href}catch(Ci){si=X.createElement("a"),si.href="",si=si.href}ai=fi.exec(si.toLowerCase())||[],ae.fn.load=function(t,i,n){if("string"!=typeof t&&mi)return mi.apply(this,arguments);var r,a,s,o=this,l=t.indexOf(" ");return l>=0&&(r=t.slice(l),t=t.slice(0,l)),ae.isFunction(i)?(n=i,i=e):i&&"object"==typeof i&&(a="POST"),o.length>0&&ae.ajax({url:t,type:a,dataType:"html",data:i}).done(function(t){s=arguments,o.html(r?ae("<div>").append(ae.parseHTML(t)).find(r):t)}).complete(n&&function(t,e){o.each(n,s||[t.responseText,e,t])}),this},ae.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(t,e){ae.fn[e]=function(t){return this.on(e,t)}}),ae.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:si,type:"GET",isLocal:pi.test(ai[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":vi,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ae.parseJSON,"text xml":ae.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(t,e){return e?z(z(t,ae.ajaxSettings),e):z(ae.ajaxSettings,t)},ajaxPrefilter:k(Ii),ajaxTransport:k(yi),ajax:function(t,i){function n(t,i,n,o){var c,u,y,v,b,w=i;2!==C&&(C=2,l&&clearTimeout(l),r=e,s=o||"",A.readyState=t>0?4:0,c=t>=200&&300>t||304===t,n&&(v=S(p,A,n)),v=T(p,v,A,c),c?(p.ifModified&&(b=A.getResponseHeader("Last-Modified"),b&&(ae.lastModified[a]=b),b=A.getResponseHeader("etag"),b&&(ae.etag[a]=b)),204===t||"HEAD"===p.type?w="nocontent":304===t?w="notmodified":(w=v.state,u=v.data,y=v.error,c=!y)):(y=w,(t||!w)&&(w="error",0>t&&(t=0))),A.status=t,A.statusText=(i||w)+"",c?f.resolveWith(g,[u,w,A]):f.rejectWith(g,[A,w,y]),A.statusCode(I),I=e,h&&d.trigger(c?"ajaxSuccess":"ajaxError",[A,p,c?u:y]),m.fireWith(g,[A,w]),h&&(d.trigger("ajaxComplete",[A,p]),--ae.active||ae.event.trigger("ajaxStop")))}"object"==typeof t&&(i=t,t=e),i=i||{};var r,a,s,o,l,c,h,u,p=ae.ajaxSetup({},i),g=p.context||p,d=p.context&&(g.nodeType||g.jquery)?ae(g):ae.event,f=ae.Deferred(),m=ae.Callbacks("once memory"),I=p.statusCode||{},y={},v={},C=0,b="canceled",A={readyState:0,getResponseHeader:function(t){var e;if(2===C){if(!o)for(o={};e=ui.exec(s);)o[e[1].toLowerCase()]=e[2];e=o[t.toLowerCase()]}return null==e?null:e},getAllResponseHeaders:function(){return 2===C?s:null},setRequestHeader:function(t,e){var i=t.toLowerCase();return C||(t=v[i]=v[i]||t,y[t]=e),this},overrideMimeType:function(t){return C||(p.mimeType=t),this},statusCode:function(t){var e;if(t)if(2>C)for(e in t)I[e]=[I[e],t[e]];else A.always(t[A.status]);return this},abort:function(t){var e=t||b;return r&&r.abort(e),n(0,e),this}};if(f.promise(A).complete=m.add,A.success=A.done,A.error=A.fail,p.url=((t||p.url||si)+"").replace(ci,"").replace(di,ai[1]+"//"),p.type=i.method||i.type||p.method||p.type,p.dataTypes=ae.trim(p.dataType||"*").toLowerCase().match(oe)||[""],null==p.crossDomain&&(c=fi.exec(p.url.toLowerCase()),p.crossDomain=!(!c||c[1]===ai[1]&&c[2]===ai[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(ai[3]||("http:"===ai[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=ae.param(p.data,p.traditional)),D(Ii,p,i,A),2===C)return A;h=p.global,h&&0===ae.active++&&ae.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!gi.test(p.type),a=p.url,p.hasContent||(p.data&&(a=p.url+=(li.test(a)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=hi.test(a)?a.replace(hi,"$1_="+oi++):a+(li.test(a)?"&":"?")+"_="+oi++)),p.ifModified&&(ae.lastModified[a]&&A.setRequestHeader("If-Modified-Since",ae.lastModified[a]),ae.etag[a]&&A.setRequestHeader("If-None-Match",ae.etag[a])),(p.data&&p.hasContent&&p.contentType!==!1||i.contentType)&&A.setRequestHeader("Content-Type",p.contentType),A.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+vi+"; q=0.01":""):p.accepts["*"]);for(u in p.headers)A.setRequestHeader(u,p.headers[u]);if(p.beforeSend&&(p.beforeSend.call(g,A,p)===!1||2===C))return A.abort();b="abort";for(u in{success:1,error:1,complete:1})A[u](p[u]);if(r=D(yi,p,i,A)){A.readyState=1,h&&d.trigger("ajaxSend",[A,p]),p.async&&p.timeout>0&&(l=setTimeout(function(){A.abort("timeout")},p.timeout));try{C=1,r.send(y,n)}catch(w){if(!(2>C))throw w;n(-1,w)}}else n(-1,"No Transport");return A},getJSON:function(t,e,i){return ae.get(t,e,i,"json")},getScript:function(t,i){return ae.get(t,e,i,"script")}}),ae.each(["get","post"],function(t,i){ae[i]=function(t,n,r,a){return ae.isFunction(n)&&(a=a||r,r=n,n=e),ae.ajax({url:t,type:i,dataType:a,data:n,success:r})}}),ae.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(t){return ae.globalEval(t),t}}}),ae.ajaxPrefilter("script",function(t){t.cache===e&&(t.cache=!1),t.crossDomain&&(t.type="GET")}),ae.ajaxTransport("script",function(t){if(t.crossDomain){var e,i;return{send:function(n,r){e=ae("<script>").prop({async:!0,charset:t.scriptCharset,src:t.url}).on("load error",i=function(t){e.remove(),i=null,t&&r("error"===t.type?404:200,t.type)}),X.head.appendChild(e[0])},abort:function(){i&&i()}}}});var bi=[],Ai=/(=)\?(?=&|$)|\?\?/;ae.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var t=bi.pop()||ae.expando+"_"+oi++;return this[t]=!0,t}}),ae.ajaxPrefilter("json jsonp",function(i,n,r){var a,s,o,l=i.jsonp!==!1&&(Ai.test(i.url)?"url":"string"==typeof i.data&&!(i.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ai.test(i.data)&&"data");return l||"jsonp"===i.dataTypes[0]?(a=i.jsonpCallback=ae.isFunction(i.jsonpCallback)?i.jsonpCallback():i.jsonpCallback,l?i[l]=i[l].replace(Ai,"$1"+a):i.jsonp!==!1&&(i.url+=(li.test(i.url)?"&":"?")+i.jsonp+"="+a),i.converters["script json"]=function(){return o||ae.error(a+" was not called"),o[0]},i.dataTypes[0]="json",s=t[a],t[a]=function(){o=arguments},r.always(function(){t[a]=s,i[a]&&(i.jsonpCallback=n.jsonpCallback,bi.push(a)),o&&ae.isFunction(s)&&s(o[0]),o=s=e}),"script"):e}),ae.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(t){}};var wi=ae.ajaxSettings.xhr(),xi={0:200,1223:204},Mi=0,ji={};t.ActiveXObject&&ae(t).on("unload",function(){for(var t in ji)ji[t]();ji=e}),ae.support.cors=!!wi&&"withCredentials"in wi,ae.support.ajax=wi=!!wi,ae.ajaxTransport(function(t){var i;return ae.support.cors||wi&&!t.crossDomain?{send:function(n,r){var a,s,o=t.xhr();if(o.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)o[a]=t.xhrFields[a];t.mimeType&&o.overrideMimeType&&o.overrideMimeType(t.mimeType),t.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(a in n)o.setRequestHeader(a,n[a]);i=function(t){return function(){i&&(delete ji[s],i=o.onload=o.onerror=null,"abort"===t?o.abort():"error"===t?r(o.status||404,o.statusText):r(xi[o.status]||o.status,o.statusText,"string"==typeof o.responseText?{text:o.responseText}:e,o.getAllResponseHeaders()))}},o.onload=i(),o.onerror=i("error"),i=ji[s=Mi++]=i("abort"),o.send(t.hasContent&&t.data||null)},abort:function(){i&&i()}}:e});var Ni,ki,Di=/^(?:toggle|show|hide)$/,zi=RegExp("^(?:([+-])=|)("+se+")([a-z%]*)$","i"),Si=/queueHooks$/,Ti=[Z],Ei={"*":[function(t,e){var i=this.createTween(t,e),n=i.cur(),r=zi.exec(e),a=r&&r[3]||(ae.cssNumber[t]?"":"px"),s=(ae.cssNumber[t]||"px"!==a&&+n)&&zi.exec(ae.css(i.elem,t)),o=1,l=20;if(s&&s[3]!==a){a=a||s[3],r=r||[],s=+n||1;do o=o||".5",s/=o,ae.style(i.elem,t,s+a);while(o!==(o=i.cur()/n)&&1!==o&&--l)}return r&&(s=i.start=+s||+n||0,i.unit=a,i.end=r[1]?s+(r[1]+1)*r[2]:+r[2]),i}]};ae.Animation=ae.extend(L,{tweener:function(t,e){ae.isFunction(t)?(e=t,t=["*"]):t=t.split(" ");for(var i,n=0,r=t.length;r>n;n++)i=t[n],Ei[i]=Ei[i]||[],Ei[i].unshift(e)},prefilter:function(t,e){e?Ti.unshift(t):Ti.push(t)}}),ae.Tween=_,_.prototype={constructor:_,init:function(t,e,i,n,r,a){this.elem=t,this.prop=i,this.easing=r||"swing",this.options=e,this.start=this.now=this.cur(),this.end=n,this.unit=a||(ae.cssNumber[i]?"":"px")},cur:function(){var t=_.propHooks[this.prop];return t&&t.get?t.get(this):_.propHooks._default.get(this)},run:function(t){var e,i=_.propHooks[this.prop];return this.pos=e=this.options.duration?ae.easing[this.easing](t,this.options.duration*t,0,1,this.options.duration):t,this.now=(this.end-this.start)*e+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),i&&i.set?i.set(this):_.propHooks._default.set(this),this}},_.prototype.init.prototype=_.prototype,_.propHooks={_default:{get:function(t){var e;return null==t.elem[t.prop]||t.elem.style&&null!=t.elem.style[t.prop]?(e=ae.css(t.elem,t.prop,""),e&&"auto"!==e?e:0):t.elem[t.prop]},set:function(t){ae.fx.step[t.prop]?ae.fx.step[t.prop](t):t.elem.style&&(null!=t.elem.style[ae.cssProps[t.prop]]||ae.cssHooks[t.prop])?ae.style(t.elem,t.prop,t.now+t.unit):t.elem[t.prop]=t.now}}},_.propHooks.scrollTop=_.propHooks.scrollLeft={set:function(t){t.elem.nodeType&&t.elem.parentNode&&(t.elem[t.prop]=t.now)}},ae.each(["toggle","show","hide"],function(t,e){var i=ae.fn[e];ae.fn[e]=function(t,n,r){return null==t||"boolean"==typeof t?i.apply(this,arguments):this.animate(P(e,!0),t,n,r)}}),ae.fn.extend({fadeTo:function(t,e,i,n){return this.filter(v).css("opacity",0).show().end().animate({opacity:e},t,i,n)},animate:function(t,e,i,n){var r=ae.isEmptyObject(t),a=ae.speed(e,i,n),s=function(){var e=L(this,ae.extend({},t),a);(r||me.get(this,"finish"))&&e.stop(!0)};return s.finish=s,r||a.queue===!1?this.each(s):this.queue(a.queue,s)},stop:function(t,i,n){var r=function(t){var e=t.stop;delete t.stop,e(n)};return"string"!=typeof t&&(n=i,i=t,t=e),i&&t!==!1&&this.queue(t||"fx",[]),this.each(function(){var e=!0,i=null!=t&&t+"queueHooks",a=ae.timers,s=me.get(this);if(i)s[i]&&s[i].stop&&r(s[i]);else for(i in s)s[i]&&s[i].stop&&Si.test(i)&&r(s[i]);for(i=a.length;i--;)a[i].elem!==this||null!=t&&a[i].queue!==t||(a[i].anim.stop(n),e=!1,a.splice(i,1));(e||!n)&&ae.dequeue(this,t)})},finish:function(t){return t!==!1&&(t=t||"fx"),this.each(function(){var e,i=me.get(this),n=i[t+"queue"],r=i[t+"queueHooks"],a=ae.timers,s=n?n.length:0;for(i.finish=!0,ae.queue(this,t,[]),r&&r.stop&&r.stop.call(this,!0),e=a.length;e--;)a[e].elem===this&&a[e].queue===t&&(a[e].anim.stop(!0),a.splice(e,1));for(e=0;s>e;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete i.finish})}}),ae.each({slideDown:P("show"),slideUp:P("hide"),slideToggle:P("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(t,e){ae.fn[t]=function(t,i,n){return this.animate(e,t,i,n)}}),ae.speed=function(t,e,i){var n=t&&"object"==typeof t?ae.extend({},t):{complete:i||!i&&e||ae.isFunction(t)&&t,duration:t,easing:i&&e||e&&!ae.isFunction(e)&&e};return n.duration=ae.fx.off?0:"number"==typeof n.duration?n.duration:n.duration in ae.fx.speeds?ae.fx.speeds[n.duration]:ae.fx.speeds._default,(null==n.queue||n.queue===!0)&&(n.queue="fx"),n.old=n.complete,n.complete=function(){ae.isFunction(n.old)&&n.old.call(this),n.queue&&ae.dequeue(this,n.queue)},n},ae.easing={linear:function(t){return t},swing:function(t){return.5-Math.cos(t*Math.PI)/2}},ae.timers=[],ae.fx=_.prototype.init,ae.fx.tick=function(){var t,i=ae.timers,n=0;for(Ni=ae.now();i.length>n;n++)t=i[n],t()||i[n]!==t||i.splice(n--,1);i.length||ae.fx.stop(),Ni=e},ae.fx.timer=function(t){t()&&ae.timers.push(t)&&ae.fx.start()},ae.fx.interval=13,ae.fx.start=function(){ki||(ki=setInterval(ae.fx.tick,ae.fx.interval))},ae.fx.stop=function(){clearInterval(ki),ki=null},ae.fx.speeds={slow:600,fast:200,_default:400},ae.fx.step={},ae.expr&&ae.expr.filters&&(ae.expr.filters.animated=function(t){return ae.grep(ae.timers,function(e){return t===e.elem}).length}),ae.fn.offset=function(t){if(arguments.length)return t===e?this:this.each(function(e){ae.offset.setOffset(this,t,e)});var i,n,r=this[0],a={top:0,left:0},s=r&&r.ownerDocument;if(s)return i=s.documentElement,ae.contains(i,r)?(typeof r.getBoundingClientRect!==V&&(a=r.getBoundingClientRect()),n=O(s),{top:a.top+n.pageYOffset-i.clientTop,left:a.left+n.pageXOffset-i.clientLeft}):a},ae.offset={setOffset:function(t,e,i){var n,r,a,s,o,l,c,h=ae.css(t,"position"),u=ae(t),p={};"static"===h&&(t.style.position="relative"),o=u.offset(),a=ae.css(t,"top"),l=ae.css(t,"left"),c=("absolute"===h||"fixed"===h)&&(a+l).indexOf("auto")>-1,c?(n=u.position(),s=n.top,r=n.left):(s=parseFloat(a)||0,r=parseFloat(l)||0),ae.isFunction(e)&&(e=e.call(t,i,o)),null!=e.top&&(p.top=e.top-o.top+s),null!=e.left&&(p.left=e.left-o.left+r),"using"in e?e.using.call(t,p):u.css(p)}},ae.fn.extend({position:function(){if(this[0]){var t,e,i=this[0],n={top:0,left:0};return"fixed"===ae.css(i,"position")?e=i.getBoundingClientRect():(t=this.offsetParent(),e=this.offset(),ae.nodeName(t[0],"html")||(n=t.offset()),n.top+=ae.css(t[0],"borderTopWidth",!0),n.left+=ae.css(t[0],"borderLeftWidth",!0)),{top:e.top-n.top-ae.css(i,"marginTop",!0),left:e.left-n.left-ae.css(i,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||U;t&&!ae.nodeName(t,"html")&&"static"===ae.css(t,"position");)t=t.offsetParent;return t||U})}}),ae.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(i,n){var r="pageYOffset"===n;ae.fn[i]=function(a){return ae.access(this,function(i,a,s){var o=O(i);return s===e?o?o[n]:i[a]:(o?o.scrollTo(r?t.pageXOffset:s,r?s:t.pageYOffset):i[a]=s,e)},i,a,arguments.length,null)}}),ae.each({Height:"height",Width:"width"},function(t,i){ae.each({padding:"inner"+t,content:i,"":"outer"+t},function(n,r){ae.fn[r]=function(r,a){var s=arguments.length&&(n||"boolean"!=typeof r),o=n||(r===!0||a===!0?"margin":"border");return ae.access(this,function(i,n,r){var a;return ae.isWindow(i)?i.document.documentElement["client"+t]:9===i.nodeType?(a=i.documentElement,Math.max(i.body["scroll"+t],a["scroll"+t],i.body["offset"+t],a["offset"+t],a["client"+t])):r===e?ae.css(i,n,o):ae.style(i,n,r,o)},i,s?r:e,s,null)}})}),ae.fn.size=function(){return this.length},ae.fn.andSelf=ae.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=ae:"function"==typeof define&&define.amd&&define("jquery",[],function(){return ae}),"object"==typeof t&&"object"==typeof t.document&&(t.jQuery=t.$=ae)}(window),function(){function t(t,e,i){for(var n=(i||0)-1,r=t?t.length:0;r>++n;)if(t[n]===e)return n;return-1}function e(e,i){var n=typeof i;if(e=e.cache,"boolean"==n||null==i)return e[i]?0:-1;"number"!=n&&"string"!=n&&(n="object");var r="number"==n?i:y+i;return e=(e=e[n])&&e[r],"object"==n?e&&t(e,i)>-1?0:-1:e?0:-1}function i(t){var e=this.cache,i=typeof t;if("boolean"==i||null==t)e[t]=!0;else{"number"!=i&&"string"!=i&&(i="object");var n="number"==i?t:y+t,r=e[i]||(e[i]={});"object"==i?(r[n]||(r[n]=[])).push(t):r[n]=!0}}function n(t){return t.charCodeAt(0)}function r(t,e){var i=t.criteria,n=e.criteria;if(i!==n){if(i>n||i===d)return 1;if(n>i||n===d)return-1}return t.index-e.index}function a(t){var e=-1,n=t.length,r=t[0],a=t[0|n/2],s=t[n-1];if(r&&"object"==typeof r&&a&&"object"==typeof a&&s&&"object"==typeof s)return!1;var o=l();o["false"]=o["null"]=o["true"]=o.undefined=!1;var c=l();for(c.array=t,c.cache=o,c.push=i;n>++e;)c.push(t[e]);return c}function s(t){return"\\"+F[t]}function o(){return f.pop()||[]}function l(){return m.pop()||{array:null,cache:null,criteria:null,"false":!1,index:0,"null":!1,number:null,object:null,push:null,string:null,"true":!1,undefined:!1,value:null}}function c(){}function h(t){t.length=0,C>f.length&&f.push(t)}function u(t){var e=t.cache;e&&u(e),t.array=t.cache=t.criteria=t.object=t.number=t.string=t.value=null,C>m.length&&m.push(t)}function p(t,e,i){e||(e=0),i===d&&(i=t?t.length:0);for(var n=-1,r=i-e||0,a=Array(0>r?0:r);r>++n;)a[n]=t[e+n];return a}function g(i){function f(t){return t&&"object"==typeof t&&!Qn(t)&&Mn.call(t,"__wrapped__")?t:new m(t)}function m(t,e){this.__chain__=!!e,this.__wrapped__=t}function C(t,e,i,n,r){if(i){var a=i(t);if(a!==d)return a}var s=je(t);if(!s)return t;var l=Sn.call(t);if(!R[l])return t;var c=Hn[l];switch(l){case Z:case _:return new c(+t);case O:case V:return new c(t);case W:return a=c(t.source,j.exec(t)),a.lastIndex=t.lastIndex,a}var u=Qn(t);if(e){var g=!n;n||(n=o()),r||(r=o());for(var f=n.length;f--;)if(n[f]==t)return r[f];a=u?c(t.length):{}}else a=u?p(t):nr({},t);return u&&(Mn.call(t,"index")&&(a.index=t.index),Mn.call(t,"input")&&(a.input=t.input)),e?(n.push(t),r.push(a),(u?Xe:sr)(t,function(t,s){a[s]=C(t,e,i,n,r)}),g&&(h(n),h(r)),a):a}function F(t,e,i){if("function"!=typeof t)return Xi;if(e===d)return t;var n=t.__bindData__||Fn.funcNames&&!t.name;if(n===d){var r=S&&wn.call(t);Fn.funcNames||!r||N.test(r)||(n=!0),(Fn.funcNames||!n)&&(n=!Fn.funcDecomp||S.test(r),Jn(t,n))}if(n!==!0&&n&&1&n[1])return t;switch(i){case 1:return function(i){return t.call(e,i)};case 2:return function(i,n){return t.call(e,i,n)};case 3:return function(i,n,r){return t.call(e,i,n,r)};case 4:return function(i,n,r,a){return t.call(e,i,n,r,a)}}return Di(t,e)}function Q(t,e,i,n){for(var r=(n||0)-1,a=t?t.length:0,s=[];a>++r;){var o=t[r];if(o&&"object"==typeof o&&"number"==typeof o.length&&(Qn(o)||ce(o))){e||(o=Q(o,e,i));var l=-1,c=o.length,h=s.length;for(s.length+=c;c>++l;)s[h++]=o[l]}else i||s.push(o)}return s}function $(t,e,i,n,r,a){if(i){var s=i(t,e);if(s!==d)return!!s}if(t===e)return 0!==t||1/t==1/e;var l=typeof t,c=typeof e;if(!(t!==t||t&&H[l]||e&&H[c]))return!1;if(null==t||null==e)return t===e;var u=Sn.call(t),p=Sn.call(e);if(u==L&&(u=Y),p==L&&(p=Y),u!=p)return!1;switch(u){case Z:case _:return+t==+e;case O:return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case W:case V:return t==dn(e)}var g=u==B;if(!g){if(Mn.call(t,"__wrapped__ ")||Mn.call(e,"__wrapped__"))return $(t.__wrapped__||t,e.__wrapped__||e,i,n,r,a);if(u!=Y)return!1;var f=t.constructor,m=e.constructor;if(f!=m&&!(Me(f)&&f instanceof f&&Me(m)&&m instanceof m))return!1}var I=!r;r||(r=o()),a||(a=o());for(var y=r.length;y--;)if(r[y]==t)return a[y]==e;var v=0;if(s=!0,r.push(t),a.push(e),g){if(y=t.length,v=e.length,s=v==t.length,!s&&!n)return s;for(;v--;){var C=y,b=e[v];if(n)for(;C--&&!(s=$(t[C],b,i,n,r,a)););else if(!(s=$(t[v],b,i,n,r,a)))break}return s}return ar(e,function(e,o,l){return Mn.call(l,o)?(v++,s=Mn.call(t,o)&&$(t[o],e,i,n,r,a)):d}),s&&!n&&ar(t,function(t,e,i){return Mn.call(i,e)?s=--v>-1:d}),I&&(h(r),h(a)),s}function q(t,e,i,n,r){(Qn(e)?Xe:sr)(e,function(e,a){var s,o,l=e,c=t[a];if(e&&((o=Qn(e))||or(e))){for(var h=n.length;h--;)if(s=n[h]==e){c=r[h];break}if(!s){var u;
+i&&(l=i(c,e),(u=l!==d)&&(c=l)),u||(c=o?Qn(c)?c:[]:or(c)?c:{}),n.push(e),r.push(c),u||q(c,e,i,n,r)}}else i&&(l=i(c,e),l===d&&(l=e)),l!==d&&(c=l);t[a]=c})}function ee(i,n,r){var s=-1,l=se(),c=i?i.length:0,p=[],g=!n&&c>=v&&l===t,d=r||g?o():p;if(g){var f=a(d);f?(l=e,d=f):(g=!1,d=r?d:(h(d),p))}for(;c>++s;){var m=i[s],I=r?r(m,s,i):m;(n?!s||d[d.length-1]!==I:0>l(d,I))&&((r||g)&&d.push(I),p.push(m))}return g?(h(d.array),u(d)):r&&h(d),p}function ie(t){return function(e,i,n){var r={};i=f.createCallback(i,n,3);var a=-1,s=e?e.length:0;if("number"==typeof s)for(;s>++a;){var o=e[a];t(r,o,i(o,a,e),e)}else sr(e,function(e,n,a){t(r,e,i(e,n,a),a)});return r}}function ne(t,e,i,n,r,a){var s=1&e,o=2&e,l=4&e,c=8&e,h=16&e,u=32&e,p=t;if(!o&&!Me(t))throw new fn;h&&!i.length&&(e&=-17,h=i=!1),u&&!n.length&&(e&=-33,u=n=!1);var g=t&&t.__bindData__;if(g)return!s||1&g[1]||(g[4]=r),!s&&1&g[1]&&(e|=8),!l||4&g[1]||(g[5]=a),h&&Nn.apply(g[2]||(g[2]=[]),i),u&&Nn.apply(g[3]||(g[3]=[]),n),g[1]|=e,ne.apply(null,g);if(!s||o||l||u||!(Fn.fastBind||Gn&&h))f=function(){var g=arguments,d=s?r:this;if((l||h||u)&&(g=Rn.call(g),h&&Tn.apply(g,i),u&&Nn.apply(g,n),l&&a>g.length))return e|=16,ne(t,c?e:-4&e,g,null,r,a);if(o&&(t=d[p]),this instanceof f){d=re(t.prototype);var m=t.apply(d,g);return je(m)?m:d}return t.apply(d,g)};else{if(h){var d=[r];Nn.apply(d,i)}var f=h?Gn.apply(t,d):Gn.call(t,r)}return Jn(f,Rn.call(arguments)),f}function re(t){return je(t)?Ln(t):{}}function ae(t){return qn[t]}function se(){var e=(e=f.indexOf)===gi?t:e;return e}function oe(t){var e,i;return t&&Sn.call(t)==Y&&(e=t.constructor,!Me(e)||e instanceof e)?(ar(t,function(t,e){i=e}),i===d||Mn.call(t,i)):!1}function le(t){return tr[t]}function ce(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Sn.call(t)==L||!1}function he(t,e,i,n){return"boolean"!=typeof e&&null!=e&&(n=i,i=e,e=!1),C(t,e,"function"==typeof i&&F(i,n,1))}function ue(t,e,i){return C(t,!0,"function"==typeof e&&F(e,i,1))}function pe(t,e,i){var n;return e=f.createCallback(e,i,3),sr(t,function(t,i,r){return e(t,i,r)?(n=i,!1):d}),n}function ge(t,e,i){var n;return e=f.createCallback(e,i,3),fe(t,function(t,i,r){return e(t,i,r)?(n=i,!1):d}),n}function de(t,e,i){var n=[];ar(t,function(t,e){n.push(e,t)});var r=n.length;for(e=F(e,i,3);r--&&e(n[r--],n[r],t)!==!1;);return t}function fe(t,e,i){var n=Kn(t),r=n.length;for(e=F(e,i,3);r--;){var a=n[r];if(e(t[a],a,t)===!1)break}return t}function me(t){var e=[];return ar(t,function(t,i){Me(t)&&e.push(i)}),e.sort()}function Ie(t,e){return t?Mn.call(t,e):!1}function ye(t){for(var e=-1,i=Kn(t),n=i.length,r={};n>++e;){var a=i[e];r[t[a]]=a}return r}function ve(t){return t===!0||t===!1||Sn.call(t)==Z}function Ce(t){return t?"object"==typeof t&&Sn.call(t)==_:!1}function be(t){return t?1===t.nodeType:!1}function Ae(t){var e=!0;if(!t)return e;var i=Sn.call(t),n=t.length;return i==B||i==V||i==L||i==Y&&"number"==typeof n&&Me(t.splice)?!n:(sr(t,function(){return e=!1}),e)}function we(t,e,i,n){return $(t,e,"function"==typeof i&&F(i,n,2))}function xe(t){return Zn(t)&&!_n(parseFloat(t))}function Me(t){return"function"==typeof t}function je(t){return!(!t||!H[typeof t])}function Ne(t){return De(t)&&t!=+t}function ke(t){return null===t}function De(t){return"number"==typeof t||Sn.call(t)==O}function ze(t){return t?"object"==typeof t&&Sn.call(t)==W:!1}function Se(t){return"string"==typeof t||Sn.call(t)==V}function Te(t){return t===d}function Ee(t){var e=arguments,i=2;if(!je(t))return t;if("number"!=typeof e[2]&&(i=e.length),i>3&&"function"==typeof e[i-2])var n=F(e[--i-1],e[i--],2);else i>2&&"function"==typeof e[i-1]&&(n=e[--i]);for(var r=Rn.call(arguments,1,i),a=-1,s=o(),l=o();i>++a;)q(t,r[a],n,s,l);return h(s),h(l),t}function Ge(t,e,i){var n=se(),r="function"==typeof e,a={};if(r)e=f.createCallback(e,i,3);else var s=Q(arguments,!0,!1,1);return ar(t,function(t,i,o){(r?!e(t,i,o):0>n(s,i))&&(a[i]=t)}),a}function Le(t){for(var e=-1,i=Kn(t),n=i.length,r=sn(n);n>++e;){var a=i[e];r[e]=[a,t[a]]}return r}function Be(t,e,i){var n={};if("function"!=typeof e)for(var r=-1,a=Q(arguments,!0,!1,1),s=je(t)?a.length:0;s>++r;){var o=a[r];o in t&&(n[o]=t[o])}else e=f.createCallback(e,i,3),ar(t,function(t,i,r){e(t,i,r)&&(n[i]=t)});return n}function Ze(t,e,i,n){var r=Qn(t);if(e=F(e,n,4),null==i)if(r)i=[];else{var a=t&&t.constructor,s=a&&a.prototype;i=re(s)}return(r?Xe:sr)(t,function(t,n,r){return e(i,t,n,r)}),i}function _e(t){for(var e=-1,i=Kn(t),n=i.length,r=sn(n);n>++e;)r[e]=t[i[e]];return r}function Pe(t){for(var e=arguments,i=-1,n=Q(e,!0,!1,1),r=e[2]&&e[2][e[1]]===t?1:n.length,a=sn(r);r>++i;)a[i]=t[n[i]];return a}function Oe(t,e,i){var n=-1,r=se(),a=t?t.length:0,s=!1;return i=(0>i?On(0,a+i):i)||0,Qn(t)?s=r(t,e,i)>-1:"number"==typeof a?s=(Se(t)?t.indexOf(e,i):r(t,e,i))>-1:sr(t,function(t){return++n>=i?!(s=t===e):d}),s}function Ye(t,e,i){var n=!0;e=f.createCallback(e,i,3);var r=-1,a=t?t.length:0;if("number"==typeof a)for(;a>++r&&(n=!!e(t[r],r,t)););else sr(t,function(t,i,r){return n=!!e(t,i,r)});return n}function We(t,e,i){var n=[];e=f.createCallback(e,i,3);var r=-1,a=t?t.length:0;if("number"==typeof a)for(;a>++r;){var s=t[r];e(s,r,t)&&n.push(s)}else sr(t,function(t,i,r){e(t,i,r)&&n.push(t)});return n}function Ve(t,e,i){e=f.createCallback(e,i,3);var n=-1,r=t?t.length:0;if("number"!=typeof r){var a;return sr(t,function(t,i,n){return e(t,i,n)?(a=t,!1):d}),a}for(;r>++n;){var s=t[n];if(e(s,n,t))return s}}function Re(t,e,i){var n;return e=f.createCallback(e,i,3),Ue(t,function(t,i,r){return e(t,i,r)?(n=t,!1):d}),n}function Xe(t,e,i){var n=-1,r=t?t.length:0;if(e=e&&i===d?e:F(e,i,3),"number"==typeof r)for(;r>++n&&e(t[n],n,t)!==!1;);else sr(t,e);return t}function Ue(t,e,i){var n=t?t.length:0;if(e=e&&i===d?e:F(e,i,3),"number"==typeof n)for(;n--&&e(t[n],n,t)!==!1;);else{var r=Kn(t);n=r.length,sr(t,function(t,i,a){return i=r?r[--n]:--n,e(a[i],i,a)})}return t}function He(t,e){var i=Rn.call(arguments,2),n=-1,r="function"==typeof e,a=t?t.length:0,s=sn("number"==typeof a?a:0);return Xe(t,function(t){s[++n]=(r?e:t[e]).apply(t,i)}),s}function Fe(t,e,i){var n=-1,r=t?t.length:0;if(e=f.createCallback(e,i,3),"number"==typeof r)for(var a=sn(r);r>++n;)a[n]=e(t[n],n,t);else a=[],sr(t,function(t,i,r){a[++n]=e(t,i,r)});return a}function Je(t,e,i){var r=-1/0,a=r;if(!e&&Qn(t))for(var s=-1,o=t.length;o>++s;){var l=t[s];l>a&&(a=l)}else e=!e&&Se(t)?n:f.createCallback(e,i,3),Xe(t,function(t,i,n){var s=e(t,i,n);s>r&&(r=s,a=t)});return a}function Qe(t,e,i){var r=1/0,a=r;if(!e&&Qn(t))for(var s=-1,o=t.length;o>++s;){var l=t[s];a>l&&(a=l)}else e=!e&&Se(t)?n:f.createCallback(e,i,3),Xe(t,function(t,i,n){var s=e(t,i,n);r>s&&(r=s,a=t)});return a}function $e(t,e){var i=-1,n=t?t.length:0;if("number"==typeof n)for(var r=sn(n);n>++i;)r[i]=t[i][e];return r||Fe(t,e)}function Ke(t,e,i,n){if(!t)return i;var r=3>arguments.length;e=F(e,n,4);var a=-1,s=t.length;if("number"==typeof s)for(r&&(i=t[++a]);s>++a;)i=e(i,t[a],a,t);else sr(t,function(t,n,a){i=r?(r=!1,t):e(i,t,n,a)});return i}function qe(t,e,i,n){var r=3>arguments.length;return e=F(e,n,4),Ue(t,function(t,n,a){i=r?(r=!1,t):e(i,t,n,a)}),i}function ti(t,e,i){return e=f.createCallback(e,i,3),We(t,function(t,i,n){return!e(t,i,n)})}function ei(t,e,i){var n=t?t.length:0;if("number"!=typeof n&&(t=_e(t)),null==e||i)return t?t[Fi(n-1)]:d;var r=ii(t);return r.length=Yn(On(0,e),r.length),r}function ii(t){var e=-1,i=t?t.length:0,n=sn("number"==typeof i?i:0);return Xe(t,function(t){var i=Fi(++e);n[e]=n[i],n[i]=t}),n}function ni(t){var e=t?t.length:0;return"number"==typeof e?e:Kn(t).length}function ri(t,e,i){var n;e=f.createCallback(e,i,3);var r=-1,a=t?t.length:0;if("number"==typeof a)for(;a>++r&&!(n=e(t[r],r,t)););else sr(t,function(t,i,r){return!(n=e(t,i,r))});return!!n}function ai(t,e,i){var n=-1,a=t?t.length:0,s=sn("number"==typeof a?a:0);for(e=f.createCallback(e,i,3),Xe(t,function(t,i,r){var a=s[++n]=l();a.criteria=e(t,i,r),a.index=n,a.value=t}),a=s.length,s.sort(r);a--;){var o=s[a];s[a]=o.value,u(o)}return s}function si(t){return t&&"number"==typeof t.length?p(t):_e(t)}function oi(t){for(var e=-1,i=t?t.length:0,n=[];i>++e;){var r=t[e];r&&n.push(r)}return n}function li(i){var n=-1,r=se(),s=i?i.length:0,o=Q(arguments,!0,!0,1),l=[],c=s>=v&&r===t;if(c){var h=a(o);h?(r=e,o=h):c=!1}for(;s>++n;){var p=i[n];0>r(o,p)&&l.push(p)}return c&&u(o),l}function ci(t,e,i){var n=-1,r=t?t.length:0;for(e=f.createCallback(e,i,3);r>++n;)if(e(t[n],n,t))return n;return-1}function hi(t,e,i){var n=t?t.length:0;for(e=f.createCallback(e,i,3);n--;)if(e(t[n],n,t))return n;return-1}function ui(t,e,i){var n=0,r=t?t.length:0;if("number"!=typeof e&&null!=e){var a=-1;for(e=f.createCallback(e,i,3);r>++a&&e(t[a],a,t);)n++}else if(n=e,null==n||i)return t?t[0]:d;return p(t,0,Yn(On(0,n),r))}function pi(t,e,i,n){return"boolean"!=typeof e&&null!=e&&(n=i,i=n&&n[e]===t?null:e,e=!1),null!=i&&(t=Fe(t,i,n)),Q(t,e)}function gi(e,i,n){if("number"==typeof n){var r=e?e.length:0;n=0>n?On(0,r+n):n||0}else if(n){var a=Ai(e,i);return e[a]===i?a:-1}return t(e,i,n)}function di(t,e,i){var n=0,r=t?t.length:0;if("number"!=typeof e&&null!=e){var a=r;for(e=f.createCallback(e,i,3);a--&&e(t[a],a,t);)n++}else n=null==e||i?1:e||n;return p(t,0,Yn(On(0,r-n),r))}function fi(i){for(var n=arguments,r=n.length,s=-1,l=o(),c=-1,p=se(),g=i?i.length:0,d=[],f=o();r>++s;){var m=n[s];l[s]=p===t&&(m?m.length:0)>=v&&a(s?n[s]:f)}t:for(;g>++c;){var I=l[0];if(m=i[c],0>(I?e(I,m):p(f,m))){for(s=r,(I||f).push(m);--s;)if(I=l[s],0>(I?e(I,m):p(n[s],m)))continue t;d.push(m)}}for(;r--;)I=l[r],I&&u(I);return h(l),h(f),d}function mi(t,e,i){var n=0,r=t?t.length:0;if("number"!=typeof e&&null!=e){var a=r;for(e=f.createCallback(e,i,3);a--&&e(t[a],a,t);)n++}else if(n=e,null==n||i)return t?t[r-1]:d;return p(t,On(0,r-n))}function Ii(t,e,i){var n=t?t.length:0;for("number"==typeof i&&(n=(0>i?On(0,n+i):Yn(i,n-1))+1);n--;)if(t[n]===e)return n;return-1}function yi(t){for(var e=arguments,i=0,n=e.length,r=t?t.length:0;n>++i;)for(var a=-1,s=e[i];r>++a;)t[a]===s&&(zn.call(t,a--,1),r--);return t}function vi(t,e,i){t=+t||0,i="number"==typeof i?i:+i||1,null==e&&(e=t,t=0);for(var n=-1,r=On(0,Cn((e-t)/(i||1))),a=sn(r);r>++n;)a[n]=t,t+=i;return a}function Ci(t,e,i){var n=-1,r=t?t.length:0,a=[];for(e=f.createCallback(e,i,3);r>++n;){var s=t[n];e(s,n,t)&&(a.push(s),zn.call(t,n--,1),r--)}return a}function bi(t,e,i){if("number"!=typeof e&&null!=e){var n=0,r=-1,a=t?t.length:0;for(e=f.createCallback(e,i,3);a>++r&&e(t[r],r,t);)n++}else n=null==e||i?1:On(0,e);return p(t,n)}function Ai(t,e,i,n){var r=0,a=t?t.length:r;for(i=i?f.createCallback(i,n,1):Xi,e=i(e);a>r;){var s=r+a>>>1;e>i(t[s])?r=s+1:a=s}return r}function wi(){return ee(Q(arguments,!0,!0))}function xi(t,e,i,n){return"boolean"!=typeof e&&null!=e&&(n=i,i=n&&n[e]===t?null:e,e=!1),null!=i&&(i=f.createCallback(i,n,3)),ee(t,e,i)}function Mi(t){return li(t,Rn.call(arguments,1))}function ji(){for(var t=arguments.length>1?arguments:arguments[0],e=-1,i=t?Je($e(t,"length")):0,n=sn(0>i?0:i);i>++e;)n[e]=$e(t,e);return n}function Ni(t,e){for(var i=-1,n=t?t.length:0,r={};n>++i;){var a=t[i];e?r[a]=e[i]:a&&(r[a[0]]=a[1])}return r}function ki(t,e){if(!Me(e))throw new fn;return function(){return 1>--t?e.apply(this,arguments):d}}function Di(t,e){return arguments.length>2?ne(t,17,Rn.call(arguments,2),null,e):ne(t,1,null,null,e)}function zi(t){for(var e=arguments.length>1?Q(arguments,!0,!1,1):me(t),i=-1,n=e.length;n>++i;){var r=e[i];t[r]=ne(t[r],1,null,null,t)}return t}function Si(t,e){return arguments.length>2?ne(e,19,Rn.call(arguments,2),null,t):ne(e,3,null,null,t)}function Ti(){for(var t=arguments,e=t.length;e--;)if(!Me(t[e]))throw new fn;return function(){for(var e=arguments,i=t.length;i--;)e=[t[i].apply(this,e)];return e[0]}}function Ei(t,e,i){var n=typeof t;if(null==t||"function"==n)return F(t,e,i);if("object"!=n)return function(e){return e[t]};var r=Kn(t),a=r[0],s=t[a];return 1!=r.length||s!==s||je(s)?function(e){for(var i=r.length,n=!1;i--&&(n=$(e[r[i]],t[r[i]],null,!0)););return n}:function(t){var e=t[a];return s===e&&(0!==s||1/s==1/e)}}function Gi(t,e){return e="number"==typeof e?e:+e||t.length,ne(t,4,null,null,null,e)}function Li(t,e,i){var n,r,a,s,o,l,c,h=0,u=!1,p=!0;if(!Me(t))throw new fn;if(e=On(0,e)||0,i===!0){var g=!0;p=!1}else je(i)&&(g=i.leading,u="maxWait"in i&&(On(e,i.maxWait)||0),p="trailing"in i?i.trailing:p);var f=function(){var i=e-(jn()-s);if(0>=i){r&&bn(r);var u=c;r=l=c=d,u&&(h=jn(),a=t.apply(o,n))}else l=Dn(f,i)},m=function(){l&&bn(l),r=l=c=d,(p||u!==e)&&(h=jn(),a=t.apply(o,n))};return function(){if(n=arguments,s=jn(),o=this,c=p&&(l||!g),u===!1)var i=g&&!l;else{r||g||(h=s);var d=u-(s-h);0>=d?(r&&(r=bn(r)),h=s,a=t.apply(o,n)):r||(r=Dn(m,d))}return l||e===u||(l=Dn(f,e)),i&&(a=t.apply(o,n)),a}}function Bi(t){if(!Me(t))throw new fn;var e=Rn.call(arguments,1);return Dn(function(){t.apply(d,e)},1)}function Zi(t,e){if(!Me(t))throw new fn;var i=Rn.call(arguments,2);return Dn(function(){t.apply(d,i)},e)}function _i(t,e){if(!Me(t))throw new fn;var i=function(){var n=i.cache,r=e?e.apply(this,arguments):y+arguments[0];return Mn.call(n,r)?n[r]:n[r]=t.apply(this,arguments)};return i.cache={},i}function Pi(t){var e,i;if(!Me(t))throw new fn;return function(){return e?i:(e=!0,i=t.apply(this,arguments),t=null,i)}}function Oi(t){return ne(t,16,Rn.call(arguments,1))}function Yi(t){return ne(t,32,null,Rn.call(arguments,1))}function Wi(t,e,i){var n=!0,r=!0;if(!Me(t))throw new fn;i===!1?n=!1:je(i)&&(n="leading"in i?i.leading:n,r="trailing"in i?i.trailing:r),X.leading=n,X.maxWait=e,X.trailing=r;var a=Li(t,e,X);return a}function Vi(t,e){if(!Me(e))throw new fn;return function(){var i=[t];return Nn.apply(i,arguments),e.apply(this,i)}}function Ri(t){return null==t?"":dn(t).replace(ir,ae)}function Xi(t){return t}function Ui(t,e){var i=t,n=!e||Me(i);e||(i=m,e=t,t=f),Xe(me(e),function(r){var a=t[r]=e[r];n&&(i.prototype[r]=function(){var e=this.__wrapped__,n=[e];Nn.apply(n,arguments);var r=a.apply(t,n);return e&&"object"==typeof e&&e===r?this:(r=new i(r),r.__chain__=this.__chain__,r)})})}function Hi(){return i._=yn,this}function Fi(t,e,i){var n=null==t,r=null==e;null==i&&("boolean"==typeof t&&r?(i=t,t=1):r||"boolean"!=typeof e||(i=e,r=!0)),n&&r&&(e=1),t=+t||0,r?(e=t,t=0):e=+e||0;var a=Vn();return i||t%1||e%1?Yn(t+a*(e-t+parseFloat("1e-"+((a+"").length-1))),e):t+An(a*(e-t+1))}function Ji(t,e){if(t){var i=t[e];return Me(i)?t[e]():i}}function Qi(t,e,i){var n=f.templateSettings;t||(t=""),i=rr({},i,n);var r,a=rr({},i.imports,n.imports),o=Kn(a),l=_e(a),c=0,h=i.interpolate||z,u="__p += '",p=gn((i.escape||z).source+"|"+h.source+"|"+(h===k?M:z).source+"|"+(i.evaluate||z).source+"|$","g");t.replace(p,function(e,i,n,a,o,l){return n||(n=a),u+=t.slice(c,l).replace(T,s),i&&(u+="' +\n__e("+i+") +\n'"),o&&(r=!0,u+="';\n"+o+";\n__p += '"),n&&(u+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),c=l+e.length,e}),u+="';\n";var g=i.variable,m=g;m||(g="obj",u="with ("+g+") {\n"+u+"\n}\n"),u=(r?u.replace(A,""):u).replace(w,"$1").replace(x,"$1;"),u="function("+g+") {\n"+(m?"":g+" || ("+g+" = {});\n")+"var __t, __p = '', __e = _.escape"+(r?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+u+"return __p\n}";var I="\n/*\n//# sourceURL="+(i.sourceURL||"/lodash/template/source["+G++ +"]")+"\n*/";try{var y=cn(o,"return "+u+I).apply(d,l)}catch(v){throw v.source=u,v}return e?y(e):(y.source=u,y)}function $i(t,e,i){t=(t=+t)>-1?t:0;var n=-1,r=sn(t);for(e=F(e,i,1);t>++n;)r[n]=e(n);return r}function Ki(t){return null==t?"":dn(t).replace(er,le)}function qi(t){var e=++I;return dn(null==t?"":t)+e}function tn(t){return t=new m(t),t.__chain__=!0,t}function en(t,e){return e(t),t}function nn(){return this.__chain__=!0,this}function rn(){return dn(this.__wrapped__)}function an(){return this.__wrapped__}i=i?te.defaults(J.Object(),i,te.pick(J,E)):J;var sn=i.Array,on=i.Boolean,ln=i.Date,cn=i.Function,hn=i.Math,un=i.Number,pn=i.Object,gn=i.RegExp,dn=i.String,fn=i.TypeError,mn=[],In=pn.prototype,yn=i._,vn=gn("^"+dn(In.valueOf).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),Cn=hn.ceil,bn=i.clearTimeout,An=hn.floor,wn=cn.prototype.toString,xn=vn.test(xn=pn.getPrototypeOf)&&xn,Mn=In.hasOwnProperty,jn=vn.test(jn=ln.now)&&jn||function(){return+new ln},Nn=mn.push,kn=i.setImmediate,Dn=i.setTimeout,zn=mn.splice,Sn=In.toString,Tn=mn.unshift,En=function(){try{var t={},e=vn.test(e=pn.defineProperty)&&e,i=e(t,t,t)&&e}catch(n){}return i}(),Gn=vn.test(Gn=Sn.bind)&&Gn,Ln=vn.test(Ln=pn.create)&&Ln,Bn=vn.test(Bn=sn.isArray)&&Bn,Zn=i.isFinite,_n=i.isNaN,Pn=vn.test(Pn=pn.keys)&&Pn,On=hn.max,Yn=hn.min,Wn=i.parseInt,Vn=hn.random,Rn=mn.slice,Xn=vn.test(i.attachEvent),Un=Gn&&!/\n|true/.test(Gn+Xn),Hn={};Hn[B]=sn,Hn[Z]=on,Hn[_]=ln,Hn[P]=cn,Hn[Y]=pn,Hn[O]=un,Hn[W]=gn,Hn[V]=dn,m.prototype=f.prototype;var Fn=f.support={};Fn.fastBind=Gn&&!Un,Fn.funcDecomp=!vn.test(i.WinRTError)&&S.test(g),Fn.funcNames="string"==typeof cn.name,f.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:k,variable:"",imports:{_:f}},Ln||(re=function(t){if(je(t)){c.prototype=t;var e=new c;c.prototype=null}return e||{}});var Jn=En?function(t,e){U.value=e,En(t,"__bindData__",U)}:c,Qn=Bn||function(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Sn.call(t)==B||!1},$n=function(t){var e,i=t,n=[];if(!i)return n;if(!H[typeof t])return n;for(e in i)Mn.call(i,e)&&n.push(e);return n},Kn=Pn?function(t){return je(t)?Pn(t):[]}:$n,qn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},tr=ye(qn),er=gn("("+Kn(tr).join("|")+")","g"),ir=gn("["+Kn(qn).join("")+"]","g"),nr=function(t,e,i){var n,r=t,a=r;if(!r)return a;var s=arguments,o=0,l="number"==typeof i?2:s.length;if(l>3&&"function"==typeof s[l-2])var c=F(s[--l-1],s[l--],2);else l>2&&"function"==typeof s[l-1]&&(c=s[--l]);for(;l>++o;)if(r=s[o],r&&H[typeof r])for(var h=-1,u=H[typeof r]&&Kn(r),p=u?u.length:0;p>++h;)n=u[h],a[n]=c?c(a[n],r[n]):r[n];return a},rr=function(t,e,i){var n,r=t,a=r;if(!r)return a;for(var s=arguments,o=0,l="number"==typeof i?2:s.length;l>++o;)if(r=s[o],r&&H[typeof r])for(var c=-1,h=H[typeof r]&&Kn(r),u=h?h.length:0;u>++c;)n=h[c],a[n]===d&&(a[n]=r[n]);return a},ar=function(t,e,i){var n,r=t,a=r;if(!r)return a;if(!H[typeof r])return a;e=e&&i===d?e:F(e,i,3);for(n in r)if(e(r[n],n,t)===!1)return a;return a},sr=function(t,e,i){var n,r=t,a=r;if(!r)return a;if(!H[typeof r])return a;e=e&&i===d?e:F(e,i,3);for(var s=-1,o=H[typeof r]&&Kn(r),l=o?o.length:0;l>++s;)if(n=o[s],e(r[n],n,t)===!1)return a;return a},or=function(t){if(!t||Sn.call(t)!=Y)return!1;var e=t.valueOf,i="function"==typeof e&&(i=xn(e))&&xn(i);return i?t==i||xn(t)==i:oe(t)},lr=ie(function(t,e,i){Mn.call(t,i)?t[i]++:t[i]=1}),cr=ie(function(t,e,i){(Mn.call(t,i)?t[i]:t[i]=[]).push(e)}),hr=ie(function(t,e,i){t[i]=e}),ur=We;Un&&K&&"function"==typeof kn&&(Bi=function(t){if(!Me(t))throw new fn;return kn.apply(i,arguments)});var pr=8==Wn(b+"08")?Wn:function(t,e){return Wn(Se(t)?t.replace(D,""):t,e||0)};return f.after=ki,f.assign=nr,f.at=Pe,f.bind=Di,f.bindAll=zi,f.bindKey=Si,f.chain=tn,f.compact=oi,f.compose=Ti,f.countBy=lr,f.createCallback=Ei,f.curry=Gi,f.debounce=Li,f.defaults=rr,f.defer=Bi,f.delay=Zi,f.difference=li,f.filter=We,f.flatten=pi,f.forEach=Xe,f.forEachRight=Ue,f.forIn=ar,f.forInRight=de,f.forOwn=sr,f.forOwnRight=fe,f.functions=me,f.groupBy=cr,f.indexBy=hr,f.initial=di,f.intersection=fi,f.invert=ye,f.invoke=He,f.keys=Kn,f.map=Fe,f.max=Je,f.memoize=_i,f.merge=Ee,f.min=Qe,f.omit=Ge,f.once=Pi,f.pairs=Le,f.partial=Oi,f.partialRight=Yi,f.pick=Be,f.pluck=$e,f.pull=yi,f.range=vi,f.reject=ti,f.remove=Ci,f.rest=bi,f.shuffle=ii,f.sortBy=ai,f.tap=en,f.throttle=Wi,f.times=$i,f.toArray=si,f.transform=Ze,f.union=wi,f.uniq=xi,f.values=_e,f.where=ur,f.without=Mi,f.wrap=Vi,f.zip=ji,f.zipObject=Ni,f.collect=Fe,f.drop=bi,f.each=Xe,f.eachRight=Ue,f.extend=nr,f.methods=me,f.object=Ni,f.select=We,f.tail=bi,f.unique=xi,f.unzip=ji,Ui(f),f.clone=he,f.cloneDeep=ue,f.contains=Oe,f.escape=Ri,f.every=Ye,f.find=Ve,f.findIndex=ci,f.findKey=pe,f.findLast=Re,f.findLastIndex=hi,f.findLastKey=ge,f.has=Ie,f.identity=Xi,f.indexOf=gi,f.isArguments=ce,f.isArray=Qn,f.isBoolean=ve,f.isDate=Ce,f.isElement=be,f.isEmpty=Ae,f.isEqual=we,f.isFinite=xe,f.isFunction=Me,f.isNaN=Ne,f.isNull=ke,f.isNumber=De,f.isObject=je,f.isPlainObject=or,f.isRegExp=ze,f.isString=Se,f.isUndefined=Te,f.lastIndexOf=Ii,f.mixin=Ui,f.noConflict=Hi,f.parseInt=pr,f.random=Fi,f.reduce=Ke,f.reduceRight=qe,f.result=Ji,f.runInContext=g,f.size=ni,f.some=ri,f.sortedIndex=Ai,f.template=Qi,f.unescape=Ki,f.uniqueId=qi,f.all=Ye,f.any=ri,f.detect=Ve,f.findWhere=Ve,f.foldl=Ke,f.foldr=qe,f.include=Oe,f.inject=Ke,sr(f,function(t,e){f.prototype[e]||(f.prototype[e]=function(){var e=[this.__wrapped__],i=this.__chain__;Nn.apply(e,arguments);var n=t.apply(f,e);return i?new m(n,i):n})}),f.first=ui,f.last=mi,f.sample=ei,f.take=ui,f.head=ui,sr(f,function(t,e){var i="sample"!==e;f.prototype[e]||(f.prototype[e]=function(e,n){var r=this.__chain__,a=t(this.__wrapped__,e,n);return r||null!=e&&(!n||i&&"function"==typeof e)?new m(a,r):a})}),f.VERSION="2.2.1",f.prototype.chain=nn,f.prototype.toString=rn,f.prototype.value=an,f.prototype.valueOf=an,Xe(["join","pop","shift"],function(t){var e=mn[t];f.prototype[t]=function(){var t=this.__chain__,i=e.apply(this.__wrapped__,arguments);return t?new m(i,t):i}}),Xe(["push","reverse","sort","unshift"],function(t){var e=mn[t];f.prototype[t]=function(){return e.apply(this.__wrapped__,arguments),this}}),Xe(["concat","slice","splice"],function(t){var e=mn[t];f.prototype[t]=function(){return new m(e.apply(this.__wrapped__,arguments),this.__chain__)}}),f}var d,f=[],m=[],I=0,y=+new Date+"",v=75,C=40,b="      \v\f \n\r\u2028\u2029 ᠎              ",A=/\b__p \+= '';/g,w=/\b(__p \+=) '' \+/g,x=/(__e\(.*?\)|\b__t\)) \+\n'';/g,M=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,j=/\w*$/,N=/^function[ \n\r\t]+\w/,k=/<%=([\s\S]+?)%>/g,D=RegExp("^["+b+"]*0+(?=.$)"),z=/($^)/,S=/\bthis\b/,T=/['\n\r\t\u2028\u2029\\]/g,E=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setImmediate","setTimeout"],G=0,L="[object Arguments]",B="[object Array]",Z="[object Boolean]",_="[object Date]",P="[object Function]",O="[object Number]",Y="[object Object]",W="[object RegExp]",V="[object String]",R={};R[P]=!1,R[L]=R[B]=R[Z]=R[_]=R[O]=R[Y]=R[W]=R[V]=!0;var X={leading:!1,maxWait:0,trailing:!1},U={configurable:!1,enumerable:!1,value:null,writable:!1},H={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},F={"\\":"\\","'":"'","\n":"n","\r":"r","        ":"t","\u2028":"u2028","\u2029":"u2029"},J=H[typeof window]&&window||this,Q=H[typeof exports]&&exports&&!exports.nodeType&&exports,$=H[typeof module]&&module&&!module.nodeType&&module,K=$&&$.exports===Q&&Q,q=H[typeof global]&&global;!q||q.global!==q&&q.window!==q||(J=q);var te=g();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(J._=te,define(function(){return te})):Q&&$?K?($.exports=te)._=te:Q._=te:J._=te}.call(this),function(){var t,e=this,i=e.Backbone,n=[],r=n.push,a=n.slice,s=n.splice;t="undefined"!=typeof exports?exports:e.Backbone={},t.VERSION="1.0.0";var o=e._;o||"undefined"==typeof require||(o=require("underscore")),t.$=e.jQuery||e.Zepto||e.ender||e.$,t.noConflict=function(){return e.Backbone=i,this},t.emulateHTTP=!1,t.emulateJSON=!1;var l=t.Events={on:function(t,e,i){if(!h(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var n=this._events[t]||(this._events[t]=[]);return n.push({callback:e,context:i,ctx:i||this}),this},once:function(t,e,i){if(!h(this,"once",t,[e,i])||!e)return this;var n=this,r=o.once(function(){n.off(t,r),e.apply(this,arguments)});return r._callback=e,this.on(t,r,i)},off:function(t,e,i){var n,r,a,s,l,c,u,p;if(!this._events||!h(this,"off",t,[e,i]))return this;if(!t&&!e&&!i)return this._events={},this;for(s=t?[t]:o.keys(this._events),l=0,c=s.length;c>l;l++)if(t=s[l],a=this._events[t]){if(this._events[t]=n=[],e||i)for(u=0,p=a.length;p>u;u++)r=a[u],(e&&e!==r.callback&&e!==r.callback._callback||i&&i!==r.context)&&n.push(r);n.length||delete this._events[t]}return this},trigger:function(t){if(!this._events)return this;var e=a.call(arguments,1);if(!h(this,"trigger",t,e))return this;var i=this._events[t],n=this._events.all;return i&&u(i,e),n&&u(n,arguments),this},stopListening:function(t,e,i){var n=this._listeners;if(!n)return this;var r=!e&&!i;"object"==typeof e&&(i=this),t&&((n={})[t._listenerId]=t);for(var a in n)n[a].off(e,i,this),r&&delete this._listeners[a];return this}},c=/\s+/,h=function(t,e,i,n){if(!i)return!0;if("object"==typeof i){for(var r in i)t[e].apply(t,[r,i[r]].concat(n));return!1}if(c.test(i)){for(var a=i.split(c),s=0,o=a.length;o>s;s++)t[e].apply(t,[a[s]].concat(n));return!1}return!0},u=function(t,e){var i,n=-1,r=t.length,a=e[0],s=e[1],o=e[2];switch(e.length){case 0:for(;r>++n;)(i=t[n]).callback.call(i.ctx);return;case 1:for(;r>++n;)(i=t[n]).callback.call(i.ctx,a);return;case 2:for(;r>++n;)(i=t[n]).callback.call(i.ctx,a,s);return;case 3:for(;r>++n;)(i=t[n]).callback.call(i.ctx,a,s,o);return;default:for(;r>++n;)(i=t[n]).callback.apply(i.ctx,e)}},p={listenTo:"on",listenToOnce:"once"};o.each(p,function(t,e){l[e]=function(e,i,n){var r=this._listeners||(this._listeners={}),a=e._listenerId||(e._listenerId=o.uniqueId("l"));return r[a]=e,"object"==typeof i&&(n=this),e[t](i,n,this),this}}),l.bind=l.on,l.unbind=l.off,o.extend(t,l);var g=t.Model=function(t,e){var i,n=t||{};e||(e={}),this.cid=o.uniqueId("c"),this.attributes={},o.extend(this,o.pick(e,d)),e.parse&&(n=this.parse(n,e)||{}),(i=o.result(this,"defaults"))&&(n=o.defaults({},n,i)),this.set(n,e),this.changed={},this.initialize.apply(this,arguments)},d=["url","urlRoot","collection"];o.extend(g.prototype,l,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(){return o.clone(this.attributes)},sync:function(){return t.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return o.escape(this.get(t))},has:function(t){return null!=this.get(t)},set:function(t,e,i){var n,r,a,s,l,c,h,u;if(null==t)return this;if("object"==typeof t?(r=t,i=e):(r={})[t]=e,i||(i={}),!this._validate(r,i))return!1;a=i.unset,l=i.silent,s=[],c=this._changing,this._changing=!0,c||(this._previousAttributes=o.clone(this.attributes),this.changed={}),u=this.attributes,h=this._previousAttributes,this.idAttribute in r&&(this.id=r[this.idAttribute]);for(n in r)e=r[n],o.isEqual(u[n],e)||s.push(n),o.isEqual(h[n],e)?delete this.changed[n]:this.changed[n]=e,a?delete u[n]:u[n]=e;if(!l){s.length&&(this._pending=!0);for(var p=0,g=s.length;g>p;p++)this.trigger("change:"+s[p],this,u[s[p]],i)}if(c)return this;if(!l)for(;this._pending;)this._pending=!1,this.trigger("change",this,i);return this._pending=!1,this._changing=!1,this},unset:function(t,e){return this.set(t,void 0,o.extend({},e,{unset:!0}))},clear:function(t){var e={};for(var i in this.attributes)e[i]=void 0;return this.set(e,o.extend({},t,{unset:!0}))},hasChanged:function(t){return null==t?!o.isEmpty(this.changed):o.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?o.clone(this.changed):!1;var e,i=!1,n=this._changing?this._previousAttributes:this.attributes;for(var r in t)o.isEqual(n[r],e=t[r])||((i||(i={}))[r]=e);return i},previous:function(t){return null!=t&&this._previousAttributes?this._previousAttributes[t]:null},previousAttributes:function(){return o.clone(this._previousAttributes)},fetch:function(t){t=t?o.clone(t):{},void 0===t.parse&&(t.parse=!0);var e=this,i=t.success;return t.success=function(n){return e.set(e.parse(n,t),t)?(i&&i(e,n,t),e.trigger("sync",e,n,t),void 0):!1},Z(this,t),this.sync("read",this,t)},save:function(t,e,i){var n,r,a,s=this.attributes;if(null==t||"object"==typeof t?(n=t,i=e):(n={})[t]=e,!(!n||i&&i.wait||this.set(n,i)))return!1;if(i=o.extend({validate:!0},i),!this._validate(n,i))return!1;n&&i.wait&&(this.attributes=o.extend({},s,n)),void 0===i.parse&&(i.parse=!0);var l=this,c=i.success;return i.success=function(t){l.attributes=s;var e=l.parse(t,i);return i.wait&&(e=o.extend(n||{},e)),o.isObject(e)&&!l.set(e,i)?!1:(c&&c(l,t,i),l.trigger("sync",l,t,i),void 0)},Z(this,i),r=this.isNew()?"create":i.patch?"patch":"update","patch"===r&&(i.attrs=n),a=this.sync(r,this,i),n&&i.wait&&(this.attributes=s),a},destroy:function(t){t=t?o.clone(t):{};var e=this,i=t.success,n=function(){e.trigger("destroy",e,e.collection,t)};if(t.success=function(r){(t.wait||e.isNew())&&n(),i&&i(e,r,t),e.isNew()||e.trigger("sync",e,r,t)},this.isNew())return t.success(),!1;Z(this,t);var r=this.sync("delete",this,t);return t.wait||n(),r},url:function(){var t=o.result(this,"urlRoot")||o.result(this.collection,"url")||B();return this.isNew()?t:t+("/"===t.charAt(t.length-1)?"":"/")+encodeURIComponent(this.id)},parse:function(t){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return null==this.id},isValid:function(t){return this._validate({},o.extend(t||{},{validate:!0}))},_validate:function(t,e){if(!e.validate||!this.validate)return!0;t=o.extend({},this.attributes,t);var i=this.validationError=this.validate(t,e)||null;return i?(this.trigger("invalid",this,i,o.extend(e||{},{validationError:i})),!1):!0}});var f=["keys","values","pairs","invert","pick","omit"];o.each(f,function(t){g.prototype[t]=function(){var e=a.call(arguments);return e.unshift(this.attributes),o[t].apply(o,e)}});var m=t.Collection=function(t,e){e||(e={}),e.url&&(this.url=e.url),e.model&&(this.model=e.model),void 0!==e.comparator&&(this.comparator=e.comparator),this._reset(),this.initialize.apply(this,arguments),t&&this.reset(t,o.extend({silent:!0},e))},I={add:!0,remove:!0,merge:!0},y={add:!0,merge:!1,remove:!1};o.extend(m.prototype,l,{model:g,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return t.sync.apply(this,arguments)},add:function(t,e){return this.set(t,o.defaults(e||{},y))},remove:function(t,e){t=o.isArray(t)?t.slice():[t],e||(e={});var i,n,r,a;for(i=0,n=t.length;n>i;i++)a=this.get(t[i]),a&&(delete this._byId[a.id],delete this._byId[a.cid],r=this.indexOf(a),this.models.splice(r,1),this.length--,e.silent||(e.index=r,a.trigger("remove",a,this,e)),this._removeReference(a));return this},set:function(t,e){e=o.defaults(e||{},I),e.parse&&(t=this.parse(t,e)),o.isArray(t)||(t=t?[t]:[]);var i,n,a,l,c,h=e.at,u=this.comparator&&null==h&&e.sort!==!1,p=o.isString(this.comparator)?this.comparator:null,g=[],d=[],f={};for(i=0,n=t.length;n>i;i++)(a=this._prepareModel(t[i],e))&&((l=this.get(a))?(e.remove&&(f[l.cid]=!0),e.merge&&(l.set(a.attributes,e),u&&!c&&l.hasChanged(p)&&(c=!0))):e.add&&(g.push(a),a.on("all",this._onModelEvent,this),this._byId[a.cid]=a,null!=a.id&&(this._byId[a.id]=a)));if(e.remove){for(i=0,n=this.length;n>i;++i)f[(a=this.models[i]).cid]||d.push(a);d.length&&this.remove(d,e)}if(g.length&&(u&&(c=!0),this.length+=g.length,null!=h?s.apply(this.models,[h,0].concat(g)):r.apply(this.models,g)),c&&this.sort({silent:!0}),e.silent)return this;for(i=0,n=g.length;n>i;i++)(a=g[i]).trigger("add",a,this,e);return c&&this.trigger("sort",this,e),this},reset:function(t,e){e||(e={});for(var i=0,n=this.models.length;n>i;i++)this._removeReference(this.models[i]);return e.previousModels=this.models,this._reset(),this.add(t,o.extend({silent:!0},e)),e.silent||this.trigger("reset",this,e),this},push:function(t,e){return t=this._prepareModel(t,e),this.add(t,o.extend({at:this.length},e)),t},pop:function(t){var e=this.at(this.length-1);return this.remove(e,t),e},unshift:function(t,e){return t=this._prepareModel(t,e),this.add(t,o.extend({at:0},e)),t},shift:function(t){var e=this.at(0);return this.remove(e,t),e},slice:function(t,e){return this.models.slice(t,e)},get:function(t){return null==t?void 0:this._byId[null!=t.id?t.id:t.cid||t]},at:function(t){return this.models[t]},where:function(t,e){return o.isEmpty(t)?e?void 0:[]:this[e?"find":"filter"](function(e){for(var i in t)if(t[i]!==e.get(i))return!1;return!0})},findWhere:function(t){return this.where(t,!0)
+},sort:function(t){if(!this.comparator)throw Error("Cannot sort a set without a comparator");return t||(t={}),o.isString(this.comparator)||1===this.comparator.length?this.models=this.sortBy(this.comparator,this):this.models.sort(o.bind(this.comparator,this)),t.silent||this.trigger("sort",this,t),this},sortedIndex:function(t,e,i){e||(e=this.comparator);var n=o.isFunction(e)?e:function(t){return t.get(e)};return o.sortedIndex(this.models,t,n,i)},pluck:function(t){return o.invoke(this.models,"get",t)},fetch:function(t){t=t?o.clone(t):{},void 0===t.parse&&(t.parse=!0);var e=t.success,i=this;return t.success=function(n){var r=t.reset?"reset":"set";i[r](n,t),e&&e(i,n,t),i.trigger("sync",i,n,t)},Z(this,t),this.sync("read",this,t)},create:function(t,e){if(e=e?o.clone(e):{},!(t=this._prepareModel(t,e)))return!1;e.wait||this.add(t,e);var i=this,n=e.success;return e.success=function(r){e.wait&&i.add(t,e),n&&n(t,r,e)},t.save(null,e),t},parse:function(t){return t},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0,this.models=[],this._byId={}},_prepareModel:function(t,e){if(t instanceof g)return t.collection||(t.collection=this),t;e||(e={}),e.collection=this;var i=new this.model(t,e);return i._validate(t,e)?i:(this.trigger("invalid",this,t,e),!1)},_removeReference:function(t){this===t.collection&&delete t.collection,t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,n){("add"!==t&&"remove"!==t||i===this)&&("destroy"===t&&this.remove(e,n),e&&t==="change:"+e.idAttribute&&(delete this._byId[e.previous(e.idAttribute)],null!=e.id&&(this._byId[e.id]=e)),this.trigger.apply(this,arguments))}});var v=["forEach","each","map","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","max","min","toArray","size","first","head","take","initial","rest","tail","drop","last","without","indexOf","shuffle","lastIndexOf","isEmpty","chain"];o.each(v,function(t){m.prototype[t]=function(){var e=a.call(arguments);return e.unshift(this.models),o[t].apply(o,e)}});var C=["groupBy","countBy","sortBy"];o.each(C,function(t){m.prototype[t]=function(e,i){var n=o.isFunction(e)?e:function(t){return t.get(e)};return o[t](this.models,n,i)}});var b=t.View=function(t){this.cid=o.uniqueId("view"),this._configure(t||{}),this._ensureElement(),this.initialize.apply(this,arguments),this.delegateEvents()},A=/^(\S+)\s*(.*)$/,w=["model","collection","el","id","attributes","className","tagName","events"];o.extend(b.prototype,l,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){return this.$el.remove(),this.stopListening(),this},setElement:function(e,i){return this.$el&&this.undelegateEvents(),this.$el=e instanceof t.$?e:t.$(e),this.el=this.$el[0],i!==!1&&this.delegateEvents(),this},delegateEvents:function(t){if(!t&&!(t=o.result(this,"events")))return this;this.undelegateEvents();for(var e in t){var i=t[e];if(o.isFunction(i)||(i=this[t[e]]),i){var n=e.match(A),r=n[1],a=n[2];i=o.bind(i,this),r+=".delegateEvents"+this.cid,""===a?this.$el.on(r,i):this.$el.on(r,a,i)}}return this},undelegateEvents:function(){return this.$el.off(".delegateEvents"+this.cid),this},_configure:function(t){this.options&&(t=o.extend({},o.result(this,"options"),t)),o.extend(this,o.pick(t,w)),this.options=t},_ensureElement:function(){if(this.el)this.setElement(o.result(this,"el"),!1);else{var e=o.extend({},o.result(this,"attributes"));this.id&&(e.id=o.result(this,"id")),this.className&&(e["class"]=o.result(this,"className"));var i=t.$("<"+o.result(this,"tagName")+">").attr(e);this.setElement(i,!1)}}}),t.sync=function(e,i,n){var r=x[e];o.defaults(n||(n={}),{emulateHTTP:t.emulateHTTP,emulateJSON:t.emulateJSON});var a={type:r,dataType:"json"};if(n.url||(a.url=o.result(i,"url")||B()),null!=n.data||!i||"create"!==e&&"update"!==e&&"patch"!==e||(a.contentType="application/json",a.data=JSON.stringify(n.attrs||i.toJSON(n))),n.emulateJSON&&(a.contentType="application/x-www-form-urlencoded",a.data=a.data?{model:a.data}:{}),n.emulateHTTP&&("PUT"===r||"DELETE"===r||"PATCH"===r)){a.type="POST",n.emulateJSON&&(a.data._method=r);var s=n.beforeSend;n.beforeSend=function(t){return t.setRequestHeader("X-HTTP-Method-Override",r),s?s.apply(this,arguments):void 0}}"GET"===a.type||n.emulateJSON||(a.processData=!1),"PATCH"!==a.type||!window.ActiveXObject||window.external&&window.external.msActiveXFilteringEnabled||(a.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")});var l=n.xhr=t.ajax(o.extend(a,n));return i.trigger("request",i,l,n),l};var x={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};t.ajax=function(){return t.$.ajax.apply(t.$,arguments)};var M=t.Router=function(t){t||(t={}),t.routes&&(this.routes=t.routes),this._bindRoutes(),this.initialize.apply(this,arguments)},j=/\((.*?)\)/g,N=/(\(\?)?:\w+/g,k=/\*\w+/g,D=/[\-{}\[\]+?.,\\\^$|#\s]/g;o.extend(M.prototype,l,{initialize:function(){},route:function(e,i,n){o.isRegExp(e)||(e=this._routeToRegExp(e)),o.isFunction(i)&&(n=i,i=""),n||(n=this[i]);var r=this;return t.history.route(e,function(a){var s=r._extractParameters(e,a);n&&n.apply(r,s),r.trigger.apply(r,["route:"+i].concat(s)),r.trigger("route",i,s),t.history.trigger("route",r,i,s)}),this},navigate:function(e,i){return t.history.navigate(e,i),this},_bindRoutes:function(){if(this.routes){this.routes=o.result(this,"routes");for(var t,e=o.keys(this.routes);null!=(t=e.pop());)this.route(t,this.routes[t])}},_routeToRegExp:function(t){return t=t.replace(D,"\\$&").replace(j,"(?:$1)?").replace(N,function(t,e){return e?t:"([^/]+)"}).replace(k,"(.*?)"),RegExp("^"+t+"$")},_extractParameters:function(t,e){var i=t.exec(e).slice(1);return o.map(i,function(t){return t?decodeURIComponent(t):null})}});var z=t.History=function(){this.handlers=[],o.bindAll(this,"checkUrl"),"undefined"!=typeof window&&(this.location=window.location,this.history=window.history)},S=/^[#\/]|\s+$/g,T=/^\/+|\/+$/g,E=/msie [\w.]+/,G=/\/$/;z.started=!1,o.extend(z.prototype,l,{interval:50,getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(null==t)if(this._hasPushState||!this._wantsHashChange||e){t=this.location.pathname;var i=this.root.replace(G,"");t.indexOf(i)||(t=t.substr(i.length))}else t=this.getHash();return t.replace(S,"")},start:function(e){if(z.started)throw Error("Backbone.history has already been started");z.started=!0,this.options=o.extend({},{root:"/"},this.options,e),this.root=this.options.root,this._wantsHashChange=this.options.hashChange!==!1,this._wantsPushState=!!this.options.pushState,this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var i=this.getFragment(),n=document.documentMode,r=E.exec(navigator.userAgent.toLowerCase())&&(!n||7>=n);this.root=("/"+this.root+"/").replace(T,"/"),r&&this._wantsHashChange&&(this.iframe=t.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo("body")[0].contentWindow,this.navigate(i)),this._hasPushState?t.$(window).on("popstate",this.checkUrl):this._wantsHashChange&&"onhashchange"in window&&!r?t.$(window).on("hashchange",this.checkUrl):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),this.fragment=i;var a=this.location,s=a.pathname.replace(/[^\/]$/,"$&/")===this.root;return this._wantsHashChange&&this._wantsPushState&&!this._hasPushState&&!s?(this.fragment=this.getFragment(null,!0),this.location.replace(this.root+this.location.search+"#"+this.fragment),!0):(this._wantsPushState&&this._hasPushState&&s&&a.hash&&(this.fragment=this.getHash().replace(S,""),this.history.replaceState({},document.title,this.root+this.fragment+a.search)),this.options.silent?void 0:this.loadUrl())},stop:function(){t.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl),clearInterval(this._checkUrlInterval),z.started=!1},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(){var t=this.getFragment();return t===this.fragment&&this.iframe&&(t=this.getFragment(this.getHash(this.iframe))),t===this.fragment?!1:(this.iframe&&this.navigate(t),this.loadUrl()||this.loadUrl(this.getHash()),void 0)},loadUrl:function(t){var e=this.fragment=this.getFragment(t),i=o.any(this.handlers,function(t){return t.route.test(e)?(t.callback(e),!0):void 0});return i},navigate:function(t,e){if(!z.started)return!1;if(e&&e!==!0||(e={trigger:e}),t=this.getFragment(t||""),this.fragment!==t){this.fragment=t;var i=this.root+t;if(this._hasPushState)this.history[e.replace?"replaceState":"pushState"]({},document.title,i);else{if(!this._wantsHashChange)return this.location.assign(i);this._updateHash(this.location,t,e.replace),this.iframe&&t!==this.getFragment(this.getHash(this.iframe))&&(e.replace||this.iframe.document.open().close(),this._updateHash(this.iframe.location,t,e.replace))}e.trigger&&this.loadUrl(t)}},_updateHash:function(t,e,i){if(i){var n=t.href.replace(/(javascript:|#).*$/,"");t.replace(n+"#"+e)}else t.hash="#"+e}}),t.history=new z;var L=function(t,e){var i,n=this;i=t&&o.has(t,"constructor")?t.constructor:function(){return n.apply(this,arguments)},o.extend(i,n,e);var r=function(){this.constructor=i};return r.prototype=n.prototype,i.prototype=new r,t&&o.extend(i.prototype,t),i.__super__=n.prototype,i};g.extend=m.extend=M.extend=b.extend=z.extend=L;var B=function(){throw Error('A "url" property or function must be specified')},Z=function(t,e){var i=e.error;e.error=function(n){i&&i(t,n,e),t.trigger("error",t,n,e)}}}.call(this),function(t,e){"function"==typeof define&&define.amd?define([],e):t.Vectorizer=t.V=e()}(this,function(){function t(){var t=++h+"";return"v-"+t}function e(t,e,n){if(!t)return void 0;if("object"==typeof t)return new s(t);if(e=e||{},"svg"===t.toLowerCase())e.xmlns=l.xmlns,e["xmlns:xlink"]=l.xlink,e.version=c;else if("<"===t[0]){var r='<svg xmlns="'+l.xmlns+'" xmlns:xlink="'+l.xlink+'" version="'+c+'">'+t+"</svg>",a=new DOMParser;a.async=!1;var o=a.parseFromString(r,"text/xml").documentElement;if(o.childNodes.length>1){for(var h=[],u=0,p=o.childNodes.length;p>u;u++){var g=o.childNodes[u];h.push(new s(document.importNode(g,!0)))}return h}return new s(document.importNode(o.firstChild,!0))}t=document.createElementNS(l.xmlns,t);for(var d in e)i(t,d,e[d]);"[object Array]"!=Object.prototype.toString.call(n)&&(n=[n]);for(var f,u=0,p=n[0]&&n.length||0;p>u;u++)f=n[u],t.appendChild(f instanceof s?f.node:f);return new s(t)}function i(t,e,i){if(e.indexOf(":")>-1){var n=e.split(":");t.setAttributeNS(l[n[0]],n[1],i)}else"id"===e?t.id=i:t.setAttribute(e,i)}function n(t){var e,i,n;if(t){var r=t.match(/translate\((.*)\)/);r&&(e=r[1].split(","));var a=t.match(/rotate\((.*)\)/);a&&(i=a[1].split(","));var s=t.match(/scale\((.*)\)/);s&&(n=s[1].split(","))}var o=n&&n[0]?parseFloat(n[0]):1;return{translate:{tx:e&&e[0]?parseInt(e[0],10):0,ty:e&&e[1]?parseInt(e[1],10):0},rotate:{angle:i&&i[0]?parseInt(i[0],10):0,cx:i&&i[1]?parseInt(i[1],10):void 0,cy:i&&i[2]?parseInt(i[2],10):void 0},scale:{sx:o,sy:n&&n[1]?parseFloat(n[1]):o}}}function r(t,e){var i=e.x*t.a+e.y*t.c+0,n=e.x*t.b+e.y*t.d+0;return{x:i,y:n}}function a(t){var e=r(t,{x:0,y:1}),i=r(t,{x:1,y:0}),n=180/Math.PI*Math.atan2(e.y,e.x)-90,a=180/Math.PI*Math.atan2(i.y,i.x);return{translateX:t.e,translateY:t.f,scaleX:Math.sqrt(t.a*t.a+t.b*t.b),scaleY:Math.sqrt(t.c*t.c+t.d*t.d),skewX:n,skewY:a,rotation:n}}function s(e){this.node=e,this.node.id||(this.node.id=t())}function o(t){var e=t.rx||t["top-rx"]||0,i=t.rx||t["bottom-rx"]||0,n=t.ry||t["top-ry"]||0,r=t.ry||t["bottom-ry"]||0;return["M",t.x,t.y+n,"v",t.height-n-r,"a",i,r,0,0,0,i,r,"h",t.width-2*i,"a",i,r,0,0,0,i,-r,"v",-(t.height-r-n),"a",e,n,0,0,0,-e,-n,"h",-(t.width-2*e),"a",e,n,0,0,0,-e,n].join(" ")}!(!window.SVGAngle&&!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1"));var l={xmlns:"http://www.w3.org/2000/svg",xlink:"http://www.w3.org/1999/xlink"},c="1.1",h=0;s.prototype={translate:function(t,e){e=e||0;var i=this.attr("transform")||"",r=n(i);if(t===void 0)return r.translate;i=i.replace(/translate\([^\)]*\)/g,"").trim();var a=r.translate.tx+t,s=r.translate.ty+e,j="translate("+a+","+s+")";return this.attr("transform",(j+" "+i).trim()),this},rotate:function(t,e,i){var r=this.attr("transform")||"",a=n(r);if(t===void 0)return a.rotate;r=r.replace(/rotate\([^\)]*\)/g,"").trim();var s=a.rotate.angle+t%360,o=void 0!==e&&void 0!==i?","+e+","+i:"";return this.attr("transform",r+" rotate("+s+o+")"),this},scale:function(t,e){e=e===void 0?t:e;var i=this.attr("transform")||"",r=n(i);return t===void 0?r.scale:(i=i.replace(/scale\([^\)]*\)/g,"").trim(),this.attr("transform",i+" scale("+t+","+e+")"),this)},bbox:function(t,e){if(!this.node.ownerSVGElement)return{x:0,y:0,width:0,height:0};var i;try{i=this.node.getBBox(),i={x:0|i.x,y:0|i.y,width:0|i.width,height:0|i.height}}catch(n){i={x:this.node.clientLeft,y:this.node.clientTop,width:this.node.clientWidth,height:this.node.clientHeight}}if(t)return i;var r=this.node.getTransformToElement(e||this.node.ownerSVGElement),a=[],s=this.node.ownerSVGElement.createSVGPoint();s.x=i.x,s.y=i.y,a.push(s.matrixTransform(r)),s.x=i.x+i.width,s.y=i.y,a.push(s.matrixTransform(r)),s.x=i.x+i.width,s.y=i.y+i.height,a.push(s.matrixTransform(r)),s.x=i.x,s.y=i.y+i.height,a.push(s.matrixTransform(r));for(var o=a[0].x,l=o,c=a[0].y,h=c,u=1,p=a.length;p>u;u++){var g=a[u].x,d=a[u].y;o>g?o=g:g>l&&(l=g),c>d?c=d:d>h&&(h=d)}return{x:o,y:c,width:l-o,height:h-c}},text:function(t){var e,i=t.split("\n"),n=0;if(this.attr("y","0.8em"),this.attr("display",t?null:"none"),1===i.length)return this.node.textContent=t,this;for(this.node.textContent="";i.length>n;n++)e=u("tspan",{dy:0==n?"0em":"1em",x:this.attr("x")||0}),e.node.textContent=i[n],this.append(e);return this},attr:function(t,e){if("string"==typeof t&&e===void 0)return this.node.getAttribute(t);if("object"==typeof t)for(var n in t)t.hasOwnProperty(n)&&i(this.node,n,t[n]);else i(this.node,t,e);return this},remove:function(){this.node.parentNode&&this.node.parentNode.removeChild(this.node)},append:function(t){var e=t;"[object Array]"!==Object.prototype.toString.call(t)&&(e=[t]);for(var i=0,n=e.length;n>i;i++)t=e[i],this.node.appendChild(t instanceof s?t.node:t);return this},prepend:function(t){this.node.insertBefore(t instanceof s?t.node:t,this.node.firstChild)},svg:function(){return this.node instanceof window.SVGSVGElement?this:u(this.node.ownerSVGElement)},defs:function(){var t=this.svg().node.getElementsByTagName("defs");return t&&t.length?u(t[0]):void 0},clone:function(){var e=u(this.node.cloneNode(!0));return e.node.id=t(),e},findOne:function(t){var e=this.node.querySelector(t);return e?u(e):void 0},find:function(t){for(var e=this.node.querySelectorAll(t),i=0,n=e.length;n>i;i++)e[i]=u(e[i]);return e},toLocalPoint:function(t,e){var i=this.svg().node,n=i.createSVGPoint();n.x=t,n.y=e;try{var r=n.matrixTransform(i.getScreenCTM().inverse()),a=this.node.getTransformToElement(i).inverse()}catch(s){return n}return r.matrixTransform(a)},translateCenterToPoint:function(t){var e=this.bbox(),i=g.rect(e).center();this.translate(t.x-i.x,t.y-i.y)},translateAndAutoOrient:function(t,e,i){var n=this.scale();this.attr("transform",""),this.scale(n.sx,n.sy);var r=this.svg().node,s=this.bbox(!1,i),o=r.createSVGTransform();o.setTranslate(-s.x-s.width/2,-s.y-s.height/2);var l=r.createSVGTransform(),c=g.point(t).changeInAngle(t.x-e.x,t.y-e.y,e);l.setRotate(c,0,0);var h=r.createSVGTransform(),u=g.point(t).move(e,s.width/2);h.setTranslate(t.x+(t.x-u.x),t.y+(t.y-u.y));var p=this.node.getTransformToElement(i),d=r.createSVGTransform();d.setMatrix(h.matrix.multiply(l.matrix.multiply(o.matrix.multiply(p))));var f=a(d.matrix);return this.translate(f.translateX,f.translateY),this.rotate(f.rotation),this},animateAlongPath:function(t,e){var i=u("animateMotion",t),n=u("mpath",{"xlink:href":"#"+u(e).node.id});i.append(n),this.append(i);try{i.node.beginElement()}catch(r){if("fake"===document.documentElement.getAttribute("smiling")){var a=i.node;a.animators=[];var s=a.getAttribute("id");s&&(id2anim[s]=a);for(var o=getTargets(a),l=0,c=o.length;c>l;l++){var h=o[l],p=new Animator(a,h,l);animators.push(p),a.animators[l]=p,p.register()}}}},hasClass:function(t){return RegExp("(\\s|^)"+t+"(\\s|$)").test(this.node.getAttribute("class"))},addClass:function(t){return this.hasClass(t)||this.node.setAttribute("class",this.node.getAttribute("class")+" "+t),this},removeClass:function(t){var e=this.node.getAttribute("class").replace(RegExp("(\\s|^)"+t+"(\\s|$)","g"),"$2");return this.hasClass(t)&&this.node.setAttribute("class",e),this},toggleClass:function(t,e){var i=e===void 0?this.hasClass(t):!e;return i?this.removeClass(t):this.addClass(t),this}};var u=e;u.decomposeMatrix=a,u.rectToPath=o;var p=u("svg").node;return u.createSVGMatrix=function(t){var e=p.createSVGMatrix();for(var i in t)e[i]=t[i];return e},u.createSVGTransform=function(){return p.createSVGTransform()},u.createSVGPoint=function(t,e){var i=p.createSVGPoint();return i.x=t,i.y=e,i},u}),function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.g=e()}(this,function(){function t(e,i){if(!(this instanceof t))return new t(e,i);var n;void 0===i&&Object(e)!==e?(n=e.split(-1===e.indexOf("@")?" ":"@"),this.x=parseInt(n[0],10),this.y=parseInt(n[1],10)):Object(e)===e?(this.x=e.x,this.y=e.y):(this.x=e,this.y=i)}function e(i,n){return this instanceof e?(this.start=t(i),this.end=t(n),void 0):new e(i,n)}function i(t,e,n,r){return this instanceof i?(void 0===e&&(e=t.y,n=t.width,r=t.height,t=t.x),this.x=t,this.y=e,this.width=n,this.height=r,void 0):new i(t,e,n,r)}function n(e,i,r){return this instanceof n?(e=t(e),this.x=e.x,this.y=e.y,this.a=i,this.b=r,void 0):new n(e,i,r)}var r=Math,a=r.abs,s=r.cos,o=r.sin,l=r.sqrt,c=r.min,h=r.max;r.atan;var u=r.atan2;r.acos;var p=r.round,g=r.floor,d=r.PI,f=r.random,m=function(t){return 180*t/d%360},I=function(t){return t%360*d/180},y=function(t,e){return e*Math.round(t/e)},v=function(t){return t%360+(0>t?360:0)};t.prototype={toString:function(){return this.x+"@"+this.y},adhereToRect:function(t){return t.containsPoint(this)?this:(this.x=c(h(this.x,t.x),t.x+t.width),this.y=c(h(this.y,t.y),t.y+t.height),this)},theta:function(e){e=t(e);var i=-(e.y-this.y),n=e.x-this.x,r=10,a=0==i.toFixed(r)&&0==n.toFixed(r)?0:u(i,n);return 0>a&&(a=2*d+a),180*a/d},distance:function(t){return e(this,t).length()},manhattanDistance:function(t){return a(t.x-this.x)+a(t.y-this.y)},offset:function(t,e){return this.x+=t||0,this.y+=e||0,this},magnitude:function(){return l(this.x*this.x+this.y*this.y)||.01},update:function(t,e){return this.x=t||0,this.y=e||0,this},round:function(t){return this.x=t?this.x.toFixed(t):p(this.x),this.y=t?this.y.toFixed(t):p(this.y),this},normalize:function(t){var e=(t||1)/this.magnitude();return this.x=e*this.x,this.y=e*this.y,this},difference:function(e){return t(this.x-e.x,this.y-e.y)},bearing:function(t){return e(this,t).bearing()},toPolar:function(e){e=e&&t(e)||t(0,0);var i=this.x,n=this.y;return this.x=l((i-e.x)*(i-e.x)+(n-e.y)*(n-e.y)),this.y=I(e.theta(t(i,n))),this},rotate:function(e,i){i=(i+360)%360,this.toPolar(e),this.y+=I(i);var n=t.fromPolar(this.x,this.y,e);return this.x=n.x,this.y=n.y,this},move:function(e,i){var n=I(t(e).theta(this));return this.offset(s(n)*i,-o(n)*i)},changeInAngle:function(e,i,n){return t(this).offset(-e,-i).theta(n)-this.theta(n)},equals:function(t){return this.x===t.x&&this.y===t.y},snapToGrid:function(t,e){return this.x=y(this.x,t),this.y=y(this.y,e||t),this}},t.fromPolar=function(e,i,n){n=n&&t(n)||t(0,0);var r=a(e*s(i)),l=a(e*o(i)),c=v(m(i));return 90>c?l=-l:180>c?(r=-r,l=-l):270>c&&(r=-r),t(n.x+r,n.y+l)},t.random=function(e,i,n,r){return t(g(f()*(i-e+1)+e),g(f()*(r-n+1)+n))},e.prototype={toString:function(){return""+this.start+" "+(""+this.end)},length:function(){return l(this.squaredLength())},squaredLength:function(){var t=this.start.x,e=this.start.y,i=this.end.x,n=this.end.y;return(t-=i)*t+(e-=n)*e},midpoint:function(){return t((this.start.x+this.end.x)/2,(this.start.y+this.end.y)/2)},intersection:function(e){var i=t(this.end.x-this.start.x,this.end.y-this.start.y),n=t(e.end.x-e.start.x,e.end.y-e.start.y),r=i.x*n.y-i.y*n.x,a=t(e.start.x-this.start.x,e.start.y-this.start.y),s=a.x*n.y-a.y*n.x,o=a.x*i.y-a.y*i.x;if(0===r||0>s*r||0>o*r)return null;if(r>0){if(s>r||o>r)return null}else if(r>s||r>o)return null;return t(this.start.x+s*i.x/r,this.start.y+s*i.y/r)},bearing:function(){var t=I(this.start.y),e=I(this.end.y),i=this.start.x,n=this.end.x,r=I(n-i),a=o(r)*s(e),l=s(t)*o(e)-o(t)*s(e)*s(r),c=m(u(a,l)),h=["NE","E","SE","S","SW","W","NW","N"],p=c-22.5;return 0>p&&(p+=360),p=parseInt(p/45),h[p]}},i.prototype={toString:function(){return""+this.origin()+" "+(""+this.corner())},origin:function(){return t(this.x,this.y)},corner:function(){return t(this.x+this.width,this.y+this.height)},topRight:function(){return t(this.x+this.width,this.y)},bottomLeft:function(){return t(this.x,this.y+this.height)},center:function(){return t(this.x+this.width/2,this.y+this.height/2)},intersect:function(t){var e=this.origin(),i=this.corner(),n=t.origin(),r=t.corner();return r.x<=e.x||r.y<=e.y||n.x>=i.x||n.y>=i.y?!1:!0},sideNearestToPoint:function(e){e=t(e);var i=e.x-this.x,n=this.x+this.width-e.x,r=e.y-this.y,a=this.y+this.height-e.y,s=i,o="left";return s>n&&(s=n,o="right"),s>r&&(s=r,o="top"),s>a&&(s=a,o="bottom"),o},containsPoint:function(e){return e=t(e),e.x>=this.x&&e.x<=this.x+this.width&&e.y>=this.y&&e.y<=this.y+this.height?!0:!1},containsRect:function(t){var e=i(t).normalize(),n=e.width,r=e.height,a=e.x,s=e.y,o=this.width,l=this.height;if(0>(o|l|n|r))return!1;var c=this.x,h=this.y;if(c>a||h>s)return!1;if(o+=c,n+=a,a>=n){if(o>=c||n>o)return!1}else if(o>=c&&n>o)return!1;if(l+=h,r+=s,s>=r){if(l>=h||r>l)return!1}else if(l>=h&&r>l)return!1;return!0},pointNearestToPoint:function(e){if(e=t(e),this.containsPoint(e)){var i=this.sideNearestToPoint(e);switch(i){case"right":return t(this.x+this.width,e.y);case"left":return t(this.x,e.y);case"bottom":return t(e.x,this.y+this.height);case"top":return t(e.x,this.y)}}return e.adhereToRect(this)},intersectionWithLineFromCenterToPoint:function(i,n){i=t(i);var r,a=t(this.x+this.width/2,this.y+this.height/2);n&&i.rotate(a,n);for(var s=[e(this.origin(),this.topRight()),e(this.topRight(),this.corner()),e(this.corner(),this.bottomLeft()),e(this.bottomLeft(),this.origin())],o=e(a,i),l=s.length-1;l>=0;--l){var c=s[l].intersection(o);if(null!==c){r=c;break}}return r&&n&&r.rotate(a,-n),r},moveAndExpand:function(t){return this.x+=t.x,this.y+=t.y,this.width+=t.width,this.height+=t.height,this},round:function(t){return this.x=t?this.x.toFixed(t):p(this.x),this.y=t?this.y.toFixed(t):p(this.y),this.width=t?this.width.toFixed(t):p(this.width),this.height=t?this.height.toFixed(t):p(this.height),this},normalize:function(){var t=this.x,e=this.y,i=this.width,n=this.height;return 0>this.width&&(t=this.x+this.width,i=-this.width),0>this.height&&(e=this.y+this.height,n=-this.height),this.x=t,this.y=e,this.width=i,this.height=n,this}},n.prototype={toString:function(){return""+t(this.x,this.y)+" "+this.a+" "+this.b},bbox:function(){return i(this.x-this.a,this.y-this.b,2*this.a,2*this.b)},intersectionWithLineFromCenterToPoint:function(e,i){e=t(e),i&&e.rotate(t(this.x,this.y),i);var n,r=e.x-this.x,a=e.y-this.y;if(0===r)return n=this.bbox().pointNearestToPoint(e),i?n.rotate(t(this.x,this.y),-i):n;var s=a/r,o=s*s,c=this.a*this.a,h=this.b*this.b,u=l(1/(1/c+o/h));u=0>r?-u:u;var p=s*u;return n=t(this.x+u,this.y+p),i?n.rotate(t(this.x,this.y),-i):n}};var C={curveThroughPoints:function(t){for(var e=this.getCurveControlPoints(t),i=["M",t[0].x,t[0].y],n=0;e[0].length>n;n++)i.push("C",e[0][n].x,e[0][n].y,e[1][n].x,e[1][n].y,t[n+1].x,t[n+1].y);return i},getCurveControlPoints:function(e){var i,n=[],r=[],a=e.length-1;if(1==a)return n[0]=t((2*e[0].x+e[1].x)/3,(2*e[0].y+e[1].y)/3),r[0]=t(2*n[0].x-e[0].x,2*n[0].y-e[0].y),[n,r];var s=[];for(i=1;a-1>i;i++)s[i]=4*e[i].x+2*e[i+1].x;s[0]=e[0].x+2*e[1].x,s[a-1]=(8*e[a-1].x+e[a].x)/2;var o=this.getFirstControlPoints(s);for(i=1;a-1>i;++i)s[i]=4*e[i].y+2*e[i+1].y;s[0]=e[0].y+2*e[1].y,s[a-1]=(8*e[a-1].y+e[a].y)/2;var l=this.getFirstControlPoints(s);for(i=0;a>i;i++)n.push(t(o[i],l[i])),a-1>i?r.push(t(2*e[i+1].x-o[i+1],2*e[i+1].y-l[i+1])):r.push(t((e[a].x+o[a-1])/2,(e[a].y+l[a-1])/2));return[n,r]},getFirstControlPoints:function(t){var e=t.length,i=[],n=[],r=2;i[0]=t[0]/r;for(var a=1;e>a;a++)n[a]=1/r,r=(e-1>a?4:3.5)-n[a],i[a]=(t[a]-i[a-1])/r;for(a=1;e>a;a++)i[e-a-1]-=n[e-a]*i[e-a];return i}},b={linear:function(t,e,i){var n=t[1]-t[0],r=e[1]-e[0];return(i-t[0])/n*r+e[0]||0}};return{toDeg:m,toRad:I,snapToGrid:y,normalizeAngle:v,point:t,line:e,rect:i,ellipse:n,bezier:C,scale:b}}),"object"==typeof exports)var _=require("lodash");var joint={dia:{},ui:{},layout:{},shapes:{},format:{},connectors:{},routers:{},util:{hashCode:function(t){var e=0;if(0==t.length)return e;for(var i=0;t.length>i;i++){var n=t.charCodeAt(i);e=(e<<5)-e+n,e&=e}return e},getByPath:function(t,e,i){i=i||".";for(var n,r=e.split(i);r.length;){if(n=r.shift(),!(n in t))return void 0;t=t[n]}return t},setByPath:function(t,e,i,n){n=n||".";var r=e.split(n),a=t,s=0;if(e.indexOf(n)>-1){for(var o=r.length;o-1>s;s++)a=a[r[s]]||(a[r[s]]={});a[r[o-1]]=i}else t[e]=i;return t},unsetByPath:function(t,e,i){i=i||".";var n=e.lastIndexOf(i);if(n>-1){var r=joint.util.getByPath(t,e.substr(0,n),i);r&&delete r[e.slice(n+1)]}else delete t[e];return t},flattenObject:function(t,e,i){e=e||".";var n={};for(var r in t)if(t.hasOwnProperty(r)){var a="object"==typeof t[r];if(a&&i&&i(t[r])&&(a=!1),a){var s=this.flattenObject(t[r],e,i);for(var o in s)s.hasOwnProperty(o)&&(n[r+e+o]=s[o])}else n[r]=t[r]}return n},uuid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=0|16*Math.random(),i="x"==t?e:8|3&e;return i.toString(16)})},guid:function(t){return this.guid.id=this.guid.id||1,t.id=void 0===t.id?"j_"+this.guid.id++:t.id,t.id},mixin:function(){for(var t=arguments[0],e=1,i=arguments.length;i>e;e++){var n=arguments[e];(Object(n)===n||_.isFunction(n)||null!==n&&void 0!==n)&&_.each(n,function(e,i){return this.mixin.deep&&Object(e)===e?(t[i]||(t[i]=_.isArray(e)?[]:{}),this.mixin(t[i],e),void 0):(t[i]!==e&&(this.mixin.supplement&&t.hasOwnProperty(i)||(t[i]=e)),void 0)},this)}return t},supplement:function(){this.mixin.supplement=!0;var t=this.mixin.apply(this,arguments);return this.mixin.supplement=!1,t},deepMixin:function(){this.mixin.deep=!0;var t=this.mixin.apply(this,arguments);return this.mixin.deep=!1,t},deepSupplement:function(){this.mixin.deep=this.mixin.supplement=!0;var t=this.mixin.apply(this,arguments);return this.mixin.deep=this.mixin.supplement=!1,t},normalizeEvent:function(t){return t.originalEvent&&t.originalEvent.changedTouches&&t.originalEvent.changedTouches.length?t.originalEvent.changedTouches[0]:t},nextFrame:function(){var t,e="undefined"!=typeof window;if(e&&(t=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame),!t){var i=0;t=function(t){var e=(new Date).getTime(),n=Math.max(0,16-(e-i)),r=setTimeout(function(){t(e+n)},n);return i=e+n,r}}return e?_.bind(t,window):t}(),cancelFrame:function(){var t,e="undefined"!=typeof window;return e&&(t=window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelAnimationFrame||window.msCancelRequestAnimationFrame||window.oCancelAnimationFrame||window.oCancelRequestAnimationFrame||window.mozCancelAnimationFrame||window.mozCancelRequestAnimationFrame),t=t||clearTimeout,e?_.bind(t,window):t}(),breakText:function(t,e,i,n){n=n||{};var r=e.width,a=e.height,s=n.svgDocument||V("svg").node,o=V("<text><tspan></tspan></text>").attr(i||{}).node,l=o.firstChild,c=document.createTextNode("");l.appendChild(c),s.appendChild(o),n.svgDocument||document.body.appendChild(s);for(var h,u=t.split(" "),p=[],g=[],d=0,f=0,m=u.length;m>d;d++){var I=u[d];if(c.data=g[f]?g[f]+" "+I:I,r>=l.getComputedTextLength())g[f]=c.data,h&&(p[f++]=!0,h=0);else{if(!g[f]||h){var y=!!h;if(h=I.length-1,y||!h){if(!h){if(!g[f]){g=[];break}u.splice(d,2,I+u[d+1]),m--,p[f++]=!0,d--;continue}u[d]=I.substring(0,h),u[d+1]=I.substring(h)+u[d+1]}else u.splice(d,1,I.substring(0,h),I.substring(h)),m++,f&&!p[f-1]&&f--;d--;continue}f++,d--}if(a!==void 0){var v=v||1.25*o.getBBox().height;if(v*g.length>a){g.splice(Math.floor(a/v));break}}}return n.svgDocument?s.removeChild(o):document.body.removeChild(s),g.join("\n")},timing:{linear:function(t){return t},quad:function(t){return t*t},cubic:function(t){return t*t*t},inout:function(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,i=e*t;return 4*(.5>t?i:3*(t-e)+i-.75)},exponential:function(t){return Math.pow(2,10*(t-1))},bounce:function(t){for(var e=0,i=1;1;e+=i,i/=2)if(t>=(7-4*e)/11){var n=(11-6*e-11*t)/4;return-n*n+i*i}},reverse:function(t){return function(e){return 1-t(1-e)}},reflect:function(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}},clamp:function(t,e,i){return e=e||0,i=i||1,function(n){var r=t(n);return e>r?e:r>i?i:r}},back:function(t){return t||(t=1.70158),function(e){return e*e*((t+1)*e-t)}},elastic:function(t){return t||(t=1.5),function(e){return Math.pow(2,10*(e-1))*Math.cos(20*Math.PI*t/3*e)}}},interpolate:{number:function(t,e){var i=e-t;return function(e){return t+i*e}},object:function(t,e){var i=_.keys(t);return function(n){var r,a,s={};for(r=i.length-1;-1!=r;r--)a=i[r],s[a]=t[a]+(e[a]-t[a])*n;return s}},hexColor:function(t,e){var i=parseInt(t.slice(1),16),n=parseInt(e.slice(1),16),r=255&i,a=(255&n)-r,s=65280&i,o=(65280&n)-s,l=16711680&i,c=(16711680&n)-l;return function(t){var e=255&r+a*t,i=65280&s+o*t,n=16711680&l+c*t;return"#"+(1<<24|e|i|n).toString(16).slice(1)}},unit:function(t,e){var i=/(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/,n=i.exec(t),r=i.exec(e),a=r[1].indexOf("."),s=a>0?r[1].length-a-1:0,t=+n[1],o=+r[1]-t,l=n[2];return function(e){return(t+o*e).toFixed(s)+l}}},filter:{blur:function(t){var e=_.isFinite(t.x)?t.x:2;return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>',{stdDeviation:_.isFinite(t.y)?[e,t.y]:e})},dropShadow:function(t){var e="SVGFEDropShadowElement"in window?'<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>':'<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>';return _.template(e,{dx:t.dx||0,dy:t.dy||0,opacity:_.isFinite(t.opacity)?t.opacity:1,color:t.color||"black",blur:_.isFinite(t.blur)?t.blur:4})},grayscale:function(t){var e=_.isFinite(t.amount)?t.amount:1;return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>',{a:.2126+.7874*(1-e),b:.7152-.7152*(1-e),c:.0722-.0722*(1-e),d:.2126-.2126*(1-e),e:.7152+.2848*(1-e),f:.0722-.0722*(1-e),g:.2126-.2126*(1-e),h:.0722+.9278*(1-e)})},sepia:function(t){var e=_.isFinite(t.amount)?t.amount:1;return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>',{a:.393+.607*(1-e),b:.769-.769*(1-e),c:.189-.189*(1-e),d:.349-.349*(1-e),e:.686+.314*(1-e),f:.168-.168*(1-e),g:.272-.272*(1-e),h:.534-.534*(1-e),i:.131+.869*(1-e)})},saturate:function(t){var e=_.isFinite(t.amount)?t.amount:1;return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>',{amount:1-e})},hueRotate:function(t){return _.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>',{angle:t.angle||0})
+},invert:function(t){var e=_.isFinite(t.amount)?t.amount:1;return _.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>',{amount:e,amount2:1-e})},brightness:function(t){return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>',{amount:_.isFinite(t.amount)?t.amount:1})},contrast:function(t){var e=_.isFinite(t.amount)?t.amount:1;return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>',{amount:e,amount2:.5-e/2})}},format:{number:function(t,e,i){function n(t){for(var e=t.length,n=[],r=0,a=i.grouping[0];e>0&&a>0;)n.push(t.substring(e-=a,e+a)),a=i.grouping[r=(r+1)%i.grouping.length];return n.reverse().join(i.thousands)}i=i||{currency:["$",""],decimal:".",thousands:",",grouping:[3]};var r=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,a=r.exec(t),s=a[1]||" ",o=a[2]||">",l=a[3]||"",c=a[4]||"",h=a[5],u=+a[6],p=a[7],g=a[8],d=a[9],f=1,m="",I="",y=!1;switch(g&&(g=+g.substring(1)),(h||"0"===s&&"="===o)&&(h=s="0",o="=",p&&(u-=Math.floor((u-1)/4))),d){case"n":p=!0,d="g";break;case"%":f=100,I="%",d="f";break;case"p":f=100,I="%",d="r";break;case"b":case"o":case"x":case"X":"#"===c&&(m="0"+d.toLowerCase());case"c":case"d":y=!0,g=0;break;case"s":f=-1,d="r"}"$"===c&&(m=i.currency[0],I=i.currency[1]),"r"!=d||g||(d="g"),null!=g&&("g"==d?g=Math.max(1,Math.min(21,g)):("e"==d||"f"==d)&&(g=Math.max(0,Math.min(20,g))));var v=h&&p;if(y&&e%1)return"";var C=0>e||0===e&&0>1/e?(e=-e,"-"):l,b=I;if(0>f){var A=this.prefix(e,g);e=A.scale(e),b=A.symbol+I}else e*=f;e=this.convert(d,e,g);var w=e.lastIndexOf("."),x=0>w?e:e.substring(0,w),M=0>w?"":i.decimal+e.substring(w+1);!h&&p&&i.grouping&&(x=n(x));var j=m.length+x.length+M.length+(v?0:C.length),N=u>j?Array(j=u-j+1).join(s):"";return v&&(x=n(N+x)),C+=m,e=x+M,("<"===o?C+e+N:">"===o?N+C+e:"^"===o?N.substring(0,j>>=1)+C+e+N.substring(j):C+(v?e:N+e))+b},convert:function(t,e,i){switch(t){case"b":return e.toString(2);case"c":return String.fromCharCode(e);case"o":return e.toString(8);case"x":return e.toString(16);case"X":return e.toString(16).toUpperCase();case"g":return e.toPrecision(i);case"e":return e.toExponential(i);case"f":return e.toFixed(i);case"r":return(e=this.round(e,this.precision(e,i))).toFixed(Math.max(0,Math.min(20,this.precision(e*(1+1e-15),i))));default:return e+""}},round:function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)},precision:function(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)},prefix:function(t,e){var i=_.map(["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"],function(t,e){var i=Math.pow(10,3*abs(8-e));return{scale:e>8?function(t){return t/i}:function(t){return t*i},symbol:t}}),n=0;return t&&(0>t&&(t*=-1),e&&(t=d3.round(t,this.precision(t,e))),n=1+Math.floor(1e-12+Math.log(t)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((0>=n?n+1:n-1)/3)))),i[8+n/3]}}}};if("object"==typeof exports&&(module.exports=joint),"object"==typeof exports)var joint={dia:{Link:require("./joint.dia.link").Link,Element:require("./joint.dia.element").Element},shapes:require("../plugins/shapes")},Backbone=require("backbone"),_=require("lodash"),g=require("./geometry");if(joint.dia.GraphCells=Backbone.Collection.extend({initialize:function(){this.on("change:z",this.sort,this)},model:function(t,e){if("link"===t.type)return new joint.dia.Link(t,e);var i=t.type.split(".")[0],n=t.type.split(".")[1];return joint.shapes[i]&&joint.shapes[i][n]?new joint.shapes[i][n](t,e):new joint.dia.Element(t,e)},comparator:function(t){return t.get("z")||0},getConnectedLinks:function(t,e){e=e||{},_.isUndefined(e.inbound)&&_.isUndefined(e.outbound)&&(e.inbound=e.outbound=!0);var i=[];return this.each(function(n){var r=n.get("source"),a=n.get("target");r&&r.id===t.id&&e.outbound&&i.push(n),a&&a.id===t.id&&e.inbound&&i.push(n)}),i}}),joint.dia.Graph=Backbone.Model.extend({initialize:function(){this.set("cells",new joint.dia.GraphCells),this.get("cells").on("all",this.trigger,this),this.get("cells").on("remove",this.removeCell,this)},toJSON:function(){var t=Backbone.Model.prototype.toJSON.apply(this,arguments);return t.cells=this.get("cells").toJSON(),t},fromJSON:function(t){if(!t.cells)throw Error("Graph JSON must contain cells array.");var e=t,i=t.cells;delete e.cells,this.set(e),this.resetCells(i)},clear:function(){this.trigger("batch:start"),this.get("cells").remove(this.get("cells").models),this.trigger("batch:stop")},_prepareCell:function(t){return t instanceof Backbone.Model&&_.isUndefined(t.get("z"))?t.set("z",this.maxZIndex()+1,{silent:!0}):_.isUndefined(t.z)&&(t.z=this.maxZIndex()+1),t},maxZIndex:function(){var t=this.get("cells").last();return t?t.get("z")||0:0},addCell:function(t,e){return _.isArray(t)?this.addCells(t,e):(this.get("cells").add(this._prepareCell(t),e||{}),this)},addCells:function(t,e){return _.each(t,function(t){this.addCell(t,e)},this),this},resetCells:function(t){return this.get("cells").reset(_.map(t,this._prepareCell,this)),this},removeCell:function(t,e,i){i&&i.disconnectLinks?this.disconnectLinks(t):this.removeLinks(t),this.get("cells").remove(t,{silent:!0})},getCell:function(t){return this.get("cells").get(t)},getElements:function(){return this.get("cells").filter(function(t){return t instanceof joint.dia.Element})},getLinks:function(){return this.get("cells").filter(function(t){return t instanceof joint.dia.Link})},getConnectedLinks:function(t,e){return this.get("cells").getConnectedLinks(t,e)},getNeighbors:function(t){var e=this.getConnectedLinks(t),i=[],n=this.get("cells");return _.each(e,function(e){var r=e.get("source"),a=e.get("target");if(!r.x){var s=n.get(r.id);s!==t&&i.push(s)}if(!a.x){var o=n.get(a.id);o!==t&&i.push(o)}}),i},disconnectLinks:function(t){_.each(this.getConnectedLinks(t),function(e){e.set(e.get("source").id===t.id?"source":"target",g.point(0,0))})},removeLinks:function(t){_.invoke(this.getConnectedLinks(t),"remove")},findModelsFromPoint:function(t){return _.filter(this.getElements(),function(e){return e.getBBox().containsPoint(t)})},findModelsInArea:function(t){return _.filter(this.getElements(),function(e){return e.getBBox().intersect(t)})}}),"object"==typeof exports&&(module.exports.Graph=joint.dia.Graph),"object"==typeof exports)var joint={util:require("./core").util,dia:{Link:require("./joint.dia.link").Link}},Backbone=require("backbone"),_=require("lodash");if(joint.dia.Cell=Backbone.Model.extend({constructor:function(t,e){var i,n=t||{};this.cid=_.uniqueId("c"),this.attributes={},e&&e.collection&&(this.collection=e.collection),e&&e.parse&&(n=this.parse(n,e)||{}),(i=_.result(this,"defaults"))&&(n=_.merge({},i,n)),this.set(n,e),this.changed={},this.initialize.apply(this,arguments)},toJSON:function(){var t=this.constructor.prototype.defaults.attrs||{},e=this.attributes.attrs,i={};_.each(e,function(e,n){var r=t[n];_.each(e,function(t,e){_.isObject(t)&&!_.isArray(t)?_.each(t,function(t,a){r&&r[e]&&_.isEqual(r[e][a],t)||(i[n]=i[n]||{},(i[n][e]||(i[n][e]={}))[a]=t)}):r&&_.isEqual(r[e],t)||(i[n]=i[n]||{},i[n][e]=t)})});var n=_.cloneDeep(_.omit(this.attributes,"attrs"));return n.attrs=i,n},initialize:function(t){t&&t.id||this.set("id",joint.util.uuid(),{silent:!0}),this._transitionIds={},this.processPorts(),this.on("change:attrs",this.processPorts,this)},processPorts:function(){var t=this.ports,e={};_.each(this.get("attrs"),function(t){t&&t.port&&(_.isUndefined(t.port.id)?e[t.port]={id:t.port}:e[t.port.id]=t.port)});var i={};if(_.each(t,function(t,n){e[n]||(i[n]=!0)}),this.collection&&!_.isEmpty(i)){var n=this.collection.getConnectedLinks(this,{inbound:!0});_.each(n,function(t){i[t.get("target").port]&&t.remove()});var r=this.collection.getConnectedLinks(this,{outbound:!0});_.each(r,function(t){i[t.get("source").port]&&t.remove()})}this.ports=e},remove:function(t){var e=this.collection;e&&e.trigger("batch:start");var i=this.get("parent");if(i){var n=this.collection&&this.collection.get(i);n.unembed(this)}_.invoke(this.getEmbeddedCells(),"remove",t),this.trigger("remove",this,this.collection,t),e&&e.trigger("batch:stop")},toFront:function(){this.collection&&this.set("z",(this.collection.last().get("z")||0)+1)},toBack:function(){this.collection&&this.set("z",(this.collection.first().get("z")||0)-1)},embed:function(t){if(this.get("parent")==t.id)throw Error("Recursive embedding not allowed.");this.trigger("batch:start"),t.set("parent",this.id),this.set("embeds",_.uniq((this.get("embeds")||[]).concat([t.id]))),this.trigger("batch:stop")},unembed:function(t){this.trigger("batch:start");var e=t.id;t.unset("parent"),this.set("embeds",_.without(this.get("embeds"),e)),this.trigger("batch:stop")},getEmbeddedCells:function(){return this.collection?_.map(this.get("embeds")||[],function(t){return this.collection.get(t)},this):[]},clone:function(t){t=t||{};var e=Backbone.Model.prototype.clone.apply(this,arguments);if(e.set("id",joint.util.uuid(),{silent:!0}),e.set("embeds",""),!t.deep)return e;var i=this.getEmbeddedCells(),n=[e],r={};return _.each(i,function(t){var i=t.clone({deep:!0});e.embed(i[0]),_.each(i,function(e){if(n.push(e),!(e instanceof joint.dia.Link)){var i=this.collection.getConnectedLinks(t,{inbound:!0});_.each(i,function(t){var i=r[t.id]||t.clone();r[t.id]=i;var n=_.clone(i.get("target"));n.id=e.id,i.set("target",n)});var a=this.collection.getConnectedLinks(t,{outbound:!0});_.each(a,function(t){var i=r[t.id]||t.clone();r[t.id]=i;var n=_.clone(i.get("source"));n.id=e.id,i.set("source",n)})}},this)},this),n=n.concat(_.values(r))},attr:function(t,e,i){var n=this.get("attrs"),r="/";if(_.isString(t)){if(e!==void 0){var a={};return joint.util.setByPath(a,t,e,r),this.set("attrs",_.merge({},n,a),i)}return joint.util.getByPath(n,t,r)}return this.set("attrs",_.merge({},n,t),e,i)},removeAttr:function(t,e){if(_.isArray(t))return _.each(t,function(t){this.removeAttr(t,e)},this),this;var i=joint.util.unsetByPath(_.merge({},this.get("attrs")),t,"/");return this.set("attrs",i,_.extend({dirty:!0},e))},transition:function(t,e,i,n){n=n||"/";var r={duration:100,delay:10,timingFunction:joint.util.timing.linear,valueFunction:joint.util.interpolate.number};i=_.extend(r,i);var a,s=t.split(n),o=s[0],l=s.length>1,c=0,h=_.bind(function(e){var r,s,u;if(c=c||e,e-=c,s=e/i.duration,1>s?this._transitionIds[t]=r=joint.util.nextFrame(h):(s=1,delete this._transitionIds[t]),u=a(i.timingFunction(s)),l){var p=joint.util.setByPath({},t,u,n)[o];u=_.merge({},this.get(o),p)}i.transitionId=r,this.set(o,u,i),r||this.trigger("transition:end",this,t)},this),u=_.bind(function(r){this.stopTransitions(t),a=i.valueFunction(joint.util.getByPath(this.attributes,t,n),e),this._transitionIds[t]=joint.util.nextFrame(r),this.trigger("transition:start",this,t)},this);return _.delay(u,i.delay,h)},getTransitions:function(){return _.keys(this._transitionIds)},stopTransitions:function(t,e){e=e||"/";var i=t&&t.split(e);_(this._transitionIds).keys().filter(i&&function(t){return _.isEqual(i,t.split(e).slice(0,i.length))}).each(function(t){joint.util.cancelFrame(this._transitionIds[t]),delete this._transitionIds[t],this.trigger("transition:end",this,t)},this)}}),joint.dia.CellView=Backbone.View.extend({tagName:"g",attributes:function(){return{"model-id":this.model.id}},initialize:function(){_.bindAll(this,"remove","update"),this.$el.data("view",this),this.listenTo(this.model,"remove",this.remove),this.listenTo(this.model,"change:attrs",this.onChangeAttrs)},onChangeAttrs:function(t,e,i){return i.dirty?this.render():this.update()},_configure:function(t){t.id=t.id||joint.util.guid(this),Backbone.View.prototype._configure.apply(this,arguments)},_ensureElement:function(){var t;if(this.el)t=_.result(this,"el");else{var e=_.extend({id:this.id},_.result(this,"attributes"));this.className&&(e["class"]=_.result(this,"className")),t=V(_.result(this,"tagName"),e).node}this.setElement(t,!1)},findBySelector:function(t){var e="."===t?this.$el:this.$el.find(t);return e},notify:function(t){if(this.paper){var e=Array.prototype.slice.call(arguments,1);this.trigger.apply(this,[t].concat(e)),this.paper.trigger.apply(this.paper,[t,this].concat(e))}},getStrokeBBox:function(t){var e=!!t;t=t||this.el;var i,n=V(t).bbox(!1,this.paper.viewport);return i=e?V(t).attr("stroke-width"):this.model.attr("rect/stroke-width")||this.model.attr("circle/stroke-width")||this.model.attr("ellipse/stroke-width")||this.model.attr("path/stroke-width"),i=parseFloat(i)||0,g.rect(n).moveAndExpand({x:-i/2,y:-i/2,width:i,height:i})},getBBox:function(){return V(this.el).bbox()},highlight:function(t){t=t?this.$(t)[0]||this.el:this.el,V(t).addClass("highlighted")},unhighlight:function(t){t=t?this.$(t)[0]||this.el:this.el,V(t).removeClass("highlighted")},findMagnet:function(t){var e=this.$(t);if(0===e.length||e[0]===this.el){var i=this.model.get("attrs")||{};return i["."]&&i["."].magnet===!1?void 0:this.el}return e.attr("magnet")?e[0]:this.findMagnet(e.parent())},applyFilter:function(t,e){var i=this.findBySelector(t),n=e.name+this.paper.svg.id+joint.util.hashCode(JSON.stringify(e));if(!this.paper.svg.getElementById(n)){var r=joint.util.filter[e.name]&&joint.util.filter[e.name](e.args||{});if(!r)throw Error("Non-existing filter "+e.name);var a=V(r);a.attr("filterUnits","userSpaceOnUse"),e.attrs&&a.attr(e.attrs),a.node.id=n,V(this.paper.svg).defs().append(a)}i.each(function(){V(this).attr("filter","url(#"+n+")")})},applyGradient:function(t,e,i){var n=this.findBySelector(t),r=i.type+this.paper.svg.id+joint.util.hashCode(JSON.stringify(i));if(!this.paper.svg.getElementById(r)){var a=["<"+i.type+">",_.map(i.stops,function(t){return'<stop offset="'+t.offset+'" stop-color="'+t.color+'" stop-opacity="'+(_.isFinite(t.opacity)?t.opacity:1)+'" />'}).join(""),"</"+i.type+">"].join(""),s=V(a);i.attrs&&s.attr(i.attrs),s.node.id=r,V(this.paper.svg).defs().append(s)}n.each(function(){V(this).attr(e,"url(#"+r+")")})},getSelector:function(t,e){if(t===this.el)return e;var i=$(t).index();return e=t.tagName+":nth-child("+(i+1)+")"+" "+(e||""),this.getSelector($(t).parent()[0],e+" ")},pointerdblclick:function(t,e,i){this.notify("cell:pointerdblclick",t,e,i)},pointerclick:function(t,e,i){this.notify("cell:pointerclick",t,e,i)},pointerdown:function(t,e,i){this.model.collection&&(this.model.trigger("batch:start"),this._collection=this.model.collection),this.notify("cell:pointerdown",t,e,i)},pointermove:function(t,e,i){this.notify("cell:pointermove",t,e,i)},pointerup:function(t,e,i){this.notify("cell:pointerup",t,e,i),this._collection&&(this._collection.trigger("batch:stop"),delete this._collection)}}),"object"==typeof exports&&(module.exports.Cell=joint.dia.Cell,module.exports.CellView=joint.dia.CellView),"object"==typeof exports)var joint={util:require("./core").util,dia:{Cell:require("./joint.dia.cell").Cell,CellView:require("./joint.dia.cell").CellView}},Backbone=require("backbone"),_=require("lodash");if(joint.dia.Element=joint.dia.Cell.extend({defaults:{position:{x:0,y:0},size:{width:1,height:1},angle:0},position:function(t,e){this.set("position",{x:t,y:e})},translate:function(t,e,i){if(e=e||0,0===t&&0===e)return this;var n=this.get("position")||{x:0,y:0},r={x:n.x+t||0,y:n.y+e||0};return i&&i.transition?(_.isObject(i.transition)||(i.transition={}),this.transition("position",r,_.extend({},i.transition,{valueFunction:joint.util.interpolate.object}))):(this.set("position",r,i),_.invoke(this.getEmbeddedCells(),"translate",t,e,i)),this},resize:function(t,e){return this.trigger("batch:start"),this.set("size",{width:t,height:e}),this.trigger("batch:stop"),this},rotate:function(t,e){return this.set("angle",e?t:((this.get("angle")||0)+t)%360)},getBBox:function(){var t=this.get("position"),e=this.get("size");return g.rect(t.x,t.y,e.width,e.height)}}),joint.dia.ElementView=joint.dia.CellView.extend({className:function(){return"element "+this.model.get("type").split(".").join(" ")},initialize:function(){_.bindAll(this,"translate","resize","rotate"),joint.dia.CellView.prototype.initialize.apply(this,arguments),this.listenTo(this.model,"change:position",this.translate),this.listenTo(this.model,"change:size",this.resize),this.listenTo(this.model,"change:angle",this.rotate)},update:function(t,e){var i=this.model.get("attrs"),n=V(this.$(".rotatable")[0]);if(n){var r=n.attr("transform");n.attr("transform","")}var a=[];_.each(e||i,function(t,e){var i=this.findBySelector(e);if(0!==i.length){var n=["style","text","html","ref-x","ref-y","ref-dx","ref-dy","ref-width","ref-height","ref","x-alignment","y-alignment","port"];_.isObject(t.filter)&&(n.push("filter"),this.applyFilter(e,t.filter)),_.isObject(t.fill)&&(n.push("fill"),this.applyGradient(e,"fill",t.fill)),_.isObject(t.stroke)&&(n.push("stroke"),this.applyGradient(e,"stroke",t.stroke)),_.isUndefined(t.text)||i.each(function(){V(this).text(t.text+"")});var r=_.omit(t,n);i.each(function(){V(this).attr(r)}),t.port&&i.attr("port",_.isUndefined(t.port.id)?t.port:t.port.id),t.style&&i.css(t.style),_.isUndefined(t.html)||i.each(function(){$(this).html(t.html+"")}),_.isUndefined(t["ref-x"])&&_.isUndefined(t["ref-y"])&&_.isUndefined(t["ref-dx"])&&_.isUndefined(t["ref-dy"])&&_.isUndefined(t["x-alignment"])&&_.isUndefined(t["y-alignment"])&&_.isUndefined(t["ref-width"])&&_.isUndefined(t["ref-height"])||_.each(i,function(t,e,i){var n=$(t);n.selector=i.selector,a.push(n)})}},this);var s=this.el.getBBox();e=e||{},_.each(a,function(t){var n=e[t.selector],r=n?_.merge({},i[t.selector],n):i[t.selector];this.positionRelative(t,s,r)},this),n&&n.attr("transform",r||"")},positionRelative:function(t,e,i){function n(t){return _.isNumber(t)&&!_.isNaN(t)}var r=i.ref,a=parseFloat(i["ref-x"]),s=parseFloat(i["ref-y"]),o=parseFloat(i["ref-dx"]),l=parseFloat(i["ref-dy"]),c=i["y-alignment"],h=i["x-alignment"],u=parseFloat(i["ref-width"]),p=parseFloat(i["ref-height"]),g=_.contains(_.pluck(_.pluck(t.parents("g"),"className"),"baseVal"),"scalable");r&&(e=V(this.findBySelector(r)[0]).bbox(!1,this.el));var d=V(t[0]);d.attr("transform")&&d.attr("transform",d.attr("transform").replace(/translate\([^)]*\)/g,"")||"");var f=0,m=0;if(n(u)&&(u>=0&&1>=u?d.attr("width",u*e.width):d.attr("width",Math.max(u+e.width,0))),n(p)&&(p>=0&&1>=p?d.attr("height",p*e.height):d.attr("height",Math.max(p+e.height,0))),n(o))if(g){var I=V(this.$(".scalable")[0]).scale();f=e.x+e.width+o/I.sx}else f=e.x+e.width+o;if(n(l))if(g){var I=V(this.$(".scalable")[0]).scale();m=e.y+e.height+l/I.sy}else m=e.y+e.height+l;if(n(a))if(a>0&&1>a)f=e.x+e.width*a;else if(g){var I=V(this.$(".scalable")[0]).scale();f=e.x+a/I.sx}else f=e.x+a;if(n(s))if(s>0&&1>s)m=e.y+e.height*s;else if(g){var I=V(this.$(".scalable")[0]).scale();m=e.y+s/I.sy}else m=e.y+s;var y=d.bbox(!1,this.paper.viewport);"middle"===c?m-=y.height/2:n(c)&&(m+=c>-1&&1>c?y.height*c:c),"middle"===h?f-=y.width/2:n(h)&&(f+=h>-1&&1>h?y.width*h:h),d.translate(f,m)},renderMarkup:function(){var t=this.model.markup||this.model.get("markup");if(!t)throw Error("properties.markup is missing while the default render() implementation is used.");var e=V(t);V(this.el).append(e)},render:function(){return this.$el.empty(),this.renderMarkup(),this.update(),this.resize(),this.rotate(),this.translate(),this},scale:function(t,e){V(this.el).scale(t,e)},resize:function(){var t=this.model.get("size")||{width:1,height:1},e=this.model.get("angle")||0,i=V(this.$(".scalable")[0]);if(i){var n=i.bbox(!0);i.attr("transform","scale("+t.width/n.width+","+t.height/n.height+")");var r=V(this.$(".rotatable")[0]),a=r&&r.attr("transform");if(a&&"null"!==a){r.attr("transform",a+" rotate("+-e+","+t.width/2+","+t.height/2+")");var s=i.bbox(!1,this.paper.viewport);this.model.set("position",{x:s.x,y:s.y}),this.rotate()}this.update()}},translate:function(){var t=this.model.get("position")||{x:0,y:0};V(this.el).attr("transform","translate("+t.x+","+t.y+")")},rotate:function(){var t=V(this.$(".rotatable")[0]);if(t){var e=this.model.get("angle")||0,i=this.model.get("size")||{width:1,height:1},n=i.width/2,r=i.height/2;t.attr("transform","rotate("+e+","+n+","+r+")")}},pointerdown:function(t,e,i){if(t.target.getAttribute("magnet")&&this.paper.options.validateMagnet.call(this.paper,this,t.target)){this.model.trigger("batch:start");var n=this.paper.getDefaultLink(this,t.target);n.set({source:{id:this.model.id,selector:this.getSelector(t.target),port:$(t.target).attr("port")},target:{x:e,y:i}}),this.paper.model.addCell(n),this._linkView=this.paper.findViewByModel(n),this._linkView.startArrowheadMove("target")}else this._dx=e,this._dy=i,joint.dia.CellView.prototype.pointerdown.apply(this,arguments)},pointermove:function(t,e,i){if(this._linkView)this._linkView.pointermove(t,e,i);else{var n=this.paper.options.gridSize;if(this.options.interactive!==!1){var r=this.model.get("position");this.model.translate(g.snapToGrid(r.x,n)-r.x+g.snapToGrid(e-this._dx,n),g.snapToGrid(r.y,n)-r.y+g.snapToGrid(i-this._dy,n))}this._dx=g.snapToGrid(e,n),this._dy=g.snapToGrid(i,n),joint.dia.CellView.prototype.pointermove.apply(this,arguments)}},pointerup:function(t,e,i){this._linkView?(this._linkView.pointerup(t,e,i),delete this._linkView,this.model.trigger("batch:stop")):joint.dia.CellView.prototype.pointerup.apply(this,arguments)}}),"object"==typeof exports&&(module.exports.Element=joint.dia.Element,module.exports.ElementView=joint.dia.ElementView),"object"==typeof exports)var joint={dia:{Cell:require("./joint.dia.cell").Cell,CellView:require("./joint.dia.cell").CellView}},Backbone=require("backbone"),_=require("lodash"),g=require("./geometry");if(joint.dia.Link=joint.dia.Cell.extend({markup:['<path class="connection" stroke="black"/>','<path class="marker-source" fill="black" stroke="black" />','<path class="marker-target" fill="black" stroke="black" />','<path class="connection-wrap"/>','<g class="labels"/>','<g class="marker-vertices"/>','<g class="marker-arrowheads"/>','<g class="link-tools"/>'].join(""),labelMarkup:['<g class="label">',"<rect />","<text />","</g>"].join(""),toolMarkup:['<g class="link-tool">','<g class="tool-remove" event="remove">','<circle r="11" />','<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>',"<title>Remove link.</title>","</g>",'<g class="tool-options" event="link:options">','<circle r="11" transform="translate(25)"/>','<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>',"<title>Link options.</title>","</g>","</g>"].join(""),vertexMarkup:['<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">','<circle class="marker-vertex" idx="<%= idx %>" r="10" />','<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>','<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',"<title>Remove vertex.</title>","</path>","</g>"].join(""),arrowheadMarkup:['<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">','<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />',"</g>"].join(""),defaults:{type:"link"},disconnect:function(){return this.set({source:g.point(0,0),target:g.point(0,0)})},label:function(t,e){t=t||0;var i=this.get("labels")||[];if(0===arguments.length||1===arguments.length)return i[t];var n=_.merge({},i[t],e),r=i.slice();return r[t]=n,this.set({labels:r})}}),joint.dia.LinkView=joint.dia.CellView.extend({className:function(){return _.unique(this.model.get("type").split(".").concat("link")).join(" ")},options:{shortLinkLength:100},initialize:function(){joint.dia.CellView.prototype.initialize.apply(this,arguments),"function"!=typeof this.constructor.prototype.watchSource&&(this.constructor.prototype.watchSource=this._createWatcher("source"),this.constructor.prototype.watchTarget=this._createWatcher("target")),this._labelCache={},this._markerCache={},this.startListening()},startListening:function(){this.listenTo(this.model,"change:markup",this.render),this.listenTo(this.model,"change:smooth change:manhattan change:router change:connector",this.update),this.listenTo(this.model,"change:toolMarkup",function(){this.renderTools().updateToolsPosition()}),this.listenTo(this.model,"change:labels change:labelMarkup",function(){this.renderLabels().updateLabelPositions()}),this.listenTo(this.model,"change:vertices change:vertexMarkup",function(){this.renderVertexMarkers().update()}),this.listenTo(this.model,"change:source",function(t,e){this.watchSource(t,e).update()}),this.listenTo(this.model,"change:target",function(t,e){this.watchTarget(t,e).update()})},render:function(){this.$el.empty();var t=V(this.model.get("markup")||this.model.markup);if(_.isArray(t)||(t=[t]),this._V={},_.each(t,function(t){var e=t.attr("class");e&&(this._V[$.camelCase(e)]=t)},this),!this._V.connection)throw Error("link: no connection path in the markup");return this.renderTools(),this.renderVertexMarkers(),this.renderArrowheadMarkers(),V(this.el).append(t),this.renderLabels(),this.watchSource(this.model,this.model.get("source")).watchTarget(this.model,this.model.get("target")).update(),this},renderLabels:function(){if(!this._V.labels)return this;this._labelCache={};var t=$(this._V.labels.node).empty(),e=this.model.get("labels")||[];if(!e.length)return this;var i=_.template(this.model.get("labelMarkup")||this.model.labelMarkup),n=V(i());return _.each(e,function(e,i){var r=n.clone().node;this._labelCache[i]=V(r);var a=$(r).find("text"),s=$(r).find("rect"),o=_.extend({"text-anchor":"middle","font-size":14},joint.util.getByPath(e,"attrs/text","/"));a.attr(_.omit(o,"text")),_.isUndefined(o.text)||V(a[0]).text(o.text+""),t.append(r);var l=V(a[0]).bbox(!0,t[0]);V(a[0]).translate(0,-l.height/2);var c=_.extend({fill:"white",rx:3,ry:3},joint.util.getByPath(e,"attrs/rect","/"));s.attr(_.extend(c,{x:l.x,y:l.y-l.height/2,width:l.width,height:l.height}))},this),this},renderTools:function(){if(!this._V.linkTools)return this;var t=$(this._V.linkTools.node).empty(),e=_.template(this.model.get("toolMarkup")||this.model.toolMarkup),i=V(e());return t.append(i.node),this._toolCache=i,this},renderVertexMarkers:function(){if(!this._V.markerVertices)return this;var t=$(this._V.markerVertices.node).empty(),e=_.template(this.model.get("vertexMarkup")||this.model.vertexMarkup);return _.each(this.model.get("vertices"),function(i,n){t.append(V(e(_.extend({idx:n},i))).node)}),this},renderArrowheadMarkers:function(){if(!this._V.markerArrowheads)return this;var t=$(this._V.markerArrowheads.node);t.empty();var e=_.template(this.model.get("arrowheadMarkup")||this.model.arrowheadMarkup);return this._V.sourceArrowhead=V(e({end:"source"})),this._V.targetArrowhead=V(e({end:"target"})),t.append(this._V.sourceArrowhead.node,this._V.targetArrowhead.node),this},update:function(){_.each(this.model.get("attrs"),function(t,e){_.isObject(t.filter)?(this.findBySelector(e).attr(_.omit(t,"filter")),this.applyFilter(e,t.filter)):this.findBySelector(e).attr(t)},this);var t=this.route=this.findRoute(this.model.get("vertices")||[]);this._findConnectionPoints(t);var e=this.getPathData(t);return this._V.connection.attr("d",e),this._V.connectionWrap&&this._V.connectionWrap.attr("d",e),this._translateAndAutoOrientArrows(this._V.markerSource,this._V.markerTarget),this.updateLabelPositions(),this.updateToolsPosition(),this.updateArrowheadMarkers(),delete this.options.perpendicular,this},_findConnectionPoints:function(t){var e,i,n,r,a=_.first(t);e=this.getConnectionPoint("source",this.model.get("source"),a||this.model.get("target")).round();var s=_.last(t);i=this.getConnectionPoint("target",this.model.get("target"),s||e).round();var o=this._markerCache;this._V.markerSource&&(o.sourceBBox=o.sourceBBox||this._V.markerSource.bbox(!0),n=g.point(e).move(a||i,-1*o.sourceBBox.width*this._V.markerSource.scale().sx).round()),this._V.markerTarget&&(o.targetBBox=o.targetBBox||this._V.markerTarget.bbox(!0),r=g.point(i).move(s||e,-1*o.targetBBox.width*this._V.markerTarget.scale().sx).round()),o.sourcePoint=n||e,o.targetPoint=r||i,this.sourcePoint=e,this.targetPoint=i},updateLabelPositions:function(){if(!this._V.labels)return this;var t=this.model.get("labels")||[];if(!t.length)return this;var e=this._V.connection.node,i=e.getTotalLength();return _.each(t,function(t,n){var r=t.position;r=r>i?i:r,r=0>r?i+r:r,r=r>1?r:i*r;var a=e.getPointAtLength(r);this._labelCache[n].attr("transform","translate("+a.x+", "+a.y+")")},this),this},updateToolsPosition:function(){if(!this._V.linkTools)return this;var t="",e=40;this.getConnectionLength()<this.options.shortLinkLength&&(t="scale(.5)",e/=2);var i=this.getPointAtLength(e);return this._toolCache.attr("transform","translate("+i.x+", "+i.y+") "+t),this},updateArrowheadMarkers:function(){if(!this._V.markerArrowheads)return this;if("none"===$.css(this._V.markerArrowheads.node,"display"))return this;var t=this.getConnectionLength()<this.options.shortLinkLength?.5:1;return this._V.sourceArrowhead.scale(t),this._V.targetArrowhead.scale(t),this._translateAndAutoOrientArrows(this._V.sourceArrowhead,this._V.targetArrowhead),this},_createWatcher:function(t){function e(e,i){i=i||{};var n=e.previous(t)||{},r=this["_"+t+"BBoxUpdate"];return this._isModel(n)&&this.stopListening(this.paper.getModelById(n.id),"change",r),this._isModel(i)&&this.listenTo(this.paper.getModelById(i.id),"change",r),_.bind(r,this)({cacheOnly:!0}),this}return e},_sourceBBoxUpdate:function(t){this.lastEndChange="source",t=t||{};var e=this.model.get("source");if(this._isModel(e)){var i=this._makeSelector(e),n=this.paper.findViewByModel(e.id),r=this.paper.viewport.querySelector(i);this.sourceBBox=n.getStrokeBBox(r)}else this.sourceBBox=g.rect(e.x,e.y,1,1);t.cacheOnly||this.update()},_targetBBoxUpdate:function(t){this.lastEndChange="target",t=t||{};var e=this.model.get("target");if(this._isModel(e)){var i=this._makeSelector(e),n=this.paper.findViewByModel(e.id),r=this.paper.viewport.querySelector(i);this.targetBBox=n.getStrokeBBox(r)}else this.targetBBox=g.rect(e.x,e.y,1,1);t.cacheOnly||this.update()},_translateAndAutoOrientArrows:function(t,e){t&&t.translateAndAutoOrient(this.sourcePoint,_.first(this.route)||this.targetPoint,this.paper.viewport),e&&e.translateAndAutoOrient(this.targetPoint,_.last(this.route)||this.sourcePoint,this.paper.viewport)
+},removeVertex:function(t){var e=_.clone(this.model.get("vertices"));return e&&e.length&&(e.splice(t,1),this.model.set("vertices",e)),this},addVertex:function(t){this.model.set("attrs",this.model.get("attrs")||{}),this.model.get("attrs");for(var e,i=(this.model.get("vertices")||[]).slice(),n=i.slice(),r=this._V.connection.node.cloneNode(!1),a=r.getTotalLength(),s=20,o=i.length+1;o--&&(i.splice(o,0,t),V(r).attr("d",this.getPathData(this.findRoute(i))),e=r.getTotalLength(),e-a>s);)i=n.slice();return this.model.set("vertices",i),Math.max(o,0)},findRoute:function(t){var e=this.model.get("router");if(!e){if(!this.model.get("manhattan"))return t;e={name:"orthogonal"}}var i=joint.routers[e.name];if(!_.isFunction(i))throw"unknown router: "+e.name;var n=i.call(this,t||[],e.args||{},this);return n},getPathData:function(t){var e=this.model.get("connector");if(e||(e=this.model.get("smooth")?{name:"smooth"}:{name:"normal"}),!_.isFunction(joint.connectors[e.name]))throw"unknown connector: "+e.name;var i=joint.connectors[e.name].call(this,this._markerCache.sourcePoint,this._markerCache.targetPoint,t||this.model.get("vertices")||{},e.args||{},this);return i},getConnectionPoint:function(t,e,i){var n;if(this._isPoint(e))n=g.point(e);else{var r,a="source"===t?this.sourceBBox:this.targetBBox;if(this._isPoint(i))r=g.point(i);else{var s="source"===t?this.targetBBox:this.sourceBBox;r=g.rect(s).intersectionWithLineFromCenterToPoint(g.rect(a).center()),r=r||g.rect(s).center()}if(this.paper.options.perpendicularLinks||this.options.perpendicular){var o,l=g.rect(0,r.y,this.paper.options.width,1),c=g.rect(r.x,0,1,this.paper.options.height);if(l.intersect(g.rect(a)))switch(o=g.rect(a).sideNearestToPoint(r)){case"left":n=g.point(a.x,r.y);break;case"right":n=g.point(a.x+a.width,r.y);break;default:n=g.rect(a).center()}else if(c.intersect(g.rect(a)))switch(o=g.rect(a).sideNearestToPoint(r)){case"top":n=g.point(r.x,a.y);break;case"bottom":n=g.point(r.x,a.y+a.height);break;default:n=g.rect(a).center()}else n=g.rect(a).intersectionWithLineFromCenterToPoint(r),n=n||g.rect(a).center()}else n=g.rect(a).intersectionWithLineFromCenterToPoint(r),n=n||g.rect(a).center()}return n},_isModel:function(t){return t&&t.id},_isPoint:function(t){return!this._isModel(t)},_makeSelector:function(t){var e='[model-id="'+t.id+'"]';return t.port?e+=' [port="'+t.port+'"]':t.selector&&(e+=" "+t.selector),e},getConnectionLength:function(){return this._V.connection.node.getTotalLength()},getPointAtLength:function(t){return this._V.connection.node.getPointAtLength(t)},_beforeArrowheadMove:function(){this.model.trigger("batch:start"),this._z=this.model.get("z"),this.model.set("z",Number.MAX_VALUE),this.el.style.pointerEvents="none"},_afterArrowheadMove:function(){this._z&&(this.model.set("z",this._z),delete this._z),this.el.style.pointerEvents="visiblePainted",this.model.trigger("batch:stop")},_createValidateConnectionArgs:function(t){function e(t,e){return i[a]=t,i[a+1]=t.el===e?void 0:e,i}var i=[];i[4]=t,i[5]=this;var n,r=0,a=0;"source"===t?(r=2,n="target"):(a=2,n="source");var s=this.model.get(n);return s.id&&(i[r]=this.paper.findViewByModel(s.id),i[r+1]=s.selector&&i[r].el.querySelector(s.selector)),e},startArrowheadMove:function(t){this._action="arrowhead-move",this._arrowhead=t,this._beforeArrowheadMove(),this._validateConnectionArgs=this._createValidateConnectionArgs(this._arrowhead)},pointerdown:function(t,e,i){if(joint.dia.CellView.prototype.pointerdown.apply(this,arguments),this._dx=e,this._dy=i,this.options.interactive!==!1){var n=t.target.getAttribute("class");switch(n){case"marker-vertex":this._action="vertex-move",this._vertexIdx=t.target.getAttribute("idx");break;case"marker-vertex-remove":case"marker-vertex-remove-area":this.removeVertex(t.target.getAttribute("idx"));break;case"marker-arrowhead":this.startArrowheadMove(t.target.getAttribute("end"));break;default:var r=t.target.parentNode.getAttribute("event");r?"remove"===r?this.model.remove():this.paper.trigger(r,t,this,e,i):(this._vertexIdx=this.addVertex({x:e,y:i}),this._action="vertex-move")}}},pointermove:function(t,e,i){switch(joint.dia.CellView.prototype.pointermove.apply(this,arguments),this._action){case"vertex-move":var n=_.clone(this.model.get("vertices"));n[this._vertexIdx]={x:e,y:i},this.model.set("vertices",n);break;case"arrowhead-move":if(this.paper.options.snapLinks){var r=this.paper.options.snapLinks.radius||50,a=this.paper.findViewsInArea({x:e-r,y:i-r,width:2*r,height:2*r});this._closestView&&this._closestView.unhighlight(this._closestEnd.selector),this._closestView=this._closestEnd=null;var s,o=g.point(e,i),l=Number.MAX_VALUE;_.each(a,function(t){"false"!==t.el.getAttribute("magnet")&&(s=t.model.getBBox().center().distance(o),r>s&&l>s&&this.paper.options.validateConnection.apply(this.paper,this._validateConnectionArgs(t,null))&&(l=s,this._closestView=t,this._closestEnd={id:t.model.id})),t.$("[magnet]").each(_.bind(function(e,i){var n=V(i).bbox(!1,this.paper.viewport);s=o.distance({x:n.x+n.width/2,y:n.y+n.height/2}),r>s&&l>s&&this.paper.options.validateConnection.apply(this.paper,this._validateConnectionArgs(t,i))&&(l=s,this._closestView=t,this._closestEnd={id:t.model.id,selector:t.getSelector(i),port:i.getAttribute("port")})},this))},this),this._closestView&&this._closestView.highlight(this._closestEnd.selector),this.model.set(this._arrowhead,this._closestEnd||{x:e,y:i})}else{var c="mousemove"===t.type?t.target:document.elementFromPoint(t.clientX,t.clientY);this._targetEvent!==c&&(this._magnetUnderPointer&&this._viewUnderPointer.unhighlight(this._magnetUnderPointer),this._viewUnderPointer=this.paper.findView(c),this._viewUnderPointer?(this._magnetUnderPointer=this._viewUnderPointer.findMagnet(c),this._magnetUnderPointer&&this.paper.options.validateConnection.apply(this.paper,this._validateConnectionArgs(this._viewUnderPointer,this._magnetUnderPointer))?this._magnetUnderPointer&&this._viewUnderPointer.highlight(this._magnetUnderPointer):this._magnetUnderPointer=null):this._magnetUnderPointer=null),this._targetEvent=c,this.model.set(this._arrowhead,{x:e,y:i})}}this._dx=e,this._dy=i},pointerup:function(){joint.dia.CellView.prototype.pointerup.apply(this,arguments),"arrowhead-move"===this._action&&(this.paper.options.snapLinks?(this._closestView&&this._closestView.unhighlight(this._closestEnd.selector),this._closestView=this._closestEnd=null):(this._magnetUnderPointer&&(this._viewUnderPointer.unhighlight(this._magnetUnderPointer),this.model.set(this._arrowhead,{id:this._viewUnderPointer.model.id,selector:this._viewUnderPointer.getSelector(this._magnetUnderPointer),port:$(this._magnetUnderPointer).attr("port")})),delete this._viewUnderPointer,delete this._magnetUnderPointer,delete this._staticView,delete this._staticMagnet),this._afterArrowheadMove()),delete this._action}}),"object"==typeof exports&&(module.exports.Link=joint.dia.Link,module.exports.LinkView=joint.dia.LinkView),joint.dia.Paper=Backbone.View.extend({options:{width:800,height:600,gridSize:50,perpendicularLinks:!1,elementView:joint.dia.ElementView,linkView:joint.dia.LinkView,snapLinks:!1,defaultLink:new joint.dia.Link,validateMagnet:function(t,e){return"passive"!==e.getAttribute("magnet")},validateConnection:function(t,e,i,n,r){return("target"===r?i:t)instanceof joint.dia.ElementView}},events:{mousedown:"pointerdown",dblclick:"mousedblclick",click:"mouseclick",touchstart:"pointerdown",mousemove:"pointermove",touchmove:"pointermove"},initialize:function(){_.bindAll(this,"addCell","sortCells","resetCells","pointerup"),this.svg=V("svg").node,this.viewport=V("g").node,V(this.svg).append(V("defs").node),V(this.viewport).attr({"class":"viewport"}),V(this.svg).append(this.viewport),this.$el.append(this.svg),this.setDimensions(),this.listenTo(this.model,"add",this.addCell),this.listenTo(this.model,"reset",this.resetCells),this.listenTo(this.model,"sort",this.sortCells),$(document).on("mouseup touchend",this.pointerup),this._mousemoved=!1},remove:function(){$(document).off("mouseup touchend",this.pointerup),Backbone.View.prototype.remove.call(this)},setDimensions:function(t,e){t&&(this.options.width=t),e&&(this.options.height=e),V(this.svg).attr("width",this.options.width),V(this.svg).attr("height",this.options.height),this.trigger("resize")},fitToContent:function(t,e,i){t=t||1,e=e||1,i=i||0;var n=V(this.viewport).bbox(!0,this.svg),r=Math.ceil((n.width+n.x)/t)*t,a=Math.ceil((n.height+n.y)/e)*e;r+=i,a+=i,(r!=this.options.width||a!=this.options.height)&&this.setDimensions(r||this.options.width,a||this.options.height)},getContentBBox:function(){var t=this.viewport.getBoundingClientRect(),e=this.viewport.getScreenCTM(),i=g.rect(Math.abs(t.left-e.e),Math.abs(t.top-e.f),t.width,t.height);return i},createViewForModel:function(t){var e,i=t.get("type"),n=i.split(".")[0],r=i.split(".")[1];return e=joint.shapes[n]&&joint.shapes[n][r+"View"]?new joint.shapes[n][r+"View"]({model:t,interactive:this.options.interactive}):t instanceof joint.dia.Element?new this.options.elementView({model:t,interactive:this.options.interactive}):new this.options.linkView({model:t,interactive:this.options.interactive})},addCell:function(t){var e=this.createViewForModel(t);V(this.viewport).append(e.el),e.paper=this,e.render(),$(e.el).find("image").on("dragstart",function(){return!1})},resetCells:function(t){$(this.viewport).empty();var e=t.models.slice();e.sort(function(t){return t instanceof joint.dia.Link?1:-1}),_.each(e,this.addCell,this),this.sortCells()},sortCells:function(){var t=$(this.viewport).children("[model-id]"),e=this.model.get("cells");this.sortElements(t,function(t,i){var n=e.get($(t).attr("model-id")),r=e.get($(i).attr("model-id"));return(n.get("z")||0)>(r.get("z")||0)?1:-1})},sortElements:function(t,e){var i=$(t),n=i.map(function(){var t=this,e=t.parentNode,i=e.insertBefore(document.createTextNode(""),t.nextSibling);return function(){if(e===this)throw Error("You can't sort elements if any one is a descendant of another.");e.insertBefore(this,i),e.removeChild(i)}});return Array.prototype.sort.call(i,e).each(function(t){n[t].call(this)})},scale:function(t,e,i,n){return i||(i=0,n=0),V(this.viewport).attr("transform",""),(i||n)&&V(this.viewport).translate(-i*(t-1),-n*(e-1)),V(this.viewport).scale(t,e),this.trigger("scale",i,n),this},rotate:function(t,e,i){if(_.isUndefined(e)){var n=this.viewport.getBBox();e=n.width/2,i=n.height/2}V(this.viewport).rotate(t,e,i)},findView:function(t){var e=this.$(t);return 0===e.length||e[0]===this.el?void 0:e.data("view")?e.data("view"):this.findView(e.parent())},findViewByModel:function(t){var e=_.isString(t)?t:t.id,i=this.$('[model-id="'+e+'"]');return i.length?i.data("view"):void 0},findViewsFromPoint:function(t){t=g.point(t);var e=_.map(this.model.getElements(),this.findViewByModel);return _.filter(e,function(e){return g.rect(V(e.el).bbox(!1,this.viewport)).containsPoint(t)},this)},findViewsInArea:function(t){t=g.rect(t);var e=_.map(this.model.getElements(),this.findViewByModel);return _.filter(e,function(e){return t.intersect(g.rect(V(e.el).bbox(!1,this.viewport)))},this)},getModelById:function(t){return this.model.getCell(t)},snapToGrid:function(t){var e=V(this.viewport).toLocalPoint(t.x,t.y);return{x:g.snapToGrid(e.x,this.options.gridSize),y:g.snapToGrid(e.y,this.options.gridSize)}},getDefaultLink:function(t,e){return _.isFunction(this.options.defaultLink)?this.options.defaultLink.call(this,t,e):this.options.defaultLink.clone()},mousedblclick:function(t){t.preventDefault(),t=joint.util.normalizeEvent(t);var e=this.findView(t.target),i=this.snapToGrid({x:t.clientX,y:t.clientY});e?e.pointerdblclick(t,i.x,i.y):this.trigger("blank:pointerdblclick",t,i.x,i.y)},mouseclick:function(t){if(!this._mousemoved){t.preventDefault(),t=joint.util.normalizeEvent(t);var e=this.findView(t.target),i=this.snapToGrid({x:t.clientX,y:t.clientY});e?e.pointerclick(t,i.x,i.y):this.trigger("blank:pointerclick",t,i.x,i.y)}this._mousemoved=!1},pointerdown:function(t){t.preventDefault(),t=joint.util.normalizeEvent(t);var e=this.findView(t.target),i=this.snapToGrid({x:t.clientX,y:t.clientY});e?(this.sourceView=e,e.pointerdown(t,i.x,i.y)):this.trigger("blank:pointerdown",t,i.x,i.y)},pointermove:function(t){if(t.preventDefault(),t=joint.util.normalizeEvent(t),this.sourceView){this._mousemoved=!0;var e=this.snapToGrid({x:t.clientX,y:t.clientY});this.sourceView.pointermove(t,e.x,e.y)}},pointerup:function(t){t=joint.util.normalizeEvent(t);var e=this.snapToGrid({x:t.clientX,y:t.clientY});this.sourceView?(this.sourceView.pointerup(t,e.x,e.y),this.sourceView=null):this.trigger("blank:pointerup",t,e.x,e.y)}}),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{},dia:{Element:require("../src/joint.dia.element").Element,ElementView:require("../src/joint.dia.element").ElementView}},_=require("lodash");if(joint.shapes.basic={},joint.shapes.basic.Generic=joint.dia.Element.extend({defaults:joint.util.deepSupplement({type:"basic.Generic",attrs:{".":{fill:"#FFFFFF",stroke:"none"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.basic.Rect=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><rect/></g><text/></g>',defaults:joint.util.deepSupplement({type:"basic.Rect",attrs:{rect:{fill:"#FFFFFF",stroke:"black",width:100,height:60},text:{"font-size":14,text:"","ref-x":.5,"ref-y":.5,ref:"rect","y-alignment":"middle","x-alignment":"middle",fill:"black","font-family":"Arial, helvetica, sans-serif"}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.basic.Text=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><text/></g></g>',defaults:joint.util.deepSupplement({type:"basic.Text",attrs:{text:{"font-size":18,fill:"black"}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.basic.Circle=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><circle/></g><text/></g>',defaults:joint.util.deepSupplement({type:"basic.Circle",size:{width:60,height:60},attrs:{circle:{fill:"#FFFFFF",stroke:"black",r:30,transform:"translate(30, 30)"},text:{"font-size":14,text:"","text-anchor":"middle","ref-x":.5,"ref-y":.5,ref:"circle","y-alignment":"middle",fill:"black","font-family":"Arial, helvetica, sans-serif"}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.basic.Image=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><image/></g><text/></g>',defaults:joint.util.deepSupplement({type:"basic.Image",attrs:{text:{"font-size":14,text:"","text-anchor":"middle","ref-x":.5,"ref-dy":20,ref:"image","y-alignment":"middle",fill:"black","font-family":"Arial, helvetica, sans-serif"}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.basic.Path=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><path/></g><text/></g>',defaults:joint.util.deepSupplement({type:"basic.Path",size:{width:60,height:60},attrs:{path:{fill:"#FFFFFF",stroke:"black"},text:{"font-size":14,text:"","text-anchor":"middle","ref-x":.5,"ref-dy":20,ref:"path","y-alignment":"middle",fill:"black","font-family":"Arial, helvetica, sans-serif"}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.basic.PortsModelInterface={initialize:function(){this.updatePortsAttrs(),this.on("change:inPorts change:outPorts",this.updatePortsAttrs,this),this.constructor.__super__.constructor.__super__.initialize.apply(this,arguments)},updatePortsAttrs:function(){var t=this.get("attrs");_.each(this._portSelectors,function(e){t[e]&&delete t[e]}),this._portSelectors=[];var e={};_.each(this.get("inPorts"),function(t,i,n){var r=this.getPortAttrs(t,i,n.length,".inPorts","in");this._portSelectors=this._portSelectors.concat(_.keys(r)),_.extend(e,r)},this),_.each(this.get("outPorts"),function(t,i,n){var r=this.getPortAttrs(t,i,n.length,".outPorts","out");this._portSelectors=this._portSelectors.concat(_.keys(r)),_.extend(e,r)},this),this.attr(e,{silent:!0}),this.processPorts(),this.trigger("process:ports")},getPortSelector:function(t){var e=".inPorts",i=this.get("inPorts").indexOf(t);if(0>i&&(e=".outPorts",i=this.get("outPorts").indexOf(t),0>i))throw Error("getPortSelector(): Port doesn't exist.");return e+">g:nth-child("+(i+1)+")>circle"}},joint.shapes.basic.PortsViewInterface={initialize:function(){this.listenTo(this.model,"process:ports",this.update),joint.dia.ElementView.prototype.initialize.apply(this,arguments)},update:function(){this.renderPorts(),joint.dia.ElementView.prototype.update.apply(this,arguments)},renderPorts:function(){var t=this.$(".inPorts").empty(),e=this.$(".outPorts").empty(),i=_.template(this.model.portMarkup);_.each(_.filter(this.model.ports,function(t){return"in"===t.type}),function(e,n){t.append(V(i({id:n,port:e})).node)}),_.each(_.filter(this.model.ports,function(t){return"out"===t.type}),function(t,n){e.append(V(i({id:n,port:t})).node)})}},joint.shapes.basic.TextBlock=joint.shapes.basic.Generic.extend({markup:['<g class="rotatable"><g class="scalable"><rect/></g><switch>','<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">','<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',"</foreignObject>",'<text class="content"/>',"</switch></g>"].join(""),defaults:joint.util.deepSupplement({type:"basic.TextBlock",attrs:{rect:{fill:"#ffffff",stroke:"#000000",width:80,height:100},text:{fill:"#000000","font-size":14,"font-family":"Arial, helvetica, sans-serif"},".content":{text:"",ref:"rect","ref-x":.5,"ref-y":.5,"y-alignment":"middle","x-alignment":"middle"}},content:""},joint.shapes.basic.Generic.prototype.defaults),initialize:function(){"undefined"!=typeof SVGForeignObjectElement&&(this.setForeignObjectSize(this,this.get("size")),this.setDivContent(this,this.get("content")),this.listenTo(this,"change:size",this.setForeignObjectSize),this.listenTo(this,"change:content",this.setDivContent)),joint.shapes.basic.Generic.prototype.initialize.apply(this,arguments)},setForeignObjectSize:function(t,e){t.attr({".fobj":_.clone(e),div:{style:_.clone(e)}})},setDivContent:function(t,e){t.attr({div:{html:e}})}}),joint.shapes.basic.TextBlockView=joint.dia.ElementView.extend({initialize:function(){joint.dia.ElementView.prototype.initialize.apply(this,arguments),"undefined"==typeof SVGForeignObjectElement&&(this.noSVGForeignObjectElement=!0,this.listenTo(this.model,"change:content",function(t){this.updateContent(t)}))},update:function(t,e){if(this.noSVGForeignObjectElement){var i=this.model,n=_.omit(e||i.get("attrs"),".content");joint.dia.ElementView.prototype.update.call(this,i,n),(!e||_.has(e,".content"))&&this.updateContent(i,e)}else joint.dia.ElementView.prototype.update.call(this,i,e)},updateContent:function(t,e){var i=_.merge({},(e||t.get("attrs"))[".content"]);delete i.text;var n=joint.util.breakText(t.get("content"),t.get("size"),i,{svgDocument:this.paper.svg}),r=joint.util.setByPath({},".content",i,"/");r[".content"].text=n,joint.dia.ElementView.prototype.update.call(this,t,r)}}),"object"==typeof exports&&(module.exports=joint.shapes.basic),joint.routers.orthogonal=function(){function t(t,e){return t.y<e.y&&t.x===e.x?"down":t.y>e.y&&t.x===e.x?"up":t.x<e.x&&t.y===e.y?"right":"left"}function e(t,e,i){var n;if(n=t.x<e.x?t.y>e.y?["up","right"]:t.y<e.y?["down","right"]:["right"]:t.x>e.x?t.y>e.y?["up","left"]:t.y<e.y?["down","left"]:["left"]:t.y>e.y?["up"]:["down"],_.contains(n,i))return i;var r=_.first(n);switch(i){case"down":if("up"===r)return _.last(n);break;case"up":if("down"===r)return _.last(n);break;case"left":if("right"===r)return _.last(n);break;case"right":if("left"===r)return _.last(n)}return r}function i(t,i,n){var r=e(t,i,n);return"down"===r||"up"===r?{x:t.x,y:i.y,d:r}:{x:i.x,y:t.y,d:r}}function n(e){e=(e||[]).slice();var n=[],s=r.center(),o=a.center();e.length||(Math.abs(s.x-o.x)<r.width/2||Math.abs(s.y-o.y)<r.height/2)&&(e=[{x:Math.min(s.x,o.x)+Math.abs(s.x-o.x)/2,y:Math.min(s.y,o.y)+Math.abs(s.y-o.y)/2}]),e.unshift(s),e.push(o);for(var l,c,h,u,p=0;e.length-1>p;p++){h=e[p],u=e[p+1],c=_.last(n),p>0&&(l=h,l.d=c?t(c,h):"top",n.push(l),c=l);var d=c&&c.d;l=i(h,u,d),g.point(l).equals(g.point(h))||g.point(l).equals(g.point(u))||n.push(l)}return n}var r,a;return function(t){return r=this.sourceBBox,a=this.targetBBox,n(t)}}(),joint.routers.manhattan=function(){"use strict";function t(t,e){for(var i,n=[],r={x:0,y:0},a=e;i=t[a];){var s=i.difference(a);s.equals(r)||(n.unshift(a),r=s),a=i}return n.unshift(a),n}function e(t,e,i){var n=i.step,r=t.center(),a=_.chain(i.directionMap).pick(e).map(function(e){var i=e.x*t.width/2,a=e.y*t.height/2,s=g.point(r).offset(i,a).snapToGrid(n);return t.containsPoint(s)&&s.offset(e.x*n,e.y*n),s}).value();return a}function i(t,e,i){var n=360/i,r=Math.floor(t.theta(e)/n);return i-r}function n(n,r,a,s){var o=s.reversed?s.endDirections:s.startDirections,l=s.reversed?s.startDirections:s.endDirections,c=n instanceof g.rect?e(n,o,s):[n],h=r instanceof g.rect?e(r,l,s):[r],u=c.length>1?n.center():c[0],p=h.length>1?r.center():h[0],d=_.filter(h,function(t){var e=""+g.point(t).snapToGrid(s.mapGridSize),i=_.every(a[e],function(e){return!e.containsPoint(t)});return i});if(d.length)for(var f=s.step,m=s.penalties,I=_.chain(d).invoke("snapToGrid",f).min(function(t){return s.estimateCost(u,t)}).value(),y={},v={},C={},b=s.directions,A=b.length,w=A/2,x=s.previousDirIndexes||{},M={},j={},N=_.chain(c).invoke("snapToGrid",f).each(function(t){var e=""+t;v[e]=0,C[e]=s.estimateCost(t,I),x[e]=x[e]||i(u,t,A),j[e]=!0}).map(function(t){return""+t}).sortBy(function(t){return C[t]}).value(),k=s.maximumLoops,D=s.maxAllowedDirectionChange;N.length&&k--;){var z=N[0],S=g.point(z);if(I.equals(S))return s.previousDirIndexes=_.pick(x,z),t(y,S);N.splice(0,1),j[P]=null,M[P]=!0;for(var T=x[z],E=v[z],G=0;A>G;G++){var L=Math.abs(G-T);if(L>w&&(L=A-L),!(L>D)){var B=b[G],Z=g.point(S).offset(B.offsetX,B.offsetY),P=""+Z;if(!M[P]){var O=""+g.point(Z).snapToGrid(s.mapGridSize),Y=_.every(a[O],function(t){return!t.containsPoint(Z)});if(Y){var W=_.has(j,P),V=E+B.cost;if((!W||v[P]>V)&&(y[P]=S,x[P]=G,v[P]=V,C[P]=V+s.estimateCost(Z,I)+m[L],!W)){var R=_.sortedIndex(N,P,function(t){return C[t]});N.splice(R,0,P),j[P]=!0}}}}}}return s.fallbackRoute(u,p,s)}function r(t,e){e.directions=_.result(e,"directions"),e.penalties=_.result(e,"penalties"),e.paddingBox=_.result(e,"paddingBox"),this.options.perpendicular=!!e.perpendicular;var i=e.reversed="source"===this.lastEndChange,r=i?g.rect(this.targetBBox):g.rect(this.sourceBBox),a=i?g.rect(this.sourceBBox):g.rect(this.targetBBox);r.moveAndExpand(e.paddingBox),a.moveAndExpand(e.paddingBox);for(var s=this.model,o=this.paper.model,l=_.chain(e.excludeEnds).map(s.get,s).pluck("id").map(o.getCell,o).value(),c=e.mapGridSize,h=_.chain(o.getElements()).difference(l).reject(function(t){return _.contains(e.excludeTypes,t.get("type"))}).invoke("getBBox").invoke("moveAndExpand",e.paddingBox).foldl(function(t,e){for(var i=e.origin().snapToGrid(c),n=e.corner().snapToGrid(c),r=i.x;n.x>=r;r+=c)for(var a=i.y;n.y>=a;a+=c){var s=r+"@"+a;t[s]=t[s]||[],t[s].push(e)}return t},{}).value(),u=[],p=_.map(t,g.point),d=r.center(),f=0,m=p.length;m>=f;f++){var I=null,y=v||r,v=p[f];if(!v){v=a;var C=!this.model.get("source").id||!this.model.get("target").id;if(C&&_.isFunction(e.draggingRoute)){var b=y instanceof g.rect?y.center():y;I=e.draggingRoute(b,v.origin(),e)}}I=I||n(y,v,h,e);var A=_.first(I);A&&A.equals(d)&&I.shift(),d=_.last(I)||d,u=u.concat(I)}return i?u.reverse():u}var a={step:10,perpendicular:!0,mapGridSize:100,excludeEnds:[],excludeTypes:["basic.Text"],maximumLoops:500,startDirections:["left","right","top","bottom"],endDirections:["left","right","top","bottom"],directionMap:{right:{x:1,y:0},bottom:{x:0,y:1},left:{x:-1,y:0},top:{x:0,y:-1}},maxAllowedDirectionChange:1,paddingBox:function(){var t=this.step;return{x:-t,y:-t,width:2*t,height:2*t}},directions:function(){var t=this.step;return[{offsetX:t,offsetY:0,cost:t},{offsetX:0,offsetY:t,cost:t},{offsetX:-t,offsetY:0,cost:t},{offsetX:0,offsetY:-t,cost:t}]},penalties:function(){return[0,this.step/2,this.step]},estimateCost:function(t,e){return t.manhattanDistance(e)},fallbackRoute:function(t,e,i){var n=i.prevDirIndexes||{},r=(n[t]||0)%2?g.point(t.x,e.y):g.point(e.x,t.y);return[r,e]},draggingRoute:null};return function(t,e,i){return r.call(i,t,_.extend({},a,e))}}(),joint.routers.metro=function(){if(!_.isFunction(joint.routers.manhattan))throw"Metro requires the manhattan router.";var t={diagonalCost:null,directions:function(){var t=this.step,e=this.diagonalCost||Math.ceil(Math.sqrt(t*t<<1));return[{offsetX:t,offsetY:0,cost:t},{offsetX:t,offsetY:t,cost:e},{offsetX:0,offsetY:t,cost:t},{offsetX:-t,offsetY:t,cost:e},{offsetX:-t,offsetY:0,cost:t},{offsetX:-t,offsetY:-t,cost:e},{offsetX:0,offsetY:-t,cost:t},{offsetX:t,offsetY:-t,cost:e}]},fallbackRoute:function(t,e){var i=t.theta(e),n={x:e.x,y:t.y},r={x:t.x,y:e.y};if(i%180>90){var a=n;n=r,r=a}var s=45>i%90?n:r,o=g.line(t,s),l=90*Math.ceil(i/90),c=g.point.fromPolar(o.squaredLength(),g.toRad(l+135),s),h=g.line(e,c),u=o.intersection(h);return u?[u.round(),e]:[e]}};return function(e,i,n){return joint.routers.manhattan(e,_.extend({},t,i),n)}}(),joint.connectors.normal=function(t,e,i){var n=["M",t.x,t.y];return _.each(i,function(t){n.push(t.x,t.y)}),n.push(e.x,e.y),n.join(" ")},joint.connectors.rounded=function(t,e,i,n){var r,a,s,o,l,c,h=n.radius||10,u=["M",t.x,t.y];return _.each(i,function(n,p){l=i[p-1]||t,c=i[p+1]||e,s=o||g.point(n).distance(l)/2,o=g.point(n).distance(c)/2,r=g.point(n).move(l,-Math.min(h,s)).round(),a=g.point(n).move(c,-Math.min(h,o)).round(),u.push(r.x,r.y,"S",n.x,n.y,a.x,a.y,"L")}),u.push(e.x,e.y),u.join(" ")},joint.connectors.smooth=function(t,e,i){var n;if(i.length)n=g.bezier.curveThroughPoints([t].concat(i).concat([e]));else{var r=t.x<e.x?e.x-(e.x-t.x)/2:t.x-(t.x-e.x)/2;n=["M",t.x,t.y,"C",r,t.y,r,e.y,e.x,e.y]}return n.join(" ")},"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{},dia:{Element:require("../src/joint.dia.element").Element,Link:require("../src/joint.dia.link").Link}};if(joint.shapes.erd={},joint.shapes.erd.Entity=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',defaults:joint.util.deepSupplement({type:"erd.Entity",size:{width:150,height:60},attrs:{".outer":{fill:"#2ECC71",stroke:"#27AE60","stroke-width":2,points:"100,0 100,60 0,60 0,0"},".inner":{fill:"#2ECC71",stroke:"#27AE60","stroke-width":2,points:"95,5 95,55 5,55 5,5",display:"none"},text:{text:"Entity","font-family":"Arial","font-size":14,ref:".outer","ref-x":.5,"ref-y":.5,"x-alignment":"middle","y-alignment":"middle"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.erd.WeakEntity=joint.shapes.erd.Entity.extend({defaults:joint.util.deepSupplement({type:"erd.WeakEntity",attrs:{".inner":{display:"auto"},text:{text:"Weak Entity"}}},joint.shapes.erd.Entity.prototype.defaults)}),joint.shapes.erd.Relationship=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',defaults:joint.util.deepSupplement({type:"erd.Relationship",size:{width:80,height:80},attrs:{".outer":{fill:"#3498DB",stroke:"#2980B9","stroke-width":2,points:"40,0 80,40 40,80 0,40"},".inner":{fill:"#3498DB",stroke:"#2980B9","stroke-width":2,points:"40,5 75,40 40,75 5,40",display:"none"},text:{text:"Relationship","font-family":"Arial","font-size":12,ref:".","ref-x":.5,"ref-y":.5,"x-alignment":"middle","y-alignment":"middle"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.erd.IdentifyingRelationship=joint.shapes.erd.Relationship.extend({defaults:joint.util.deepSupplement({type:"erd.IdentifyingRelationship",attrs:{".inner":{display:"auto"},text:{text:"Identifying"}}},joint.shapes.erd.Relationship.prototype.defaults)}),joint.shapes.erd.Attribute=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><ellipse class="outer"/><ellipse class="inner"/></g><text/></g>',defaults:joint.util.deepSupplement({type:"erd.Attribute",size:{width:100,height:50},attrs:{ellipse:{transform:"translate(50, 25)"},".outer":{stroke:"#D35400","stroke-width":2,cx:0,cy:0,rx:50,ry:25,fill:"#E67E22"},".inner":{stroke:"#D35400","stroke-width":2,cx:0,cy:0,rx:45,ry:20,fill:"transparent",display:"none"},text:{"font-family":"Arial","font-size":14,ref:".","ref-x":.5,"ref-y":.5,"x-alignment":"middle","y-alignment":"middle"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.erd.Multivalued=joint.shapes.erd.Attribute.extend({defaults:joint.util.deepSupplement({type:"erd.Multivalued",attrs:{".inner":{display:"block"},text:{text:"multivalued"}}},joint.shapes.erd.Attribute.prototype.defaults)}),joint.shapes.erd.Derived=joint.shapes.erd.Attribute.extend({defaults:joint.util.deepSupplement({type:"erd.Derived",attrs:{".outer":{"stroke-dasharray":"3,5"},text:{text:"derived"}}},joint.shapes.erd.Attribute.prototype.defaults)}),joint.shapes.erd.Key=joint.shapes.erd.Attribute.extend({defaults:joint.util.deepSupplement({type:"erd.Key",attrs:{ellipse:{"stroke-width":4},text:{text:"key","font-weight":"bold","text-decoration":"underline"}}},joint.shapes.erd.Attribute.prototype.defaults)}),joint.shapes.erd.Normal=joint.shapes.erd.Attribute.extend({defaults:joint.util.deepSupplement({type:"erd.Normal",attrs:{text:{text:"Normal"}}},joint.shapes.erd.Attribute.prototype.defaults)}),joint.shapes.erd.ISA=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>',defaults:joint.util.deepSupplement({type:"erd.ISA",size:{width:100,height:50},attrs:{polygon:{points:"0,0 50,50 100,0",fill:"#F1C40F",stroke:"#F39C12","stroke-width":2},text:{text:"ISA",ref:".","ref-x":.5,"ref-y":.3,"x-alignment":"middle","y-alignment":"middle"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.erd.Line=joint.dia.Link.extend({defaults:{type:"erd.Line"},cardinality:function(t){this.set("labels",[{position:-20,attrs:{text:{dy:-8,text:t}}}])}}),"object"==typeof exports&&(module.exports=joint.shapes.erd),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{basic:require("./joint.shapes.basic")},dia:{Element:require("../src/joint.dia.element").Element,Link:require("../src/joint.dia.link").Link}};if(joint.shapes.fsa={},joint.shapes.fsa.State=joint.shapes.basic.Circle.extend({defaults:joint.util.deepSupplement({type:"fsa.State",attrs:{circle:{"stroke-width":3},text:{"font-weight":"bold"}}},joint.shapes.basic.Circle.prototype.defaults)}),joint.shapes.fsa.StartState=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><circle/></g></g>',defaults:joint.util.deepSupplement({type:"fsa.StartState",size:{width:20,height:20},attrs:{circle:{transform:"translate(10, 10)",r:10,fill:"black"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.fsa.EndState=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',defaults:joint.util.deepSupplement({type:"fsa.EndState",size:{width:20,height:20},attrs:{".outer":{transform:"translate(10, 10)",r:10,fill:"#FFFFFF",stroke:"black"},".inner":{transform:"translate(10, 10)",r:6,fill:"#000000"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.fsa.Arrow=joint.dia.Link.extend({defaults:joint.util.deepSupplement({type:"fsa.Arrow",attrs:{".marker-target":{d:"M 10 0 L 0 5 L 10 10 z"}},smooth:!0},joint.dia.Link.prototype.defaults)}),"object"==typeof exports&&(module.exports=joint.shapes.fsa),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{},dia:{Element:require("../src/joint.dia.element").Element,Link:require("../src/joint.dia.link").Link}};if(joint.shapes.org={},joint.shapes.org.Member=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><rect class="card"/><image/></g><text class="rank"/><text class="name"/></g>',defaults:joint.util.deepSupplement({type:"org.Member",size:{width:180,height:70},attrs:{rect:{width:170,height:60},".card":{fill:"#FFFFFF",stroke:"#000000","stroke-width":2,"pointer-events":"visiblePainted",rx:10,ry:10},image:{width:48,height:48,ref:".card","ref-x":10,"ref-y":5},".rank":{"text-decoration":"underline",ref:".card","ref-x":.9,"ref-y":.2,"font-family":"Courier New","font-size":14,"text-anchor":"end"},".name":{"font-weight":"bold",ref:".card","ref-x":.9,"ref-y":.6,"font-family":"Courier New","font-size":14,"text-anchor":"end"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.org.Arrow=joint.dia.Link.extend({defaults:{type:"org.Arrow",source:{selector:".card"},target:{selector:".card"},attrs:{".connection":{stroke:"#585858","stroke-width":3}},z:-1}}),"object"==typeof exports&&(module.exports=joint.shapes.org),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{basic:require("./joint.shapes.basic")},dia:{}};
+if(joint.shapes.chess={},joint.shapes.chess.KingWhite=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;"><path      d="M 22.5,11.63 L 22.5,6"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path      d="M 20,8 L 25,8"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path      d="M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25"      style="fill:#ffffff; stroke:#000000; stroke-linecap:butt; stroke-linejoin:miter;" />    <path      d="M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z "      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 11.5,30 C 17,27 27,27 32.5,30"      style="fill:none; stroke:#000000;" />    <path      d="M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5"      style="fill:none; stroke:#000000;" />    <path      d="M 11.5,37 C 17,34 27,34 32.5,37"      style="fill:none; stroke:#000000;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.KingWhite",size:{width:42,height:38}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.KingBlack=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path       d="M 22.5,11.63 L 22.5,6"       style="fill:none; stroke:#000000; stroke-linejoin:miter;"       id="path6570" />    <path       d="M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25"       style="fill:#000000;fill-opacity:1; stroke-linecap:butt; stroke-linejoin:miter;" />    <path       d="M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z "       style="fill:#000000; stroke:#000000;" />    <path       d="M 20,8 L 25,8"       style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path       d="M 32,29.5 C 32,29.5 40.5,25.5 38.03,19.85 C 34.15,14 25,18 22.5,24.5 L 22.51,26.6 L 22.5,24.5 C 20,18 9.906,14 6.997,19.85 C 4.5,25.5 11.85,28.85 11.85,28.85"       style="fill:none; stroke:#ffffff;" />    <path       d="M 11.5,30 C 17,27 27,27 32.5,30 M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5 M 11.5,37 C 17,34 27,34 32.5,37"       style="fill:none; stroke:#ffffff;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.KingBlack",size:{width:42,height:38}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.QueenWhite=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(-1,-1)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(15.5,-5.5)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(32,-1)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(7,-4.5)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(24,-4)" />    <path      d="M 9,26 C 17.5,24.5 30,24.5 36,26 L 38,14 L 31,25 L 31,11 L 25.5,24.5 L 22.5,9.5 L 19.5,24.5 L 14,10.5 L 14,25 L 7,14 L 9,26 z "      style="stroke-linecap:butt;" />    <path      d="M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z "      style="stroke-linecap:butt;" />    <path      d="M 11.5,30 C 15,29 30,29 33.5,30"      style="fill:none;" />    <path      d="M 12,33.5 C 18,32.5 27,32.5 33,33.5"      style="fill:none;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.QueenWhite",size:{width:42,height:38}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.QueenBlack=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#000000; stroke:none;">      <circle cx="6"    cy="12" r="2.75" />      <circle cx="14"   cy="9"  r="2.75" />      <circle cx="22.5" cy="8"  r="2.75" />      <circle cx="31"   cy="9"  r="2.75" />      <circle cx="39"   cy="12" r="2.75" />    </g>    <path       d="M 9,26 C 17.5,24.5 30,24.5 36,26 L 38.5,13.5 L 31,25 L 30.7,10.9 L 25.5,24.5 L 22.5,10 L 19.5,24.5 L 14.3,10.9 L 14,25 L 6.5,13.5 L 9,26 z"       style="stroke-linecap:butt; stroke:#000000;" />    <path       d="M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z"       style="stroke-linecap:butt;" />    <path       d="M 11,38.5 A 35,35 1 0 0 34,38.5"       style="fill:none; stroke:#000000; stroke-linecap:butt;" />    <path       d="M 11,29 A 35,35 1 0 1 34,29"       style="fill:none; stroke:#ffffff;" />    <path       d="M 12.5,31.5 L 32.5,31.5"       style="fill:none; stroke:#ffffff;" />    <path       d="M 11.5,34.5 A 35,35 1 0 0 33.5,34.5"       style="fill:none; stroke:#ffffff;" />    <path       d="M 10.5,37.5 A 35,35 1 0 0 34.5,37.5"       style="fill:none; stroke:#ffffff;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.QueenBlack",size:{width:42,height:38}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.RookWhite=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z "      style="stroke-linecap:butt;" />    <path      d="M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z "      style="stroke-linecap:butt;" />    <path      d="M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14"      style="stroke-linecap:butt;" />    <path      d="M 34,14 L 31,17 L 14,17 L 11,14" />    <path      d="M 31,17 L 31,29.5 L 14,29.5 L 14,17"      style="stroke-linecap:butt; stroke-linejoin:miter;" />    <path      d="M 31,29.5 L 32.5,32 L 12.5,32 L 14,29.5" />    <path      d="M 11,14 L 34,14"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.RookWhite",size:{width:32,height:34}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.RookBlack=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z "      style="stroke-linecap:butt;" />    <path      d="M 12.5,32 L 14,29.5 L 31,29.5 L 32.5,32 L 12.5,32 z "      style="stroke-linecap:butt;" />    <path      d="M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z "      style="stroke-linecap:butt;" />    <path      d="M 14,29.5 L 14,16.5 L 31,16.5 L 31,29.5 L 14,29.5 z "      style="stroke-linecap:butt;stroke-linejoin:miter;" />    <path      d="M 14,16.5 L 11,14 L 34,14 L 31,16.5 L 14,16.5 z "      style="stroke-linecap:butt;" />    <path      d="M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14 L 11,14 z "      style="stroke-linecap:butt;" />    <path      d="M 12,35.5 L 33,35.5 L 33,35.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 13,31.5 L 32,31.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 14,29.5 L 31,29.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 14,16.5 L 31,16.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 11,14 L 34,14"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.RookBlack",size:{width:32,height:34}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.BishopWhite=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-rule:evenodd; fill-opacity:1; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:round; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#ffffff; stroke:#000000; stroke-linecap:butt;">       <path        d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />      <path        d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />      <path        d="M 25 8 A 2.5 2.5 0 1 1  20,8 A 2.5 2.5 0 1 1  25 8 z" />    </g>    <path      d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.BishopWhite",size:{width:38,height:38}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.BishopBlack=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-rule:evenodd; fill-opacity:1; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:round; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#000000; stroke:#000000; stroke-linecap:butt;">       <path        d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />      <path        d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />      <path        d="M 25 8 A 2.5 2.5 0 1 1  20,8 A 2.5 2.5 0 1 1  25 8 z" />    </g>    <path       d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"       style="fill:none; stroke:#ffffff; stroke-linejoin:miter;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.BishopBlack",size:{width:38,height:38}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.KnightWhite=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18"      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10"      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z"      style="fill:#000000; stroke:#000000;" />    <path      d="M 15 15.5 A 0.5 1.5 0 1 1  14,15.5 A 0.5 1.5 0 1 1  15 15.5 z"      transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)"      style="fill:#000000; stroke:#000000;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.KnightWhite",size:{width:38,height:37}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.KnightBlack=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18"      style="fill:#000000; stroke:#000000;" />    <path      d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10"      style="fill:#000000; stroke:#000000;" />    <path      d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z"      style="fill:#ffffff; stroke:#ffffff;" />    <path      d="M 15 15.5 A 0.5 1.5 0 1 1  14,15.5 A 0.5 1.5 0 1 1  15 15.5 z"      transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)"      style="fill:#ffffff; stroke:#ffffff;" />    <path      d="M 24.55,10.4 L 24.1,11.85 L 24.6,12 C 27.75,13 30.25,14.49 32.5,18.75 C 34.75,23.01 35.75,29.06 35.25,39 L 35.2,39.5 L 37.45,39.5 L 37.5,39 C 38,28.94 36.62,22.15 34.25,17.66 C 31.88,13.17 28.46,11.02 25.06,10.5 L 24.55,10.4 z "      style="fill:#ffffff; stroke:none;" />  </g></g></g>',defaults:joint.util.deepSupplement({type:"chess.KnightBlack",size:{width:38,height:37}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.PawnWhite=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><path d="M 22,9 C 19.79,9 18,10.79 18,13 C 18,13.89 18.29,14.71 18.78,15.38 C 16.83,16.5 15.5,18.59 15.5,21 C 15.5,23.03 16.44,24.84 17.91,26.03 C 14.91,27.09 10.5,31.58 10.5,39.5 L 33.5,39.5 C 33.5,31.58 29.09,27.09 26.09,26.03 C 27.56,24.84 28.5,23.03 28.5,21 C 28.5,18.59 27.17,16.5 25.22,15.38 C 25.71,14.71 26,13.89 26,13 C 26,10.79 24.21,9 22,9 z "  style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:nonzero; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:miter; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;" /></g></g>',defaults:joint.util.deepSupplement({type:"chess.PawnWhite",size:{width:28,height:33}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.chess.PawnBlack=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><path d="M 22,9 C 19.79,9 18,10.79 18,13 C 18,13.89 18.29,14.71 18.78,15.38 C 16.83,16.5 15.5,18.59 15.5,21 C 15.5,23.03 16.44,24.84 17.91,26.03 C 14.91,27.09 10.5,31.58 10.5,39.5 L 33.5,39.5 C 33.5,31.58 29.09,27.09 26.09,26.03 C 27.56,24.84 28.5,23.03 28.5,21 C 28.5,18.59 27.17,16.5 25.22,15.38 C 25.71,14.71 26,13.89 26,13 C 26,10.79 24.21,9 22,9 z "  style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:nonzero; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:miter; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;" /></g></g>',defaults:joint.util.deepSupplement({type:"chess.PawnBlack",size:{width:28,height:33}},joint.shapes.basic.Generic.prototype.defaults)}),"object"==typeof exports&&(module.exports=joint.shapes.chess),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{basic:require("./joint.shapes.basic")},dia:{ElementView:require("../src/joint.dia.element").ElementView,Link:require("../src/joint.dia.link").Link}};if(joint.shapes.pn={},joint.shapes.pn.Place=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><circle class="root"/><g class="tokens" /></g><text class="label"/></g>',defaults:joint.util.deepSupplement({type:"pn.Place",size:{width:50,height:50},attrs:{".root":{r:25,fill:"white",stroke:"black",transform:"translate(25, 25)"},".label":{"text-anchor":"middle","ref-x":.5,"ref-y":-20,ref:".root",fill:"black","font-size":12},".tokens > circle":{fill:"black",r:5},".tokens.one > circle":{transform:"translate(25, 25)"},".tokens.two > circle:nth-child(1)":{transform:"translate(19, 25)"},".tokens.two > circle:nth-child(2)":{transform:"translate(31, 25)"},".tokens.three > circle:nth-child(1)":{transform:"translate(18, 29)"},".tokens.three > circle:nth-child(2)":{transform:"translate(25, 19)"},".tokens.three > circle:nth-child(3)":{transform:"translate(32, 29)"},".tokens.alot > text":{transform:"translate(25, 18)","text-anchor":"middle",fill:"black"}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.pn.PlaceView=joint.dia.ElementView.extend({initialize:function(){joint.dia.ElementView.prototype.initialize.apply(this,arguments),this.model.on("change:tokens",function(){this.renderTokens(),this.update()},this)},render:function(){joint.dia.ElementView.prototype.render.apply(this,arguments),this.renderTokens(),this.update()},renderTokens:function(){var t=this.$(".tokens").empty();t[0].className.baseVal="tokens";var e=this.model.get("tokens");if(e)switch(e){case 1:t[0].className.baseVal+=" one",t.append(V("<circle/>").node);break;case 2:t[0].className.baseVal+=" two",t.append(V("<circle/>").node,V("<circle/>").node);break;case 3:t[0].className.baseVal+=" three",t.append(V("<circle/>").node,V("<circle/>").node,V("<circle/>").node);break;default:t[0].className.baseVal+=" alot",t.append(V("<text/>").text(e+"").node)}}}),joint.shapes.pn.Transition=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><rect class="root"/></g></g><text class="label"/>',defaults:joint.util.deepSupplement({type:"pn.Transition",size:{width:12,height:50},attrs:{rect:{width:12,height:50,fill:"black",stroke:"black"},".label":{"text-anchor":"middle","ref-x":.5,"ref-y":-20,ref:"rect",fill:"black","font-size":12}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.pn.Link=joint.dia.Link.extend({defaults:joint.util.deepSupplement({attrs:{".marker-target":{d:"M 10 0 L 0 5 L 10 10 z"}}},joint.dia.Link.prototype.defaults)}),"object"==typeof exports&&(module.exports=joint.shapes.pn),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{basic:require("./joint.shapes.basic")},dia:{ElementView:require("../src/joint.dia.element").ElementView,Link:require("../src/joint.dia.link").Link}},_=require("lodash");if(joint.shapes.devs={},joint.shapes.devs.Model=joint.shapes.basic.Generic.extend(_.extend({},joint.shapes.basic.PortsModelInterface,{markup:'<g class="rotatable"><g class="scalable"><rect/></g><text class="label"/><g class="inPorts"/><g class="outPorts"/></g>',portMarkup:'<g class="port<%= id %>"><circle/><text/></g>',defaults:joint.util.deepSupplement({type:"devs.Model",size:{width:1,height:1},inPorts:[],outPorts:[],attrs:{".":{magnet:!1},rect:{width:150,height:250,stroke:"black"},circle:{r:10,magnet:!0,stroke:"black"},text:{fill:"black","pointer-events":"none"},".label":{text:"Model","ref-x":.3,"ref-y":.2},".inPorts text":{x:-15,dy:4,"text-anchor":"end"},".outPorts text":{x:15,dy:4}}},joint.shapes.basic.Generic.prototype.defaults),getPortAttrs:function(t,e,i,n,r){var a={},s="port"+e,o=n+">."+s,l=o+">text",c=o+">circle";return a[l]={text:t},a[c]={port:{id:t||_.uniqueId(r),type:r}},a[o]={ref:"rect","ref-y":(e+.5)*(1/i)},".outPorts"===n&&(a[o]["ref-dx"]=0),a}})),joint.shapes.devs.Atomic=joint.shapes.devs.Model.extend({defaults:joint.util.deepSupplement({type:"devs.Atomic",size:{width:80,height:80},attrs:{rect:{fill:"salmon"},".label":{text:"Atomic"},".inPorts circle":{fill:"PaleGreen"},".outPorts circle":{fill:"Tomato"}}},joint.shapes.devs.Model.prototype.defaults)}),joint.shapes.devs.Coupled=joint.shapes.devs.Model.extend({defaults:joint.util.deepSupplement({type:"devs.Coupled",size:{width:200,height:300},attrs:{rect:{fill:"seaGreen"},".label":{text:"Coupled"},".inPorts circle":{fill:"PaleGreen"},".outPorts circle":{fill:"Tomato"}}},joint.shapes.devs.Model.prototype.defaults)}),joint.shapes.devs.Link=joint.dia.Link.extend({defaults:{type:"devs.Link",attrs:{".connection":{"stroke-width":2}}}}),joint.shapes.devs.ModelView=joint.dia.ElementView.extend(joint.shapes.basic.PortsViewInterface),joint.shapes.devs.AtomicView=joint.shapes.devs.ModelView,joint.shapes.devs.CoupledView=joint.shapes.devs.ModelView,"object"==typeof exports&&(module.exports=joint.shapes.devs),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{basic:require("./joint.shapes.basic")},dia:{ElementView:require("../src/joint.dia.element").ElementView,Link:require("../src/joint.dia.link").Link}},_=require("lodash");if(joint.shapes.uml={},joint.shapes.uml.Class=joint.shapes.basic.Generic.extend({markup:['<g class="rotatable">','<g class="scalable">','<rect class="uml-class-name-rect"/><rect class="uml-class-attrs-rect"/><rect class="uml-class-methods-rect"/>',"</g>",'<text class="uml-class-name-text"/><text class="uml-class-attrs-text"/><text class="uml-class-methods-text"/>',"</g>"].join(""),defaults:joint.util.deepSupplement({type:"uml.Class",attrs:{rect:{width:200},".uml-class-name-rect":{stroke:"black","stroke-width":2,fill:"#3498db"},".uml-class-attrs-rect":{stroke:"black","stroke-width":2,fill:"#2980b9"},".uml-class-methods-rect":{stroke:"black","stroke-width":2,fill:"#2980b9"},".uml-class-name-text":{ref:".uml-class-name-rect","ref-y":.5,"ref-x":.5,"text-anchor":"middle","y-alignment":"middle","font-weight":"bold",fill:"black","font-size":12,"font-family":"Times New Roman"},".uml-class-attrs-text":{ref:".uml-class-attrs-rect","ref-y":5,"ref-x":5,fill:"black","font-size":12,"font-family":"Times New Roman"},".uml-class-methods-text":{ref:".uml-class-methods-rect","ref-y":5,"ref-x":5,fill:"black","font-size":12,"font-family":"Times New Roman"}},name:[],attributes:[],methods:[]},joint.shapes.basic.Generic.prototype.defaults),initialize:function(){_.bindAll(this,"updateRectangles"),this.on("change:name change:attributes change:methods",function(){this.updateRectangles(),this.trigger("uml-update")}),this.updateRectangles(),joint.shapes.basic.Generic.prototype.initialize.apply(this,arguments)},getClassName:function(){return this.get("name")},updateRectangles:function(){var t=this.get("attrs"),e=[{type:"name",text:this.getClassName()},{type:"attrs",text:this.get("attributes")},{type:"methods",text:this.get("methods")}],i=0;_.each(e,function(e){var n=_.isArray(e.text)?e.text:[e.text],r=20*n.length+20;t[".uml-class-"+e.type+"-text"].text=n.join("\n"),t[".uml-class-"+e.type+"-rect"].height=r,t[".uml-class-"+e.type+"-rect"].transform="translate(0,"+i+")",i+=r})}}),joint.shapes.uml.ClassView=joint.dia.ElementView.extend({initialize:function(){joint.dia.ElementView.prototype.initialize.apply(this,arguments),this.model.on("uml-update",_.bind(function(){this.update(),this.resize()},this))}}),joint.shapes.uml.Abstract=joint.shapes.uml.Class.extend({defaults:joint.util.deepSupplement({type:"uml.Abstract",attrs:{".uml-class-name-rect":{fill:"#e74c3c"},".uml-class-attrs-rect":{fill:"#c0392b"},".uml-class-methods-rect":{fill:"#c0392b"}}},joint.shapes.uml.Class.prototype.defaults),getClassName:function(){return["<<Abstract>>",this.get("name")]}}),joint.shapes.uml.AbstractView=joint.shapes.uml.ClassView,joint.shapes.uml.Interface=joint.shapes.uml.Class.extend({defaults:joint.util.deepSupplement({type:"uml.Interface",attrs:{".uml-class-name-rect":{fill:"#f1c40f"},".uml-class-attrs-rect":{fill:"#f39c12"},".uml-class-methods-rect":{fill:"#f39c12"}}},joint.shapes.uml.Class.prototype.defaults),getClassName:function(){return["<<Interface>>",this.get("name")]}}),joint.shapes.uml.InterfaceView=joint.shapes.uml.ClassView,joint.shapes.uml.Generalization=joint.dia.Link.extend({defaults:{type:"uml.Generalization",attrs:{".marker-target":{d:"M 20 0 L 0 10 L 20 20 z",fill:"white"}}}}),joint.shapes.uml.Implementation=joint.dia.Link.extend({defaults:{type:"uml.Implementation",attrs:{".marker-target":{d:"M 20 0 L 0 10 L 20 20 z",fill:"white"},".connection":{"stroke-dasharray":"3,3"}}}}),joint.shapes.uml.Aggregation=joint.dia.Link.extend({defaults:{type:"uml.Aggregation",attrs:{".marker-target":{d:"M 40 10 L 20 20 L 0 10 L 20 0 z",fill:"white"}}}}),joint.shapes.uml.Composition=joint.dia.Link.extend({defaults:{type:"uml.Composition",attrs:{".marker-target":{d:"M 40 10 L 20 20 L 0 10 L 20 0 z",fill:"black"}}}}),joint.shapes.uml.Association=joint.dia.Link.extend({defaults:{type:"uml.Association"}}),joint.shapes.uml.State=joint.shapes.basic.Generic.extend({markup:['<g class="rotatable">','<g class="scalable">',"<rect/>","</g>",'<path/><text class="uml-state-name"/><text class="uml-state-events"/>',"</g>"].join(""),defaults:joint.util.deepSupplement({type:"uml.State",attrs:{rect:{width:200,height:200,fill:"#ecf0f1",stroke:"#bdc3c7","stroke-width":3,rx:10,ry:10},path:{d:"M 0 20 L 200 20",stroke:"#bdc3c7","stroke-width":2},".uml-state-name":{ref:"rect","ref-x":.5,"ref-y":5,"text-anchor":"middle","font-family":"Courier New","font-size":14,fill:"#000000"},".uml-state-events":{ref:"path","ref-x":5,"ref-y":5,"font-family":"Courier New","font-size":14,fill:"#000000"}},name:"State",events:[]},joint.shapes.basic.Generic.prototype.defaults),initialize:function(){_.bindAll(this,"updateEvents","updatePath"),this.on({"change:name":function(){this.updateName(),this.trigger("change:attrs")},"change:events":function(){this.updateEvents(),this.trigger("change:attrs")},"change:size":this.updatePath}),this.updateName(),this.updateEvents(),this.updatePath(),joint.shapes.basic.Generic.prototype.initialize.apply(this,arguments)},updateName:function(){this.get("attrs")[".uml-state-name"].text=this.get("name")},updateEvents:function(){this.get("attrs")[".uml-state-events"].text=this.get("events").join("\n")},updatePath:function(){this.get("attrs").path.d="M 0 20 L "+this.get("size").width+" 20"}}),joint.shapes.uml.StartState=joint.shapes.basic.Circle.extend({defaults:joint.util.deepSupplement({type:"uml.StartState",attrs:{circle:{fill:"#34495e",stroke:"#2c3e50","stroke-width":2,rx:1}}},joint.shapes.basic.Circle.prototype.defaults)}),joint.shapes.uml.EndState=joint.shapes.basic.Generic.extend({markup:'<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',defaults:joint.util.deepSupplement({type:"uml.EndState",size:{width:20,height:20},attrs:{"circle.outer":{transform:"translate(10, 10)",r:10,fill:"white",stroke:"#2c3e50"},"circle.inner":{transform:"translate(10, 10)",r:6,fill:"#34495e"}}},joint.shapes.basic.Generic.prototype.defaults)}),joint.shapes.uml.Transition=joint.dia.Link.extend({defaults:{type:"uml.Transition",attrs:{".marker-target":{d:"M 10 0 L 0 5 L 10 10 z",fill:"#34495e",stroke:"#2c3e50"},".connection":{stroke:"#2c3e50"}}}}),"object"==typeof exports&&(module.exports=joint.shapes.uml),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{basic:require("./joint.shapes.basic")},dia:{Link:require("../src/joint.dia.link").Link}};if(joint.shapes.logic={},joint.shapes.logic.Gate=joint.shapes.basic.Generic.extend({defaults:joint.util.deepSupplement({type:"logic.Gate",size:{width:80,height:40},attrs:{".":{magnet:!1},".body":{width:100,height:50},circle:{r:7,stroke:"black",fill:"transparent","stroke-width":2}}},joint.shapes.basic.Generic.prototype.defaults),operation:function(){return!0}}),joint.shapes.logic.IO=joint.shapes.logic.Gate.extend({markup:'<g class="rotatable"><g class="scalable"><rect class="body"/></g><path class="wire"/><circle/><text/></g>',defaults:joint.util.deepSupplement({type:"logic.IO",size:{width:60,height:30},attrs:{".body":{fill:"white",stroke:"black","stroke-width":2},".wire":{ref:".body","ref-y":.5,stroke:"black"},text:{fill:"black",ref:".body","ref-x":.5,"ref-y":.5,"y-alignment":"middle","text-anchor":"middle","font-weight":"bold","font-variant":"small-caps","text-transform":"capitalize","font-size":"14px"}}},joint.shapes.logic.Gate.prototype.defaults)}),joint.shapes.logic.Input=joint.shapes.logic.IO.extend({defaults:joint.util.deepSupplement({type:"logic.Input",attrs:{".wire":{"ref-dx":0,d:"M 0 0 L 23 0"},circle:{ref:".body","ref-dx":30,"ref-y":.5,magnet:!0,"class":"output",port:"out"},text:{text:"input"}}},joint.shapes.logic.IO.prototype.defaults)}),joint.shapes.logic.Output=joint.shapes.logic.IO.extend({defaults:joint.util.deepSupplement({type:"logic.Output",attrs:{".wire":{"ref-x":0,d:"M 0 0 L -23 0"},circle:{ref:".body","ref-x":-30,"ref-y":.5,magnet:"passive","class":"input",port:"in"},text:{text:"output"}}},joint.shapes.logic.IO.prototype.defaults)}),joint.shapes.logic.Gate11=joint.shapes.logic.Gate.extend({markup:'<g class="rotatable"><g class="scalable"><image class="body"/></g><circle class="input"/><circle class="output"/></g>',defaults:joint.util.deepSupplement({type:"logic.Gate11",attrs:{".input":{ref:".body","ref-x":-2,"ref-y":.5,magnet:"passive",port:"in"},".output":{ref:".body","ref-dx":2,"ref-y":.5,magnet:!0,port:"out"}}},joint.shapes.logic.Gate.prototype.defaults)}),joint.shapes.logic.Gate21=joint.shapes.logic.Gate.extend({markup:'<g class="rotatable"><g class="scalable"><image class="body"/></g><circle class="input input1"/><circle  class="input input2"/><circle class="output"/></g>',defaults:joint.util.deepSupplement({type:"logic.Gate21",attrs:{".input1":{ref:".body","ref-x":-2,"ref-y":.3,magnet:"passive",port:"in1"},".input2":{ref:".body","ref-x":-2,"ref-y":.7,magnet:"passive",port:"in2"},".output":{ref:".body","ref-dx":2,"ref-y":.5,magnet:!0,port:"out"}}},joint.shapes.logic.Gate.prototype.defaults)}),joint.shapes.logic.Repeater=joint.shapes.logic.Gate11.extend({defaults:joint.util.deepSupplement({type:"logic.Repeater",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9Ik5PVCBBTlNJLnN2ZyIKICAgaW5rc2NhcGU6b3V0cHV0X2V4dGVuc2lvbj0ib3JnLmlua3NjYXBlLm91dHB1dC5zdmcuaW5rc2NhcGUiPgogIDxkZWZzCiAgICAgaWQ9ImRlZnM0Ij4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAxNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF96PSI1MCA6IDE1IDogMSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIyNSA6IDEwIDogMSIKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI3MTQiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMC41IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEgOiAwLjUgOiAxIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjAuNSA6IDAuMzMzMzMzMzMgOiAxIgogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgwNiIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgxOSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIzNzIuMDQ3MjQgOiAzNTAuNzg3MzkgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNzQ0LjA5NDQ4IDogNTI2LjE4MTA5IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MjYuMTgxMDkgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjc3NyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSI3NSA6IDQwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjE1MCA6IDYwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA2MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUzMjc1IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjUwIDogMzMuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEwMCA6IDUwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmU1NTMzIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjMyIDogMjEuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjY0IDogMzIgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDMyIDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI1NTciCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMjUgOiAxNi42NjY2NjcgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNTAgOiAyNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMjUgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICA8L2RlZnM+CiAgPHNvZGlwb2RpOm5hbWVkdmlldwogICAgIGlkPSJiYXNlIgogICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIKICAgICBib3JkZXJjb2xvcj0iIzY2NjY2NiIKICAgICBib3JkZXJvcGFjaXR5PSIxLjAiCiAgICAgaW5rc2NhcGU6cGFnZW9wYWNpdHk9IjAuMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOnpvb209IjgiCiAgICAgaW5rc2NhcGU6Y3g9Ijg0LjY4NTM1MiIKICAgICBpbmtzY2FwZTpjeT0iMTUuMjg4NjI4IgogICAgIGlua3NjYXBlOmRvY3VtZW50LXVuaXRzPSJweCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJsYXllcjEiCiAgICAgc2hvd2dyaWQ9InRydWUiCiAgICAgaW5rc2NhcGU6Z3JpZC1iYm94PSJ0cnVlIgogICAgIGlua3NjYXBlOmdyaWQtcG9pbnRzPSJ0cnVlIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwMDAwIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTM5OSIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI4NzQiCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjMzIgogICAgIGlua3NjYXBlOndpbmRvdy15PSIwIgogICAgIGlua3NjYXBlOnNuYXAtYmJveD0idHJ1ZSI+CiAgICA8aW5rc2NhcGU6Z3JpZAogICAgICAgaWQ9IkdyaWRGcm9tUHJlMDQ2U2V0dGluZ3MiCiAgICAgICB0eXBlPSJ4eWdyaWQiCiAgICAgICBvcmlnaW54PSIwcHgiCiAgICAgICBvcmlnaW55PSIwcHgiCiAgICAgICBzcGFjaW5neD0iMXB4IgogICAgICAgc3BhY2luZ3k9IjFweCIKICAgICAgIGNvbG9yPSIjMDAwMGZmIgogICAgICAgZW1wY29sb3I9IiMwMDAwZmYiCiAgICAgICBvcGFjaXR5PSIwLjIiCiAgICAgICBlbXBvcGFjaXR5PSIwLjQiCiAgICAgICBlbXBzcGFjaW5nPSI1IgogICAgICAgdmlzaWJsZT0idHJ1ZSIKICAgICAgIGVuYWJsZWQ9InRydWUiIC8+CiAgPC9zb2RpcG9kaTpuYW1lZHZpZXc+CiAgPG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhNyI+CiAgICA8cmRmOlJERj4KICAgICAgPGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPgogICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PgogICAgICAgIDxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz4KICAgICAgPC9jYzpXb3JrPgogICAgPC9yZGY6UkRGPgogIDwvbWV0YWRhdGE+CiAgPGcKICAgICBpbmtzY2FwZTpsYWJlbD0iTGF5ZXIgMSIKICAgICBpbmtzY2FwZTpncm91cG1vZGU9ImxheWVyIgogICAgIGlkPSJsYXllcjEiPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjEuOTk5OTk5ODg7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gNzIuMTU2OTEsMjUgTCA5NSwyNSIKICAgICAgIGlkPSJwYXRoMzA1OSIKICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2MiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MjtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgZD0iTSAyOS4wNDM0NzgsMjUgTCA1LjA0MzQ3ODEsMjUiCiAgICAgICBpZD0icGF0aDMwNjEiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MztzdHJva2UtbGluZWpvaW46bWl0ZXI7bWFya2VyOm5vbmU7c3Ryb2tlLW9wYWNpdHk6MTt2aXNpYmlsaXR5OnZpc2libGU7ZGlzcGxheTppbmxpbmU7b3ZlcmZsb3c6dmlzaWJsZTtlbmFibGUtYmFja2dyb3VuZDphY2N1bXVsYXRlIgogICAgICAgZD0iTSAyOC45Njg3NSwyLjU5Mzc1IEwgMjguOTY4NzUsNSBMIDI4Ljk2ODc1LDQ1IEwgMjguOTY4NzUsNDcuNDA2MjUgTCAzMS4xMjUsNDYuMzQzNzUgTCA3Mi4xNTYyNSwyNi4zNDM3NSBMIDcyLjE1NjI1LDIzLjY1NjI1IEwgMzEuMTI1LDMuNjU2MjUgTCAyOC45Njg3NSwyLjU5Mzc1IHogTSAzMS45Njg3NSw3LjQwNjI1IEwgNjguMDkzNzUsMjUgTCAzMS45Njg3NSw0Mi41OTM3NSBMIDMxLjk2ODc1LDcuNDA2MjUgeiIKICAgICAgIGlkPSJwYXRoMjYzOCIKICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2NjY2NjY2NjY2NjYyIgLz4KICA8L2c+Cjwvc3ZnPgo="}}},joint.shapes.logic.Gate11.prototype.defaults),operation:function(t){return t
+}}),joint.shapes.logic.Not=joint.shapes.logic.Gate11.extend({defaults:joint.util.deepSupplement({type:"logic.Not",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9Ik5PVCBBTlNJLnN2ZyIKICAgaW5rc2NhcGU6b3V0cHV0X2V4dGVuc2lvbj0ib3JnLmlua3NjYXBlLm91dHB1dC5zdmcuaW5rc2NhcGUiPgogIDxkZWZzCiAgICAgaWQ9ImRlZnM0Ij4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAxNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF96PSI1MCA6IDE1IDogMSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIyNSA6IDEwIDogMSIKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI3MTQiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMC41IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEgOiAwLjUgOiAxIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjAuNSA6IDAuMzMzMzMzMzMgOiAxIgogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgwNiIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgxOSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIzNzIuMDQ3MjQgOiAzNTAuNzg3MzkgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNzQ0LjA5NDQ4IDogNTI2LjE4MTA5IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MjYuMTgxMDkgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjc3NyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSI3NSA6IDQwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjE1MCA6IDYwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA2MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUzMjc1IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjUwIDogMzMuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEwMCA6IDUwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmU1NTMzIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjMyIDogMjEuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjY0IDogMzIgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDMyIDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI1NTciCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMjUgOiAxNi42NjY2NjcgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNTAgOiAyNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMjUgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICA8L2RlZnM+CiAgPHNvZGlwb2RpOm5hbWVkdmlldwogICAgIGlkPSJiYXNlIgogICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIKICAgICBib3JkZXJjb2xvcj0iIzY2NjY2NiIKICAgICBib3JkZXJvcGFjaXR5PSIxLjAiCiAgICAgaW5rc2NhcGU6cGFnZW9wYWNpdHk9IjAuMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOnpvb209IjgiCiAgICAgaW5rc2NhcGU6Y3g9Ijg0LjY4NTM1MiIKICAgICBpbmtzY2FwZTpjeT0iMTUuMjg4NjI4IgogICAgIGlua3NjYXBlOmRvY3VtZW50LXVuaXRzPSJweCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJsYXllcjEiCiAgICAgc2hvd2dyaWQ9InRydWUiCiAgICAgaW5rc2NhcGU6Z3JpZC1iYm94PSJ0cnVlIgogICAgIGlua3NjYXBlOmdyaWQtcG9pbnRzPSJ0cnVlIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwMDAwIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTM5OSIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI4NzQiCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjMzIgogICAgIGlua3NjYXBlOndpbmRvdy15PSIwIgogICAgIGlua3NjYXBlOnNuYXAtYmJveD0idHJ1ZSI+CiAgICA8aW5rc2NhcGU6Z3JpZAogICAgICAgaWQ9IkdyaWRGcm9tUHJlMDQ2U2V0dGluZ3MiCiAgICAgICB0eXBlPSJ4eWdyaWQiCiAgICAgICBvcmlnaW54PSIwcHgiCiAgICAgICBvcmlnaW55PSIwcHgiCiAgICAgICBzcGFjaW5neD0iMXB4IgogICAgICAgc3BhY2luZ3k9IjFweCIKICAgICAgIGNvbG9yPSIjMDAwMGZmIgogICAgICAgZW1wY29sb3I9IiMwMDAwZmYiCiAgICAgICBvcGFjaXR5PSIwLjIiCiAgICAgICBlbXBvcGFjaXR5PSIwLjQiCiAgICAgICBlbXBzcGFjaW5nPSI1IgogICAgICAgdmlzaWJsZT0idHJ1ZSIKICAgICAgIGVuYWJsZWQ9InRydWUiIC8+CiAgPC9zb2RpcG9kaTpuYW1lZHZpZXc+CiAgPG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhNyI+CiAgICA8cmRmOlJERj4KICAgICAgPGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPgogICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PgogICAgICAgIDxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz4KICAgICAgPC9jYzpXb3JrPgogICAgPC9yZGY6UkRGPgogIDwvbWV0YWRhdGE+CiAgPGcKICAgICBpbmtzY2FwZTpsYWJlbD0iTGF5ZXIgMSIKICAgICBpbmtzY2FwZTpncm91cG1vZGU9ImxheWVyIgogICAgIGlkPSJsYXllcjEiPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjEuOTk5OTk5ODg7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gNzkuMTU2OTEsMjUgTCA5NSwyNSIKICAgICAgIGlkPSJwYXRoMzA1OSIKICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2MiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MjtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgZD0iTSAyOS4wNDM0NzgsMjUgTCA1LjA0MzQ3ODEsMjUiCiAgICAgICBpZD0icGF0aDMwNjEiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MztzdHJva2UtbGluZWpvaW46bWl0ZXI7bWFya2VyOm5vbmU7c3Ryb2tlLW9wYWNpdHk6MTt2aXNpYmlsaXR5OnZpc2libGU7ZGlzcGxheTppbmxpbmU7b3ZlcmZsb3c6dmlzaWJsZTtlbmFibGUtYmFja2dyb3VuZDphY2N1bXVsYXRlIgogICAgICAgZD0iTSAyOC45Njg3NSwyLjU5Mzc1IEwgMjguOTY4NzUsNSBMIDI4Ljk2ODc1LDQ1IEwgMjguOTY4NzUsNDcuNDA2MjUgTCAzMS4xMjUsNDYuMzQzNzUgTCA3Mi4xNTYyNSwyNi4zNDM3NSBMIDcyLjE1NjI1LDIzLjY1NjI1IEwgMzEuMTI1LDMuNjU2MjUgTCAyOC45Njg3NSwyLjU5Mzc1IHogTSAzMS45Njg3NSw3LjQwNjI1IEwgNjguMDkzNzUsMjUgTCAzMS45Njg3NSw0Mi41OTM3NSBMIDMxLjk2ODc1LDcuNDA2MjUgeiIKICAgICAgIGlkPSJwYXRoMjYzOCIKICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2NjY2NjY2NjY2NjYyIgLz4KICAgIDxwYXRoCiAgICAgICBzb2RpcG9kaTp0eXBlPSJhcmMiCiAgICAgICBzdHlsZT0iZmlsbDpub25lO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDozO3N0cm9rZS1saW5lam9pbjptaXRlcjttYXJrZXI6bm9uZTtzdHJva2Utb3BhY2l0eToxO3Zpc2liaWxpdHk6dmlzaWJsZTtkaXNwbGF5OmlubGluZTtvdmVyZmxvdzp2aXNpYmxlO2VuYWJsZS1iYWNrZ3JvdW5kOmFjY3VtdWxhdGUiCiAgICAgICBpZD0icGF0aDI2NzEiCiAgICAgICBzb2RpcG9kaTpjeD0iNzYiCiAgICAgICBzb2RpcG9kaTpjeT0iMjUiCiAgICAgICBzb2RpcG9kaTpyeD0iNCIKICAgICAgIHNvZGlwb2RpOnJ5PSI0IgogICAgICAgZD0iTSA4MCwyNSBBIDQsNCAwIDEgMSA3MiwyNSBBIDQsNCAwIDEgMSA4MCwyNSB6IgogICAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEsMCkiIC8+CiAgPC9nPgo8L3N2Zz4K"}}},joint.shapes.logic.Gate11.prototype.defaults),operation:function(t){return!t}}),joint.shapes.logic.Or=joint.shapes.logic.Gate21.extend({defaults:joint.util.deepSupplement({type:"logic.Or",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9Ik9SIEFOU0kuc3ZnIgogICBpbmtzY2FwZTpvdXRwdXRfZXh0ZW5zaW9uPSJvcmcuaW5rc2NhcGUub3V0cHV0LnN2Zy5pbmtzY2FwZSI+CiAgPGRlZnMKICAgICBpZD0iZGVmczQiPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDE1IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3o9IjUwIDogMTUgOiAxIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjI1IDogMTAgOiAxIgogICAgICAgaWQ9InBlcnNwZWN0aXZlMjcxNCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAwLjUgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfej0iMSA6IDAuNSA6IDEiCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMC41IDogMC4zMzMzMzMzMyA6IDEiCiAgICAgICBpZD0icGVyc3BlY3RpdmUyODA2IiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUyODE5IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjM3Mi4wNDcyNCA6IDM1MC43ODczOSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSI3NDQuMDk0NDggOiA1MjYuMTgxMDkgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDUyNi4xODEwOSA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUyNzc3IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49Ijc1IDogNDAgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iMTUwIDogNjAgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDYwIDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTMyNzUiCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iNTAgOiAzMy4zMzMzMzMgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iMTAwIDogNTAgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDUwIDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTU1MzMiCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMzIgOiAyMS4zMzMzMzMgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNjQgOiAzMiA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMzIgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjU1NyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIyNSA6IDE2LjY2NjY2NyA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSI1MCA6IDI1IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAyNSA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogIDwvZGVmcz4KICA8c29kaXBvZGk6bmFtZWR2aWV3CiAgICAgaWQ9ImJhc2UiCiAgICAgcGFnZWNvbG9yPSIjZmZmZmZmIgogICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IgogICAgIGJvcmRlcm9wYWNpdHk9IjEuMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMC4wIgogICAgIGlua3NjYXBlOnBhZ2VzaGFkb3c9IjIiCiAgICAgaW5rc2NhcGU6em9vbT0iNCIKICAgICBpbmtzY2FwZTpjeD0iMTEzLjAwMDM5IgogICAgIGlua3NjYXBlOmN5PSIxMi44OTM3MzEiCiAgICAgaW5rc2NhcGU6ZG9jdW1lbnQtdW5pdHM9InB4IgogICAgIGlua3NjYXBlOmN1cnJlbnQtbGF5ZXI9ImcyNTYwIgogICAgIHNob3dncmlkPSJmYWxzZSIKICAgICBpbmtzY2FwZTpncmlkLWJib3g9InRydWUiCiAgICAgaW5rc2NhcGU6Z3JpZC1wb2ludHM9InRydWUiCiAgICAgZ3JpZHRvbGVyYW5jZT0iMTAwMDAiCiAgICAgaW5rc2NhcGU6d2luZG93LXdpZHRoPSIxMzk5IgogICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9Ijg3NCIKICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMzciCiAgICAgaW5rc2NhcGU6d2luZG93LXk9Ii00IgogICAgIGlua3NjYXBlOnNuYXAtYmJveD0idHJ1ZSI+CiAgICA8aW5rc2NhcGU6Z3JpZAogICAgICAgaWQ9IkdyaWRGcm9tUHJlMDQ2U2V0dGluZ3MiCiAgICAgICB0eXBlPSJ4eWdyaWQiCiAgICAgICBvcmlnaW54PSIwcHgiCiAgICAgICBvcmlnaW55PSIwcHgiCiAgICAgICBzcGFjaW5neD0iMXB4IgogICAgICAgc3BhY2luZ3k9IjFweCIKICAgICAgIGNvbG9yPSIjMDAwMGZmIgogICAgICAgZW1wY29sb3I9IiMwMDAwZmYiCiAgICAgICBvcGFjaXR5PSIwLjIiCiAgICAgICBlbXBvcGFjaXR5PSIwLjQiCiAgICAgICBlbXBzcGFjaW5nPSI1IgogICAgICAgdmlzaWJsZT0idHJ1ZSIKICAgICAgIGVuYWJsZWQ9InRydWUiIC8+CiAgPC9zb2RpcG9kaTpuYW1lZHZpZXc+CiAgPG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhNyI+CiAgICA8cmRmOlJERj4KICAgICAgPGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPgogICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PgogICAgICAgIDxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz4KICAgICAgPC9jYzpXb3JrPgogICAgPC9yZGY6UkRGPgogIDwvbWV0YWRhdGE+CiAgPGcKICAgICBpbmtzY2FwZTpsYWJlbD0iTGF5ZXIgMSIKICAgICBpbmtzY2FwZTpncm91cG1vZGU9ImxheWVyIgogICAgIGlkPSJsYXllcjEiPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjI7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Im0gNzAsMjUgYyAyMCwwIDI1LDAgMjUsMCIKICAgICAgIGlkPSJwYXRoMzA1OSIKICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2MiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MjtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgZD0iTSAzMSwxNSA1LDE1IgogICAgICAgaWQ9InBhdGgzMDYxIiAvPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjEuOTk5OTk5ODg7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gMzIsMzUgNSwzNSIKICAgICAgIGlkPSJwYXRoMzk0NCIgLz4KICAgIDxnCiAgICAgICBpZD0iZzI1NjAiCiAgICAgICBpbmtzY2FwZTpsYWJlbD0iTGF5ZXIgMSIKICAgICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDI2LjUsLTM5LjUpIj4KICAgICAgPHBhdGgKICAgICAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MztzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgICBkPSJNIC0yLjQwNjI1LDQ0LjUgTCAtMC40MDYyNSw0Ni45Mzc1IEMgLTAuNDA2MjUsNDYuOTM3NSA1LjI1LDUzLjkzNzU0OSA1LjI1LDY0LjUgQyA1LjI1LDc1LjA2MjQ1MSAtMC40MDYyNSw4Mi4wNjI1IC0wLjQwNjI1LDgyLjA2MjUgTCAtMi40MDYyNSw4NC41IEwgMC43NSw4NC41IEwgMTQuNzUsODQuNSBDIDE3LjE1ODA3Niw4NC41MDAwMDEgMjIuNDM5Njk5LDg0LjUyNDUxNCAyOC4zNzUsODIuMDkzNzUgQyAzNC4zMTAzMDEsNzkuNjYyOTg2IDQwLjkxMTUzNiw3NC43NTA0ODQgNDYuMDYyNSw2NS4yMTg3NSBMIDQ0Ljc1LDY0LjUgTCA0Ni4wNjI1LDYzLjc4MTI1IEMgMzUuNzU5Mzg3LDQ0LjcxNTU5IDE5LjUwNjU3NCw0NC41IDE0Ljc1LDQ0LjUgTCAwLjc1LDQ0LjUgTCAtMi40MDYyNSw0NC41IHogTSAzLjQ2ODc1LDQ3LjUgTCAxNC43NSw0Ny41IEMgMTkuNDM0MTczLDQ3LjUgMzMuMDM2ODUsNDcuMzY5NzkzIDQyLjcxODc1LDY0LjUgQyAzNy45NTE5NjQsNzIuOTI5MDc1IDMyLjE5NzQ2OSw3Ny4xODM5MSAyNyw3OS4zMTI1IEMgMjEuNjM5MzM5LDgxLjUwNzkyNCAxNy4xNTgwNzUsODEuNTAwMDAxIDE0Ljc1LDgxLjUgTCAzLjUsODEuNSBDIDUuMzczNTg4NCw3OC4zOTE1NjYgOC4yNSw3Mi40NTA2NSA4LjI1LDY0LjUgQyA4LjI1LDU2LjUyNjY0NiA1LjM0MTQ2ODYsNTAuNTk5ODE1IDMuNDY4NzUsNDcuNSB6IgogICAgICAgICBpZD0icGF0aDQ5NzMiCiAgICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2NzY2NjY3NjY2NjY2NjY2NzY2NzYyIgLz4KICAgIDwvZz4KICA8L2c+Cjwvc3ZnPgo="}}},joint.shapes.logic.Gate21.prototype.defaults),operation:function(t,e){return t||e}}),joint.shapes.logic.And=joint.shapes.logic.Gate21.extend({defaults:joint.util.deepSupplement({type:"logic.And",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9IkFORCBBTlNJLnN2ZyIKICAgaW5rc2NhcGU6b3V0cHV0X2V4dGVuc2lvbj0ib3JnLmlua3NjYXBlLm91dHB1dC5zdmcuaW5rc2NhcGUiPgogIDxkZWZzCiAgICAgaWQ9ImRlZnM0Ij4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAxNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF96PSI1MCA6IDE1IDogMSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIyNSA6IDEwIDogMSIKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI3MTQiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMC41IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEgOiAwLjUgOiAxIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjAuNSA6IDAuMzMzMzMzMzMgOiAxIgogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgwNiIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgxOSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIzNzIuMDQ3MjQgOiAzNTAuNzg3MzkgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNzQ0LjA5NDQ4IDogNTI2LjE4MTA5IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MjYuMTgxMDkgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjc3NyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSI3NSA6IDQwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjE1MCA6IDYwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA2MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUzMjc1IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjUwIDogMzMuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEwMCA6IDUwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmU1NTMzIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjMyIDogMjEuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjY0IDogMzIgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDMyIDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgPC9kZWZzPgogIDxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBpZD0iYmFzZSIKICAgICBwYWdlY29sb3I9IiNmZmZmZmYiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMS4wIgogICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwLjAiCiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIKICAgICBpbmtzY2FwZTp6b29tPSI4IgogICAgIGlua3NjYXBlOmN4PSI1Ni42OTgzNDgiCiAgICAgaW5rc2NhcGU6Y3k9IjI1LjMyNjg5OSIKICAgICBpbmtzY2FwZTpkb2N1bWVudC11bml0cz0icHgiCiAgICAgaW5rc2NhcGU6Y3VycmVudC1sYXllcj0ibGF5ZXIxIgogICAgIHNob3dncmlkPSJ0cnVlIgogICAgIGlua3NjYXBlOmdyaWQtYmJveD0idHJ1ZSIKICAgICBpbmtzY2FwZTpncmlkLXBvaW50cz0idHJ1ZSIKICAgICBncmlkdG9sZXJhbmNlPSIxMDAwMCIKICAgICBpbmtzY2FwZTp3aW5kb3ctd2lkdGg9IjEzOTkiCiAgICAgaW5rc2NhcGU6d2luZG93LWhlaWdodD0iODc0IgogICAgIGlua3NjYXBlOndpbmRvdy14PSIzMyIKICAgICBpbmtzY2FwZTp3aW5kb3cteT0iMCIKICAgICBpbmtzY2FwZTpzbmFwLWJib3g9InRydWUiPgogICAgPGlua3NjYXBlOmdyaWQKICAgICAgIGlkPSJHcmlkRnJvbVByZTA0NlNldHRpbmdzIgogICAgICAgdHlwZT0ieHlncmlkIgogICAgICAgb3JpZ2lueD0iMHB4IgogICAgICAgb3JpZ2lueT0iMHB4IgogICAgICAgc3BhY2luZ3g9IjFweCIKICAgICAgIHNwYWNpbmd5PSIxcHgiCiAgICAgICBjb2xvcj0iIzAwMDBmZiIKICAgICAgIGVtcGNvbG9yPSIjMDAwMGZmIgogICAgICAgb3BhY2l0eT0iMC4yIgogICAgICAgZW1wb3BhY2l0eT0iMC40IgogICAgICAgZW1wc3BhY2luZz0iNSIKICAgICAgIHZpc2libGU9InRydWUiCiAgICAgICBlbmFibGVkPSJ0cnVlIiAvPgogIDwvc29kaXBvZGk6bmFtZWR2aWV3PgogIDxtZXRhZGF0YQogICAgIGlkPSJtZXRhZGF0YTciPgogICAgPHJkZjpSREY+CiAgICAgIDxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj4KICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4KICAgICAgICA8ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+CiAgICAgIDwvY2M6V29yaz4KICAgIDwvcmRmOlJERj4KICA8L21ldGFkYXRhPgogIDxnCiAgICAgaW5rc2NhcGU6bGFiZWw9IkxheWVyIDEiCiAgICAgaW5rc2NhcGU6Z3JvdXBtb2RlPSJsYXllciIKICAgICBpZD0ibGF5ZXIxIj4KICAgIDxwYXRoCiAgICAgICBzdHlsZT0iZmlsbDpub25lO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICBkPSJtIDcwLDI1IGMgMjAsMCAyNSwwIDI1LDAiCiAgICAgICBpZD0icGF0aDMwNTkiCiAgICAgICBzb2RpcG9kaTpub2RldHlwZXM9ImNjIiAvPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjI7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gMzEsMTUgNSwxNSIKICAgICAgIGlkPSJwYXRoMzA2MSIgLz4KICAgIDxwYXRoCiAgICAgICBzdHlsZT0iZmlsbDpub25lO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoxLjk5OTk5OTg4O3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICBkPSJNIDMyLDM1IDUsMzUiCiAgICAgICBpZD0icGF0aDM5NDQiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZvbnQtc2l6ZTptZWRpdW07Zm9udC1zdHlsZTpub3JtYWw7Zm9udC12YXJpYW50Om5vcm1hbDtmb250LXdlaWdodDpub3JtYWw7Zm9udC1zdHJldGNoOm5vcm1hbDt0ZXh0LWluZGVudDowO3RleHQtYWxpZ246c3RhcnQ7dGV4dC1kZWNvcmF0aW9uOm5vbmU7bGluZS1oZWlnaHQ6bm9ybWFsO2xldHRlci1zcGFjaW5nOm5vcm1hbDt3b3JkLXNwYWNpbmc6bm9ybWFsO3RleHQtdHJhbnNmb3JtOm5vbmU7ZGlyZWN0aW9uOmx0cjtibG9jay1wcm9ncmVzc2lvbjp0Yjt3cml0aW5nLW1vZGU6bHItdGI7dGV4dC1hbmNob3I6c3RhcnQ7ZmlsbDojMDAwMDAwO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTpub25lO3N0cm9rZS13aWR0aDozO21hcmtlcjpub25lO3Zpc2liaWxpdHk6dmlzaWJsZTtkaXNwbGF5OmlubGluZTtvdmVyZmxvdzp2aXNpYmxlO2VuYWJsZS1iYWNrZ3JvdW5kOmFjY3VtdWxhdGU7Zm9udC1mYW1pbHk6Qml0c3RyZWFtIFZlcmEgU2FuczstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOkJpdHN0cmVhbSBWZXJhIFNhbnMiCiAgICAgICBkPSJNIDMwLDUgTCAzMCw2LjQyODU3MTQgTCAzMCw0My41NzE0MjkgTCAzMCw0NSBMIDMxLjQyODU3MSw0NSBMIDUwLjQ3NjE5LDQ1IEMgNjEuNzQ0MDk4LDQ1IDcwLjQ3NjE5LDM1Ljk5OTk1NSA3MC40NzYxOSwyNSBDIDcwLjQ3NjE5LDE0LjAwMDA0NSA2MS43NDQwOTksNS4wMDAwMDAyIDUwLjQ3NjE5LDUgQyA1MC40NzYxOSw1IDUwLjQ3NjE5LDUgMzEuNDI4NTcxLDUgTCAzMCw1IHogTSAzMi44NTcxNDMsNy44NTcxNDI5IEMgNDAuODM0MjY0LDcuODU3MTQyOSA0NS45MTgzNjgsNy44NTcxNDI5IDQ4LjA5NTIzOCw3Ljg1NzE0MjkgQyA0OS4yODU3MTQsNy44NTcxNDI5IDQ5Ljg4MDk1Miw3Ljg1NzE0MjkgNTAuMTc4NTcxLDcuODU3MTQyOSBDIDUwLjMyNzM4MSw3Ljg1NzE0MjkgNTAuNDA5MjI3LDcuODU3MTQyOSA1MC40NDY0MjksNy44NTcxNDI5IEMgNTAuNDY1MDI5LDcuODU3MTQyOSA1MC40NzE1NDMsNy44NTcxNDI5IDUwLjQ3NjE5LDcuODU3MTQyOSBDIDYwLjIzNjg1Myw3Ljg1NzE0MyA2Ny4xNDI4NTcsMTUuNDk3MDk4IDY3LjE0Mjg1NywyNSBDIDY3LjE0Mjg1NywzNC41MDI5MDIgNTkuNzYwNjYyLDQyLjE0Mjg1NyA1MCw0Mi4xNDI4NTcgTCAzMi44NTcxNDMsNDIuMTQyODU3IEwgMzIuODU3MTQzLDcuODU3MTQyOSB6IgogICAgICAgaWQ9InBhdGgyODg0IgogICAgICAgc29kaXBvZGk6bm9kZXR5cGVzPSJjY2NjY2NzY2NjY3Nzc3NzY2NjIiAvPgogIDwvZz4KPC9zdmc+Cg=="}}},joint.shapes.logic.Gate21.prototype.defaults),operation:function(t,e){return t&&e}}),joint.shapes.logic.Nor=joint.shapes.logic.Gate21.extend({defaults:joint.util.deepSupplement({type:"logic.Nor",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9Ik5PUiBBTlNJLnN2ZyIKICAgaW5rc2NhcGU6b3V0cHV0X2V4dGVuc2lvbj0ib3JnLmlua3NjYXBlLm91dHB1dC5zdmcuaW5rc2NhcGUiPgogIDxkZWZzCiAgICAgaWQ9ImRlZnM0Ij4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAxNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF96PSI1MCA6IDE1IDogMSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIyNSA6IDEwIDogMSIKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI3MTQiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMC41IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEgOiAwLjUgOiAxIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjAuNSA6IDAuMzMzMzMzMzMgOiAxIgogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgwNiIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgxOSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIzNzIuMDQ3MjQgOiAzNTAuNzg3MzkgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNzQ0LjA5NDQ4IDogNTI2LjE4MTA5IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MjYuMTgxMDkgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjc3NyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSI3NSA6IDQwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjE1MCA6IDYwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA2MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUzMjc1IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjUwIDogMzMuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEwMCA6IDUwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmU1NTMzIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjMyIDogMjEuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjY0IDogMzIgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDMyIDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI1NTciCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMjUgOiAxNi42NjY2NjcgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNTAgOiAyNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMjUgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICA8L2RlZnM+CiAgPHNvZGlwb2RpOm5hbWVkdmlldwogICAgIGlkPSJiYXNlIgogICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIKICAgICBib3JkZXJjb2xvcj0iIzY2NjY2NiIKICAgICBib3JkZXJvcGFjaXR5PSIxLjAiCiAgICAgaW5rc2NhcGU6cGFnZW9wYWNpdHk9IjAuMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOnpvb209IjEiCiAgICAgaW5rc2NhcGU6Y3g9Ijc4LjY3NzY0NCIKICAgICBpbmtzY2FwZTpjeT0iMjIuMTAyMzQ0IgogICAgIGlua3NjYXBlOmRvY3VtZW50LXVuaXRzPSJweCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJsYXllcjEiCiAgICAgc2hvd2dyaWQ9InRydWUiCiAgICAgaW5rc2NhcGU6Z3JpZC1iYm94PSJ0cnVlIgogICAgIGlua3NjYXBlOmdyaWQtcG9pbnRzPSJ0cnVlIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwMDAwIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTM5OSIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI4NzQiCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjM3IgogICAgIGlua3NjYXBlOndpbmRvdy15PSItNCIKICAgICBpbmtzY2FwZTpzbmFwLWJib3g9InRydWUiPgogICAgPGlua3NjYXBlOmdyaWQKICAgICAgIGlkPSJHcmlkRnJvbVByZTA0NlNldHRpbmdzIgogICAgICAgdHlwZT0ieHlncmlkIgogICAgICAgb3JpZ2lueD0iMHB4IgogICAgICAgb3JpZ2lueT0iMHB4IgogICAgICAgc3BhY2luZ3g9IjFweCIKICAgICAgIHNwYWNpbmd5PSIxcHgiCiAgICAgICBjb2xvcj0iIzAwMDBmZiIKICAgICAgIGVtcGNvbG9yPSIjMDAwMGZmIgogICAgICAgb3BhY2l0eT0iMC4yIgogICAgICAgZW1wb3BhY2l0eT0iMC40IgogICAgICAgZW1wc3BhY2luZz0iNSIKICAgICAgIHZpc2libGU9InRydWUiCiAgICAgICBlbmFibGVkPSJ0cnVlIiAvPgogIDwvc29kaXBvZGk6bmFtZWR2aWV3PgogIDxtZXRhZGF0YQogICAgIGlkPSJtZXRhZGF0YTciPgogICAgPHJkZjpSREY+CiAgICAgIDxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj4KICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4KICAgICAgICA8ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+CiAgICAgIDwvY2M6V29yaz4KICAgIDwvcmRmOlJERj4KICA8L21ldGFkYXRhPgogIDxnCiAgICAgaW5rc2NhcGU6bGFiZWw9IkxheWVyIDEiCiAgICAgaW5rc2NhcGU6Z3JvdXBtb2RlPSJsYXllciIKICAgICBpZD0ibGF5ZXIxIj4KICAgIDxwYXRoCiAgICAgICBzdHlsZT0iZmlsbDpub25lO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICBkPSJNIDc5LDI1IEMgOTksMjUgOTUsMjUgOTUsMjUiCiAgICAgICBpZD0icGF0aDMwNTkiCiAgICAgICBzb2RpcG9kaTpub2RldHlwZXM9ImNjIiAvPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjI7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gMzEsMTUgNSwxNSIKICAgICAgIGlkPSJwYXRoMzA2MSIgLz4KICAgIDxwYXRoCiAgICAgICBzdHlsZT0iZmlsbDpub25lO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoxLjk5OTk5OTg4O3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICBkPSJNIDMyLDM1IDUsMzUiCiAgICAgICBpZD0icGF0aDM5NDQiIC8+CiAgICA8ZwogICAgICAgaWQ9ImcyNTYwIgogICAgICAgaW5rc2NhcGU6bGFiZWw9IkxheWVyIDEiCiAgICAgICB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyNi41LC0zOS41KSI+CiAgICAgIDxwYXRoCiAgICAgICAgIHN0eWxlPSJmaWxsOiMwMDAwMDA7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjM7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgICAgZD0iTSAtMi40MDYyNSw0NC41IEwgLTAuNDA2MjUsNDYuOTM3NSBDIC0wLjQwNjI1LDQ2LjkzNzUgNS4yNSw1My45Mzc1NDkgNS4yNSw2NC41IEMgNS4yNSw3NS4wNjI0NTEgLTAuNDA2MjUsODIuMDYyNSAtMC40MDYyNSw4Mi4wNjI1IEwgLTIuNDA2MjUsODQuNSBMIDAuNzUsODQuNSBMIDE0Ljc1LDg0LjUgQyAxNy4xNTgwNzYsODQuNTAwMDAxIDIyLjQzOTY5OSw4NC41MjQ1MTQgMjguMzc1LDgyLjA5Mzc1IEMgMzQuMzEwMzAxLDc5LjY2Mjk4NiA0MC45MTE1MzYsNzQuNzUwNDg0IDQ2LjA2MjUsNjUuMjE4NzUgTCA0NC43NSw2NC41IEwgNDYuMDYyNSw2My43ODEyNSBDIDM1Ljc1OTM4Nyw0NC43MTU1OSAxOS41MDY1NzQsNDQuNSAxNC43NSw0NC41IEwgMC43NSw0NC41IEwgLTIuNDA2MjUsNDQuNSB6IE0gMy40Njg3NSw0Ny41IEwgMTQuNzUsNDcuNSBDIDE5LjQzNDE3Myw0Ny41IDMzLjAzNjg1LDQ3LjM2OTc5MyA0Mi43MTg3NSw2NC41IEMgMzcuOTUxOTY0LDcyLjkyOTA3NSAzMi4xOTc0NjksNzcuMTgzOTEgMjcsNzkuMzEyNSBDIDIxLjYzOTMzOSw4MS41MDc5MjQgMTcuMTU4MDc1LDgxLjUwMDAwMSAxNC43NSw4MS41IEwgMy41LDgxLjUgQyA1LjM3MzU4ODQsNzguMzkxNTY2IDguMjUsNzIuNDUwNjUgOC4yNSw2NC41IEMgOC4yNSw1Ni41MjY2NDYgNS4zNDE0Njg2LDUwLjU5OTgxNSAzLjQ2ODc1LDQ3LjUgeiIKICAgICAgICAgaWQ9InBhdGg0OTczIgogICAgICAgICBzb2RpcG9kaTpub2RldHlwZXM9ImNjc2NjY2NzY2NjY2NjY2Njc2Njc2MiIC8+CiAgICAgIDxwYXRoCiAgICAgICAgIHNvZGlwb2RpOnR5cGU9ImFyYyIKICAgICAgICAgc3R5bGU9ImZpbGw6bm9uZTtmaWxsLW9wYWNpdHk6MTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MztzdHJva2UtbGluZWpvaW46bWl0ZXI7bWFya2VyOm5vbmU7c3Ryb2tlLW9wYWNpdHk6MTt2aXNpYmlsaXR5OnZpc2libGU7ZGlzcGxheTppbmxpbmU7b3ZlcmZsb3c6dmlzaWJsZTtlbmFibGUtYmFja2dyb3VuZDphY2N1bXVsYXRlIgogICAgICAgICBpZD0icGF0aDI2MDQiCiAgICAgICAgIHNvZGlwb2RpOmN4PSI3NSIKICAgICAgICAgc29kaXBvZGk6Y3k9IjI1IgogICAgICAgICBzb2RpcG9kaTpyeD0iNCIKICAgICAgICAgc29kaXBvZGk6cnk9IjQiCiAgICAgICAgIGQ9Ik0gNzksMjUgQSA0LDQgMCAxIDEgNzEsMjUgQSA0LDQgMCAxIDEgNzksMjUgeiIKICAgICAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI2LjUsMzkuNSkiIC8+CiAgICA8L2c+CiAgPC9nPgo8L3N2Zz4K"}}},joint.shapes.logic.Gate21.prototype.defaults),operation:function(t,e){return!(t||e)}}),joint.shapes.logic.Nand=joint.shapes.logic.Gate21.extend({defaults:joint.util.deepSupplement({type:"logic.Nand",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9Ik5BTkQgQU5TSS5zdmciCiAgIGlua3NjYXBlOm91dHB1dF9leHRlbnNpb249Im9yZy5pbmtzY2FwZS5vdXRwdXQuc3ZnLmlua3NjYXBlIj4KICA8ZGVmcwogICAgIGlkPSJkZWZzNCI+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMTUgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfej0iNTAgOiAxNSA6IDEiCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMjUgOiAxMCA6IDEiCiAgICAgICBpZD0icGVyc3BlY3RpdmUyNzE0IiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDAuNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF96PSIxIDogMC41IDogMSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIwLjUgOiAwLjMzMzMzMzMzIDogMSIKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI4MDYiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI4MTkiCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMzcyLjA0NzI0IDogMzUwLjc4NzM5IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9Ijc0NC4wOTQ0OCA6IDUyNi4xODEwOSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogNTI2LjE4MTA5IDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI3NzciCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iNzUgOiA0MCA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSIxNTAgOiA2MCA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogNjAgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMzI3NSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSI1MCA6IDMzLjMzMzMzMyA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSIxMDAgOiA1MCA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogNTAgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlNTUzMyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIzMiA6IDIxLjMzMzMzMyA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSI2NCA6IDMyIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAzMiA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogIDwvZGVmcz4KICA8c29kaXBvZGk6bmFtZWR2aWV3CiAgICAgaWQ9ImJhc2UiCiAgICAgcGFnZWNvbG9yPSIjZmZmZmZmIgogICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IgogICAgIGJvcmRlcm9wYWNpdHk9IjEuMCIKICAgICBpbmtzY2FwZTpwYWdlb3BhY2l0eT0iMC4wIgogICAgIGlua3NjYXBlOnBhZ2VzaGFkb3c9IjIiCiAgICAgaW5rc2NhcGU6em9vbT0iMTYiCiAgICAgaW5rc2NhcGU6Y3g9Ijc4LjI4MzMwNyIKICAgICBpbmtzY2FwZTpjeT0iMTYuNDQyODQzIgogICAgIGlua3NjYXBlOmRvY3VtZW50LXVuaXRzPSJweCIKICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJsYXllcjEiCiAgICAgc2hvd2dyaWQ9InRydWUiCiAgICAgaW5rc2NhcGU6Z3JpZC1iYm94PSJ0cnVlIgogICAgIGlua3NjYXBlOmdyaWQtcG9pbnRzPSJ0cnVlIgogICAgIGdyaWR0b2xlcmFuY2U9IjEwMDAwIgogICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTM5OSIKICAgICBpbmtzY2FwZTp3aW5kb3ctaGVpZ2h0PSI4NzQiCiAgICAgaW5rc2NhcGU6d2luZG93LXg9IjMzIgogICAgIGlua3NjYXBlOndpbmRvdy15PSIwIgogICAgIGlua3NjYXBlOnNuYXAtYmJveD0idHJ1ZSI+CiAgICA8aW5rc2NhcGU6Z3JpZAogICAgICAgaWQ9IkdyaWRGcm9tUHJlMDQ2U2V0dGluZ3MiCiAgICAgICB0eXBlPSJ4eWdyaWQiCiAgICAgICBvcmlnaW54PSIwcHgiCiAgICAgICBvcmlnaW55PSIwcHgiCiAgICAgICBzcGFjaW5neD0iMXB4IgogICAgICAgc3BhY2luZ3k9IjFweCIKICAgICAgIGNvbG9yPSIjMDAwMGZmIgogICAgICAgZW1wY29sb3I9IiMwMDAwZmYiCiAgICAgICBvcGFjaXR5PSIwLjIiCiAgICAgICBlbXBvcGFjaXR5PSIwLjQiCiAgICAgICBlbXBzcGFjaW5nPSI1IgogICAgICAgdmlzaWJsZT0idHJ1ZSIKICAgICAgIGVuYWJsZWQ9InRydWUiIC8+CiAgPC9zb2RpcG9kaTpuYW1lZHZpZXc+CiAgPG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhNyI+CiAgICA8cmRmOlJERj4KICAgICAgPGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPgogICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PgogICAgICAgIDxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz4KICAgICAgPC9jYzpXb3JrPgogICAgPC9yZGY6UkRGPgogIDwvbWV0YWRhdGE+CiAgPGcKICAgICBpbmtzY2FwZTpsYWJlbD0iTGF5ZXIgMSIKICAgICBpbmtzY2FwZTpncm91cG1vZGU9ImxheWVyIgogICAgIGlkPSJsYXllcjEiPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjI7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gNzksMjUgQyA5MS44LDI1IDk1LDI1IDk1LDI1IgogICAgICAgaWQ9InBhdGgzMDU5IgogICAgICAgc29kaXBvZGk6bm9kZXR5cGVzPSJjYyIgLz4KICAgIDxwYXRoCiAgICAgICBzdHlsZT0iZmlsbDpub25lO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICBkPSJNIDMxLDE1IDUsMTUiCiAgICAgICBpZD0icGF0aDMwNjEiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MS45OTk5OTk4ODtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgZD0iTSAzMiwzNSA1LDM1IgogICAgICAgaWQ9InBhdGgzOTQ0IiAvPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmb250LXNpemU6bWVkaXVtO2ZvbnQtc3R5bGU6bm9ybWFsO2ZvbnQtdmFyaWFudDpub3JtYWw7Zm9udC13ZWlnaHQ6bm9ybWFsO2ZvbnQtc3RyZXRjaDpub3JtYWw7dGV4dC1pbmRlbnQ6MDt0ZXh0LWFsaWduOnN0YXJ0O3RleHQtZGVjb3JhdGlvbjpub25lO2xpbmUtaGVpZ2h0Om5vcm1hbDtsZXR0ZXItc3BhY2luZzpub3JtYWw7d29yZC1zcGFjaW5nOm5vcm1hbDt0ZXh0LXRyYW5zZm9ybTpub25lO2RpcmVjdGlvbjpsdHI7YmxvY2stcHJvZ3Jlc3Npb246dGI7d3JpdGluZy1tb2RlOmxyLXRiO3RleHQtYW5jaG9yOnN0YXJ0O2ZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MzttYXJrZXI6bm9uZTt2aXNpYmlsaXR5OnZpc2libGU7ZGlzcGxheTppbmxpbmU7b3ZlcmZsb3c6dmlzaWJsZTtlbmFibGUtYmFja2dyb3VuZDphY2N1bXVsYXRlO2ZvbnQtZmFtaWx5OkJpdHN0cmVhbSBWZXJhIFNhbnM7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjpCaXRzdHJlYW0gVmVyYSBTYW5zIgogICAgICAgZD0iTSAzMCw1IEwgMzAsNi40Mjg1NzE0IEwgMzAsNDMuNTcxNDI5IEwgMzAsNDUgTCAzMS40Mjg1NzEsNDUgTCA1MC40NzYxOSw0NSBDIDYxLjc0NDA5OCw0NSA3MC40NzYxOSwzNS45OTk5NTUgNzAuNDc2MTksMjUgQyA3MC40NzYxOSwxNC4wMDAwNDUgNjEuNzQ0MDk5LDUuMDAwMDAwMiA1MC40NzYxOSw1IEMgNTAuNDc2MTksNSA1MC40NzYxOSw1IDMxLjQyODU3MSw1IEwgMzAsNSB6IE0gMzIuODU3MTQzLDcuODU3MTQyOSBDIDQwLjgzNDI2NCw3Ljg1NzE0MjkgNDUuOTE4MzY4LDcuODU3MTQyOSA0OC4wOTUyMzgsNy44NTcxNDI5IEMgNDkuMjg1NzE0LDcuODU3MTQyOSA0OS44ODA5NTIsNy44NTcxNDI5IDUwLjE3ODU3MSw3Ljg1NzE0MjkgQyA1MC4zMjczODEsNy44NTcxNDI5IDUwLjQwOTIyNyw3Ljg1NzE0MjkgNTAuNDQ2NDI5LDcuODU3MTQyOSBDIDUwLjQ2NTAyOSw3Ljg1NzE0MjkgNTAuNDcxNTQzLDcuODU3MTQyOSA1MC40NzYxOSw3Ljg1NzE0MjkgQyA2MC4yMzY4NTMsNy44NTcxNDMgNjcuMTQyODU3LDE1LjQ5NzA5OCA2Ny4xNDI4NTcsMjUgQyA2Ny4xNDI4NTcsMzQuNTAyOTAyIDU5Ljc2MDY2Miw0Mi4xNDI4NTcgNTAsNDIuMTQyODU3IEwgMzIuODU3MTQzLDQyLjE0Mjg1NyBMIDMyLjg1NzE0Myw3Ljg1NzE0MjkgeiIKICAgICAgIGlkPSJwYXRoMjg4NCIKICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2NjY2Njc2NjY2Nzc3Nzc2NjYyIgLz4KICAgIDxwYXRoCiAgICAgICBzb2RpcG9kaTp0eXBlPSJhcmMiCiAgICAgICBzdHlsZT0iZmlsbDpub25lO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDozO3N0cm9rZS1saW5lam9pbjptaXRlcjttYXJrZXI6bm9uZTtzdHJva2Utb3BhY2l0eToxO3Zpc2liaWxpdHk6dmlzaWJsZTtkaXNwbGF5OmlubGluZTtvdmVyZmxvdzp2aXNpYmxlO2VuYWJsZS1iYWNrZ3JvdW5kOmFjY3VtdWxhdGUiCiAgICAgICBpZD0icGF0aDQwMDgiCiAgICAgICBzb2RpcG9kaTpjeD0iNzUiCiAgICAgICBzb2RpcG9kaTpjeT0iMjUiCiAgICAgICBzb2RpcG9kaTpyeD0iNCIKICAgICAgIHNvZGlwb2RpOnJ5PSI0IgogICAgICAgZD0iTSA3OSwyNSBBIDQsNCAwIDEgMSA3MSwyNSBBIDQsNCAwIDEgMSA3OSwyNSB6IiAvPgogIDwvZz4KPC9zdmc+Cg=="}}},joint.shapes.logic.Gate21.prototype.defaults),operation:function(t,e){return!(t&&e)
+}}),joint.shapes.logic.Xor=joint.shapes.logic.Gate21.extend({defaults:joint.util.deepSupplement({type:"logic.Xor",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9IlhPUiBBTlNJLnN2ZyIKICAgaW5rc2NhcGU6b3V0cHV0X2V4dGVuc2lvbj0ib3JnLmlua3NjYXBlLm91dHB1dC5zdmcuaW5rc2NhcGUiPgogIDxkZWZzCiAgICAgaWQ9ImRlZnM0Ij4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAxNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF96PSI1MCA6IDE1IDogMSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIyNSA6IDEwIDogMSIKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI3MTQiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMC41IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEgOiAwLjUgOiAxIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjAuNSA6IDAuMzMzMzMzMzMgOiAxIgogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgwNiIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjgxOSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIzNzIuMDQ3MjQgOiAzNTAuNzg3MzkgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNzQ0LjA5NDQ4IDogNTI2LjE4MTA5IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MjYuMTgxMDkgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMjc3NyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSI3NSA6IDQwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjE1MCA6IDYwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA2MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUzMjc1IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjUwIDogMzMuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjEwMCA6IDUwIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiA1MCA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmU1NTMzIgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjMyIDogMjEuMzMzMzMzIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjY0IDogMzIgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDMyIDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI1NTciCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMjUgOiAxNi42NjY2NjcgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfej0iNTAgOiAyNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMjUgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICA8L2RlZnM+CiAgPHNvZGlwb2RpOm5hbWVkdmlldwogICAgIGlkPSJiYXNlIgogICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIKICAgICBib3JkZXJjb2xvcj0iIzY2NjY2NiIKICAgICBib3JkZXJvcGFjaXR5PSIxLjAiCiAgICAgaW5rc2NhcGU6cGFnZW9wYWNpdHk9IjAuMCIKICAgICBpbmtzY2FwZTpwYWdlc2hhZG93PSIyIgogICAgIGlua3NjYXBlOnpvb209IjUuNjU2ODU0MiIKICAgICBpbmtzY2FwZTpjeD0iMjUuOTM4MTE2IgogICAgIGlua3NjYXBlOmN5PSIxNy4yMzAwNSIKICAgICBpbmtzY2FwZTpkb2N1bWVudC11bml0cz0icHgiCiAgICAgaW5rc2NhcGU6Y3VycmVudC1sYXllcj0ibGF5ZXIxIgogICAgIHNob3dncmlkPSJ0cnVlIgogICAgIGlua3NjYXBlOmdyaWQtYmJveD0idHJ1ZSIKICAgICBpbmtzY2FwZTpncmlkLXBvaW50cz0idHJ1ZSIKICAgICBncmlkdG9sZXJhbmNlPSIxMDAwMCIKICAgICBpbmtzY2FwZTp3aW5kb3ctd2lkdGg9IjEzOTkiCiAgICAgaW5rc2NhcGU6d2luZG93LWhlaWdodD0iODc0IgogICAgIGlua3NjYXBlOndpbmRvdy14PSIzMyIKICAgICBpbmtzY2FwZTp3aW5kb3cteT0iMCIKICAgICBpbmtzY2FwZTpzbmFwLWJib3g9InRydWUiPgogICAgPGlua3NjYXBlOmdyaWQKICAgICAgIGlkPSJHcmlkRnJvbVByZTA0NlNldHRpbmdzIgogICAgICAgdHlwZT0ieHlncmlkIgogICAgICAgb3JpZ2lueD0iMHB4IgogICAgICAgb3JpZ2lueT0iMHB4IgogICAgICAgc3BhY2luZ3g9IjFweCIKICAgICAgIHNwYWNpbmd5PSIxcHgiCiAgICAgICBjb2xvcj0iIzAwMDBmZiIKICAgICAgIGVtcGNvbG9yPSIjMDAwMGZmIgogICAgICAgb3BhY2l0eT0iMC4yIgogICAgICAgZW1wb3BhY2l0eT0iMC40IgogICAgICAgZW1wc3BhY2luZz0iNSIKICAgICAgIHZpc2libGU9InRydWUiCiAgICAgICBlbmFibGVkPSJ0cnVlIiAvPgogIDwvc29kaXBvZGk6bmFtZWR2aWV3PgogIDxtZXRhZGF0YQogICAgIGlkPSJtZXRhZGF0YTciPgogICAgPHJkZjpSREY+CiAgICAgIDxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj4KICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4KICAgICAgICA8ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+CiAgICAgIDwvY2M6V29yaz4KICAgIDwvcmRmOlJERj4KICA8L21ldGFkYXRhPgogIDxnCiAgICAgaW5rc2NhcGU6bGFiZWw9IkxheWVyIDEiCiAgICAgaW5rc2NhcGU6Z3JvdXBtb2RlPSJsYXllciIKICAgICBpZD0ibGF5ZXIxIj4KICAgIDxwYXRoCiAgICAgICBzdHlsZT0iZmlsbDpub25lO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoyO3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICBkPSJtIDcwLDI1IGMgMjAsMCAyNSwwIDI1LDAiCiAgICAgICBpZD0icGF0aDMwNTkiCiAgICAgICBzb2RpcG9kaTpub2RldHlwZXM9ImNjIiAvPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjEuOTk5OTk5ODg7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gMzAuMzg1NzE3LDE1IEwgNC45OTk5OTk4LDE1IgogICAgICAgaWQ9InBhdGgzMDYxIiAvPgogICAgPHBhdGgKICAgICAgIHN0eWxlPSJmaWxsOm5vbmU7c3Ryb2tlOiMwMDAwMDA7c3Ryb2tlLXdpZHRoOjEuOTk5OTk5NzY7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgIGQ9Ik0gMzEuMzYyMDkxLDM1IEwgNC45OTk5OTk4LDM1IgogICAgICAgaWQ9InBhdGgzOTQ0IiAvPgogICAgPGcKICAgICAgIGlkPSJnMjU2MCIKICAgICAgIGlua3NjYXBlOmxhYmVsPSJMYXllciAxIgogICAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjYuNSwtMzkuNSkiPgogICAgICA8cGF0aAogICAgICAgICBpZD0icGF0aDM1MTYiCiAgICAgICAgIHN0eWxlPSJmaWxsOiMwMDAwMDA7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjM7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgICAgZD0iTSAtMi4yNSw4MS41MDAwMDUgQyAtMy44NDczNzQsODQuMTQ0NDA1IC00LjUsODQuNTAwMDA1IC00LjUsODQuNTAwMDA1IEwgLTguMTU2MjUsODQuNTAwMDA1IEwgLTYuMTU2MjUsODIuMDYyNTA1IEMgLTYuMTU2MjUsODIuMDYyNTA1IC0wLjUsNzUuMDYyNDUxIC0wLjUsNjQuNSBDIC0wLjUsNTMuOTM3NTQ5IC02LjE1NjI1LDQ2LjkzNzUgLTYuMTU2MjUsNDYuOTM3NSBMIC04LjE1NjI1LDQ0LjUgTCAtNC41LDQ0LjUgQyAtMy43MTg3NSw0NS40Mzc1IC0zLjA3ODEyNSw0Ni4xNTYyNSAtMi4yODEyNSw0Ny41IEMgLTAuNDA4NTMxLDUwLjU5OTgxNSAyLjUsNTYuNTI2NjQ2IDIuNSw2NC41IEMgMi41LDcyLjQ1MDY1IC0wLjM5NjY5Nyw3OC4zNzk0MjUgLTIuMjUsODEuNTAwMDA1IHoiCiAgICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2NjY3NjY2Njc2MiIC8+CiAgICAgIDxwYXRoCiAgICAgICAgIHN0eWxlPSJmaWxsOiMwMDAwMDA7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjM7c3Ryb2tlLWxpbmVjYXA6YnV0dDtzdHJva2UtbGluZWpvaW46bWl0ZXI7c3Ryb2tlLW9wYWNpdHk6MSIKICAgICAgICAgZD0iTSAtMi40MDYyNSw0NC41IEwgLTAuNDA2MjUsNDYuOTM3NSBDIC0wLjQwNjI1LDQ2LjkzNzUgNS4yNSw1My45Mzc1NDkgNS4yNSw2NC41IEMgNS4yNSw3NS4wNjI0NTEgLTAuNDA2MjUsODIuMDYyNSAtMC40MDYyNSw4Mi4wNjI1IEwgLTIuNDA2MjUsODQuNSBMIDAuNzUsODQuNSBMIDE0Ljc1LDg0LjUgQyAxNy4xNTgwNzYsODQuNTAwMDAxIDIyLjQzOTY5OSw4NC41MjQ1MTQgMjguMzc1LDgyLjA5Mzc1IEMgMzQuMzEwMzAxLDc5LjY2Mjk4NiA0MC45MTE1MzYsNzQuNzUwNDg0IDQ2LjA2MjUsNjUuMjE4NzUgTCA0NC43NSw2NC41IEwgNDYuMDYyNSw2My43ODEyNSBDIDM1Ljc1OTM4Nyw0NC43MTU1OSAxOS41MDY1NzQsNDQuNSAxNC43NSw0NC41IEwgMC43NSw0NC41IEwgLTIuNDA2MjUsNDQuNSB6IE0gMy40Njg3NSw0Ny41IEwgMTQuNzUsNDcuNSBDIDE5LjQzNDE3Myw0Ny41IDMzLjAzNjg1LDQ3LjM2OTc5MyA0Mi43MTg3NSw2NC41IEMgMzcuOTUxOTY0LDcyLjkyOTA3NSAzMi4xOTc0NjksNzcuMTgzOTEgMjcsNzkuMzEyNSBDIDIxLjYzOTMzOSw4MS41MDc5MjQgMTcuMTU4MDc1LDgxLjUwMDAwMSAxNC43NSw4MS41IEwgMy41LDgxLjUgQyA1LjM3MzU4ODQsNzguMzkxNTY2IDguMjUsNzIuNDUwNjUgOC4yNSw2NC41IEMgOC4yNSw1Ni41MjY2NDYgNS4zNDE0Njg2LDUwLjU5OTgxNSAzLjQ2ODc1LDQ3LjUgeiIKICAgICAgICAgaWQ9InBhdGg0OTczIgogICAgICAgICBzb2RpcG9kaTpub2RldHlwZXM9ImNjc2NjY2NzY2NjY2NjY2Njc2Njc2MiIC8+CiAgICA8L2c+CiAgPC9nPgo8L3N2Zz4K"}}},joint.shapes.logic.Gate21.prototype.defaults),operation:function(t,e){return!(t&&!e||!t&&e)}}),joint.shapes.logic.Xnor=joint.shapes.logic.Gate21.extend({defaults:joint.util.deepSupplement({type:"logic.Xnor",attrs:{image:{"xlink:href":"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgo8c3ZnCiAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIKICAgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiCiAgIHdpZHRoPSIxMDAiCiAgIGhlaWdodD0iNTAiCiAgIGlkPSJzdmcyIgogICBzb2RpcG9kaTp2ZXJzaW9uPSIwLjMyIgogICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjQ2IgogICB2ZXJzaW9uPSIxLjAiCiAgIHNvZGlwb2RpOmRvY25hbWU9IlhOT1IgQU5TSS5zdmciCiAgIGlua3NjYXBlOm91dHB1dF9leHRlbnNpb249Im9yZy5pbmtzY2FwZS5vdXRwdXQuc3ZnLmlua3NjYXBlIj4KICA8ZGVmcwogICAgIGlkPSJkZWZzNCI+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogMTUgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfej0iNTAgOiAxNSA6IDEiCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMjUgOiAxMCA6IDEiCiAgICAgICBpZD0icGVyc3BlY3RpdmUyNzE0IiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDAuNSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF96PSIxIDogMC41IDogMSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIwLjUgOiAwLjMzMzMzMzMzIDogMSIKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI4MDYiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI4MTkiCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iMzcyLjA0NzI0IDogMzUwLjc4NzM5IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9Ijc0NC4wOTQ0OCA6IDUyNi4xODEwOSA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogNTI2LjE4MTA5IDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgICA8aW5rc2NhcGU6cGVyc3BlY3RpdmUKICAgICAgIGlkPSJwZXJzcGVjdGl2ZTI3NzciCiAgICAgICBpbmtzY2FwZTpwZXJzcDNkLW9yaWdpbj0iNzUgOiA0MCA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSIxNTAgOiA2MCA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogNjAgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlMzI3NSIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSI1MCA6IDMzLjMzMzMzMyA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSIxMDAgOiA1MCA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF95PSIwIDogMTAwMCA6IDAiCiAgICAgICBpbmtzY2FwZTp2cF94PSIwIDogNTAgOiAxIgogICAgICAgc29kaXBvZGk6dHlwZT0iaW5rc2NhcGU6cGVyc3AzZCIgLz4KICAgIDxpbmtzY2FwZTpwZXJzcGVjdGl2ZQogICAgICAgaWQ9InBlcnNwZWN0aXZlNTUzMyIKICAgICAgIGlua3NjYXBlOnBlcnNwM2Qtb3JpZ2luPSIzMiA6IDIxLjMzMzMzMyA6IDEiCiAgICAgICBpbmtzY2FwZTp2cF96PSI2NCA6IDMyIDogMSIKICAgICAgIGlua3NjYXBlOnZwX3k9IjAgOiAxMDAwIDogMCIKICAgICAgIGlua3NjYXBlOnZwX3g9IjAgOiAzMiA6IDEiCiAgICAgICBzb2RpcG9kaTp0eXBlPSJpbmtzY2FwZTpwZXJzcDNkIiAvPgogICAgPGlua3NjYXBlOnBlcnNwZWN0aXZlCiAgICAgICBpZD0icGVyc3BlY3RpdmUyNTU3IgogICAgICAgaW5rc2NhcGU6cGVyc3AzZC1vcmlnaW49IjI1IDogMTYuNjY2NjY3IDogMSIKICAgICAgIGlua3NjYXBlOnZwX3o9IjUwIDogMjUgOiAxIgogICAgICAgaW5rc2NhcGU6dnBfeT0iMCA6IDEwMDAgOiAwIgogICAgICAgaW5rc2NhcGU6dnBfeD0iMCA6IDI1IDogMSIKICAgICAgIHNvZGlwb2RpOnR5cGU9Imlua3NjYXBlOnBlcnNwM2QiIC8+CiAgPC9kZWZzPgogIDxzb2RpcG9kaTpuYW1lZHZpZXcKICAgICBpZD0iYmFzZSIKICAgICBwYWdlY29sb3I9IiNmZmZmZmYiCiAgICAgYm9yZGVyY29sb3I9IiM2NjY2NjYiCiAgICAgYm9yZGVyb3BhY2l0eT0iMS4wIgogICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwLjAiCiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIKICAgICBpbmtzY2FwZTp6b29tPSI0IgogICAgIGlua3NjYXBlOmN4PSI5NS43MjM2NiIKICAgICBpbmtzY2FwZTpjeT0iLTI2Ljc3NTAyMyIKICAgICBpbmtzY2FwZTpkb2N1bWVudC11bml0cz0icHgiCiAgICAgaW5rc2NhcGU6Y3VycmVudC1sYXllcj0ibGF5ZXIxIgogICAgIHNob3dncmlkPSJ0cnVlIgogICAgIGlua3NjYXBlOmdyaWQtYmJveD0idHJ1ZSIKICAgICBpbmtzY2FwZTpncmlkLXBvaW50cz0idHJ1ZSIKICAgICBncmlkdG9sZXJhbmNlPSIxMDAwMCIKICAgICBpbmtzY2FwZTp3aW5kb3ctd2lkdGg9IjEzOTkiCiAgICAgaW5rc2NhcGU6d2luZG93LWhlaWdodD0iODc0IgogICAgIGlua3NjYXBlOndpbmRvdy14PSIzMyIKICAgICBpbmtzY2FwZTp3aW5kb3cteT0iMCIKICAgICBpbmtzY2FwZTpzbmFwLWJib3g9InRydWUiPgogICAgPGlua3NjYXBlOmdyaWQKICAgICAgIGlkPSJHcmlkRnJvbVByZTA0NlNldHRpbmdzIgogICAgICAgdHlwZT0ieHlncmlkIgogICAgICAgb3JpZ2lueD0iMHB4IgogICAgICAgb3JpZ2lueT0iMHB4IgogICAgICAgc3BhY2luZ3g9IjFweCIKICAgICAgIHNwYWNpbmd5PSIxcHgiCiAgICAgICBjb2xvcj0iIzAwMDBmZiIKICAgICAgIGVtcGNvbG9yPSIjMDAwMGZmIgogICAgICAgb3BhY2l0eT0iMC4yIgogICAgICAgZW1wb3BhY2l0eT0iMC40IgogICAgICAgZW1wc3BhY2luZz0iNSIKICAgICAgIHZpc2libGU9InRydWUiCiAgICAgICBlbmFibGVkPSJ0cnVlIiAvPgogIDwvc29kaXBvZGk6bmFtZWR2aWV3PgogIDxtZXRhZGF0YQogICAgIGlkPSJtZXRhZGF0YTciPgogICAgPHJkZjpSREY+CiAgICAgIDxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj4KICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4KICAgICAgICA8ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+CiAgICAgIDwvY2M6V29yaz4KICAgIDwvcmRmOlJERj4KICA8L21ldGFkYXRhPgogIDxnCiAgICAgaW5rc2NhcGU6bGFiZWw9IkxheWVyIDEiCiAgICAgaW5rc2NhcGU6Z3JvdXBtb2RlPSJsYXllciIKICAgICBpZD0ibGF5ZXIxIj4KICAgIDxwYXRoCiAgICAgICBzdHlsZT0iZmlsbDpub25lO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoyLjAwMDAwMDI0O3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICBkPSJNIDc4LjMzMzMzMiwyNSBDIDkxLjY2NjY2NiwyNSA5NSwyNSA5NSwyNSIKICAgICAgIGlkPSJwYXRoMzA1OSIKICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2MiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MS45OTk5OTk4ODtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgZD0iTSAzMC4zODU3MTcsMTUgTCA0Ljk5OTk5OTgsMTUiCiAgICAgICBpZD0icGF0aDMwNjEiIC8+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MS45OTk5OTk3NjtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgZD0iTSAzMS4zNjIwOTEsMzUgTCA0Ljk5OTk5OTgsMzUiCiAgICAgICBpZD0icGF0aDM5NDQiIC8+CiAgICA8ZwogICAgICAgaWQ9ImcyNTYwIgogICAgICAgaW5rc2NhcGU6bGFiZWw9IkxheWVyIDEiCiAgICAgICB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyNi41LC0zOS41KSI+CiAgICAgIDxwYXRoCiAgICAgICAgIGlkPSJwYXRoMzUxNiIKICAgICAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MztzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgICBkPSJNIC0yLjI1LDgxLjUwMDAwNSBDIC0zLjg0NzM3NCw4NC4xNDQ0MDUgLTQuNSw4NC41MDAwMDUgLTQuNSw4NC41MDAwMDUgTCAtOC4xNTYyNSw4NC41MDAwMDUgTCAtNi4xNTYyNSw4Mi4wNjI1MDUgQyAtNi4xNTYyNSw4Mi4wNjI1MDUgLTAuNSw3NS4wNjI0NTEgLTAuNSw2NC41IEMgLTAuNSw1My45Mzc1NDkgLTYuMTU2MjUsNDYuOTM3NSAtNi4xNTYyNSw0Ni45Mzc1IEwgLTguMTU2MjUsNDQuNSBMIC00LjUsNDQuNSBDIC0zLjcxODc1LDQ1LjQzNzUgLTMuMDc4MTI1LDQ2LjE1NjI1IC0yLjI4MTI1LDQ3LjUgQyAtMC40MDg1MzEsNTAuNTk5ODE1IDIuNSw1Ni41MjY2NDYgMi41LDY0LjUgQyAyLjUsNzIuNDUwNjUgLTAuMzk2Njk3LDc4LjM3OTQyNSAtMi4yNSw4MS41MDAwMDUgeiIKICAgICAgICAgc29kaXBvZGk6bm9kZXR5cGVzPSJjY2Njc2NjY2NzYyIgLz4KICAgICAgPHBhdGgKICAgICAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MztzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIgogICAgICAgICBkPSJNIC0yLjQwNjI1LDQ0LjUgTCAtMC40MDYyNSw0Ni45Mzc1IEMgLTAuNDA2MjUsNDYuOTM3NSA1LjI1LDUzLjkzNzU0OSA1LjI1LDY0LjUgQyA1LjI1LDc1LjA2MjQ1MSAtMC40MDYyNSw4Mi4wNjI1IC0wLjQwNjI1LDgyLjA2MjUgTCAtMi40MDYyNSw4NC41IEwgMC43NSw4NC41IEwgMTQuNzUsODQuNSBDIDE3LjE1ODA3Niw4NC41MDAwMDEgMjIuNDM5Njk5LDg0LjUyNDUxNCAyOC4zNzUsODIuMDkzNzUgQyAzNC4zMTAzMDEsNzkuNjYyOTg2IDQwLjkxMTUzNiw3NC43NTA0ODQgNDYuMDYyNSw2NS4yMTg3NSBMIDQ0Ljc1LDY0LjUgTCA0Ni4wNjI1LDYzLjc4MTI1IEMgMzUuNzU5Mzg3LDQ0LjcxNTU5IDE5LjUwNjU3NCw0NC41IDE0Ljc1LDQ0LjUgTCAwLjc1LDQ0LjUgTCAtMi40MDYyNSw0NC41IHogTSAzLjQ2ODc1LDQ3LjUgTCAxNC43NSw0Ny41IEMgMTkuNDM0MTczLDQ3LjUgMzMuMDM2ODUsNDcuMzY5NzkzIDQyLjcxODc1LDY0LjUgQyAzNy45NTE5NjQsNzIuOTI5MDc1IDMyLjE5NzQ2OSw3Ny4xODM5MSAyNyw3OS4zMTI1IEMgMjEuNjM5MzM5LDgxLjUwNzkyNCAxNy4xNTgwNzUsODEuNTAwMDAxIDE0Ljc1LDgxLjUgTCAzLjUsODEuNSBDIDUuMzczNTg4NCw3OC4zOTE1NjYgOC4yNSw3Mi40NTA2NSA4LjI1LDY0LjUgQyA4LjI1LDU2LjUyNjY0NiA1LjM0MTQ2ODYsNTAuNTk5ODE1IDMuNDY4NzUsNDcuNSB6IgogICAgICAgICBpZD0icGF0aDQ5NzMiCiAgICAgICAgIHNvZGlwb2RpOm5vZGV0eXBlcz0iY2NzY2NjY3NjY2NjY2NjY2NzY2NzYyIgLz4KICAgIDwvZz4KICAgIDxwYXRoCiAgICAgICBzb2RpcG9kaTp0eXBlPSJhcmMiCiAgICAgICBzdHlsZT0iZmlsbDpub25lO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDozO3N0cm9rZS1saW5lam9pbjptaXRlcjttYXJrZXI6bm9uZTtzdHJva2Utb3BhY2l0eToxO3Zpc2liaWxpdHk6dmlzaWJsZTtkaXNwbGF5OmlubGluZTtvdmVyZmxvdzp2aXNpYmxlO2VuYWJsZS1iYWNrZ3JvdW5kOmFjY3VtdWxhdGUiCiAgICAgICBpZD0icGF0aDM1NTEiCiAgICAgICBzb2RpcG9kaTpjeD0iNzUiCiAgICAgICBzb2RpcG9kaTpjeT0iMjUiCiAgICAgICBzb2RpcG9kaTpyeD0iNCIKICAgICAgIHNvZGlwb2RpOnJ5PSI0IgogICAgICAgZD0iTSA3OSwyNSBBIDQsNCAwIDEgMSA3MSwyNSBBIDQsNCAwIDEgMSA3OSwyNSB6IiAvPgogIDwvZz4KPC9zdmc+Cg=="}}},joint.shapes.logic.Gate21.prototype.defaults),operation:function(t,e){return!(t&&e||!t&&!e)}}),joint.shapes.logic.Wire=joint.dia.Link.extend({arrowheadMarkup:['<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">','<circle class="marker-arrowhead" end="<%= end %>" r="7"/>',"</g>"].join(""),vertexMarkup:['<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">','<circle class="marker-vertex" idx="<%= idx %>" r="10" />','<g class="marker-vertex-remove-group">','<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>','<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',"<title>Remove vertex.</title>","</path>","</g>","</g>"].join(""),defaults:joint.util.deepSupplement({type:"logic.Wire",attrs:{".connection":{"stroke-width":2},".marker-vertex":{r:7}},router:{name:"orthogonal"},connector:{name:"rounded",args:{radius:10}}},joint.dia.Link.prototype.defaults)}),"object"==typeof exports&&(module.exports=joint.shapes.logic),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{},dia:{Element:require("../src/joint.dia.element").Element}},_=require("lodash");if(joint.shapes.chart={},joint.shapes.chart.Plot=joint.shapes.basic.Generic.extend({markup:['<clipPath class="clip"><rect/></clipPath>','<g class="rotatable">','<g class="scalable"></g>','<g class="background"><rect/><text/></g>','<g class="axis">','<g class="y-axis"><path/><g class="ticks"></g></g>','<g class="x-axis"><path/><g class="ticks"></g></g>','<g class="markings"></g>',"</g>",'<g class="data"><g class="series"></g></g>','<g class="foreground">','<rect/><text class="caption"/><text class="subcaption"/>','<g class="legend"><g class="legend-items"></g></g>','<line class="guideline x-guideline" /><line class="guideline y-guideline" />',"</g>","</g>"].join(""),tickMarkup:'<g class="tick"><line/><text/></g>',pointMarkup:'<g class="point"><circle/><text/></g>',barMarkup:'<path class="bar"/>',markingMarkup:'<g class="marking"><rect/><text/></g>',serieMarkup:'<g><clipPath class="serie-clip"><rect/></clipPath><path/><g class="bars"></g><g class="points"></g></g>',legendItemMarkup:'<g class="legend-item"><circle/><text/></g>',defaults:joint.util.deepSupplement({type:"chart.Plot",attrs:{".data path":{fill:"none",stroke:"black"},".data .bars rect":{fill:"none",stroke:"black"},".background rect":{fill:"white",stroke:"#e5e5e5",opacity:1},".background text":{fill:"black",text:"No data available.",ref:".","ref-x":.5,"ref-y":.5,"text-anchor":"middle","y-alignment":"middle",display:"none"},".foreground > rect":{fill:"white",stroke:"#e5e5e5",opacity:0,"pointer-events":"none"},".foreground .caption":{fill:"black",text:"",ref:".foreground > rect","ref-x":.5,"ref-y":10,"text-anchor":"middle","y-alignment":"middle","font-size":14},".foreground .subcaption":{fill:"black",text:"",ref:".foreground > rect","ref-x":.5,"ref-y":23,"text-anchor":"middle","y-alignment":"middle","font-size":10},".point":{display:"inline-block"},".point circle":{r:2,stroke:"black",fill:"black",opacity:.3},".point text":{fill:"black","font-size":8,"text-anchor":"middle",display:"none"},".axis path":{fill:"none",stroke:"black"},".axis .tick":{fill:"none",stroke:"black"},".y-axis .tick line":{fill:"none",stroke:"black",x2:2,y2:0,opacity:1},".x-axis .tick line":{fill:"none",stroke:"black",x2:0,y2:-3,opacity:1},".y-axis .tick text":{fill:"black",stroke:"none","font-size":10,dy:"-.5em",x:-5,"text-anchor":"end"},".x-axis .tick text":{fill:"black",stroke:"none","font-size":10,dy:".5em",x:0,"text-anchor":"middle"},".axis .markings":{fill:"black",stroke:"none","fill-opacity":1},".axis .markings text":{fill:"black","text-anchor":"end","font-size":10,dy:-5,dx:-5},".guideline":{"pointer-events":"none",display:"none"},".x-guideline":{stroke:"black",visibility:"hidden"},".y-guideline":{stroke:"black",visibility:"hidden"},".legend":{ref:".background","ref-x":10,"ref-y":10},".legend-item text":{fill:"black",transform:"translate(14, 0)","font-size":11},".legend-item circle":{r:5,transform:"translate(5,5)"},".legend-item":{cursor:"pointer"},".legend-item.disabled circle":{fill:"gray"},".legend-item.disabled text":{opacity:.5}}},joint.shapes.basic.Generic.prototype.defaults),legendPosition:function(t,e){e=e||{},this.trigger("batch:start"),this.removeAttr([".legend/ref-x",".legend/ref-y",".legend/ref-dx",".legend/ref-dy",".legend/x-alignment",".legend/y-alignment"],{silent:!0});var i=e.padding||10,n={n:{".legend":{"ref-x":.5,"x-alignment":-.5,"ref-y":i}},ne:{".legend":{"ref-dx":-i,"x-alignment":-.999,"ref-y":i}},e:{".legend":{"ref-dx":-i,"x-alignment":-.999,"ref-y":.5,"y-alignment":-.5}},se:{".legend":{"ref-dx":-i,"ref-dy":-i,"x-alignment":-.999,"y-alignment":-.999}},s:{".legend":{"ref-x":.5,"ref-dy":-i,"x-alignment":-.5,"y-alignment":-.999}},sw:{".legend":{"ref-x":i,"ref-dy":-i,"y-alignment":-.999}},w:{".legend":{"ref-x":i,"ref-y":.5,"y-alignment":-.5}},nw:{".legend":{"ref-x":i,"ref-y":i}},nnw:{".legend":{"ref-x":i,"ref-y":-i,"y-alignment":-.999}},nn:{".legend":{"ref-x":.5,"ref-y":-i,"x-alignment":-.5,"y-alignment":-.999}},nne:{".legend":{"ref-dx":-i,"ref-y":-i,"x-alignment":-.999,"y-alignment":-.999}},nnee:{".legend":{"ref-dx":i,"ref-y":-i,"y-alignment":-.999}},nee:{".legend":{"ref-y":i,"ref-dx":i}},ee:{".legend":{"ref-dx":i,"ref-y":.5,"y-alignment":-.5}},see:{".legend":{"ref-dx":i,"ref-dy":-i,"y-alignment":-.999}},ssee:{".legend":{"ref-dx":i,"ref-dy":i}},sse:{".legend":{"ref-dx":-i,"ref-dy":i,"x-alignment":-.999}},ss:{".legend":{"ref-x":.5,"ref-dy":i,"x-alignment":-.5}},ssw:{".legend":{"ref-x":i,"ref-dy":i}},ssww:{".legend":{"ref-x":-i,"ref-dy":i,"x-alignment":-.999}},sww:{".legend":{"ref-x":-i,"ref-dy":-i,"x-alignment":-.999,"y-alignment":-.999}},ww:{".legend":{"ref-x":-i,"ref-y":.5,"x-alignment":-.999,"y-alignment":-.5}},nww:{".legend":{"ref-x":-i,"ref-y":i,"x-alignment":-.999}},nnww:{".legend":{"ref-x":-i,"ref-y":-i,"x-alignment":-.999,"y-alignment":-.999}}};n[t]&&this.attr(n[t]),this.trigger("batch:stop")},addPoint:function(t,e,i){i=i||{};var n=this.get("series"),r=_.findIndex(n,{name:e});if(-1===r)throw Error("Serie "+e+" was not found.");var a=_.cloneDeep(n[r]);a.data.push(t),_.isFinite(i.maxLen)&&a.data.length>i.maxLen&&a.data.shift(),n=n.slice(),n[r]=a,this.set("series",n,i)},lastPoint:function(t){return _.last(_.findWhere(this.get("series"),{name:t}).data)},firstPoint:function(t){return _.first(_.findWhere(this.get("series"),{name:t}).data)}}),joint.shapes.chart.PlotView=joint.dia.ElementView.extend({events:{mousemove:"onMouseMove",mouseout:"onMouseOut"},initialize:function(){joint.dia.ElementView.prototype.initialize.apply(this,arguments),this.listenTo(this.model,"change:series change:interpolate change:padding change:canvas change:markings change:axis",_.bind(function(){this.update()},this)),this.on("cell:pointerdown",this.onPointerDown,this),this._disabledSeries=[]},renderMarkup:function(){joint.dia.ElementView.prototype.renderMarkup.apply(this,arguments),this.elDataClipPath=this.$(".clip")[0],this.elDataClipPathRect=this.elDataClipPath.firstChild,this.elBackgroundRect=this.$(".background rect")[0],this.elBackgroundText=this.$(".background text")[0],this.elForeground=this.$(".foreground")[0],this.elForegroundRect=this.$(".foreground rect")[0],this.elDataSeries=this.$(".data .series")[0],this.elYAxisPath=this.$(".y-axis path")[0],this.elYAxisTicks=this.$(".y-axis .ticks")[0],this.elXAxisPath=this.$(".x-axis path")[0],this.elXAxisTicks=this.$(".x-axis .ticks")[0],this.elMarkings=this.$(".axis .markings")[0],this.elXGuideline=this.$(".x-guideline")[0],this.elYGuideline=this.$(".y-guideline")[0],this.elLegend=this.$(".legend")[0],this.elLegendItems=this.$(".legend-items")[0],this.elTick=V(this.model.tickMarkup),this.elMarking=V(this.model.markingMarkup),this.elLegendItem=V(this.model.legendItemMarkup),this.elPoint=V(this.model.pointMarkup),this.elBar=V(this.model.barMarkup),this.elSerie=V(this.model.serieMarkup),this.elDataClipPath.id="clip_"+this.cid,V(this.$(".data")[0]).attr("clip-path","url(#"+this.elDataClipPath.id+")"),V(this.elMarkings).attr("clip-path","url(#"+this.elDataClipPath.id+")")},update:function(t){t=this.filterSeries(t),this.calculateStats(t);var e=this.model.get("size"),i=e.width,n=e.height;this.canvas=_.extend({x:0,y:0,width:i,height:n},this.model.get("canvas"));var r,a={top:0,right:0,bottom:0,left:0},s=this.model.get("padding");r=_.isObject(s)?_.extend({},a,s):_.isUndefined(s)?a:{top:s,right:2*s,bottom:2*s,left:s},this.canvas=g.rect(this.canvas).moveAndExpand(g.rect(r.left,r.top,-r.right,-r.bottom));var o={x:0,y:0,width:i,height:n};V(this.elDataClipPathRect).attr(o),V(this.elBackgroundRect).attr(o),V(this.elForegroundRect).attr(o),this.updateAxis(),this.updateMarkings(),this.isEmpty()?$(this.elBackgroundText).show():$(this.elBackgroundText).hide(),this.updateSeries(t),this.updateLegend(),joint.dia.ElementView.prototype.update.apply(this,arguments)},calculateStats:function(t){t=t||this.model.get("series");var e=[],i=[],n={},r={},a={};_.each(t,function(t,s){var o=a[t.name||s]||(a[t.name||s]={});o.decreasingX=!0,o.decreasingY=!0,o.nonDecreasingX=!0,o.nonDecreasingY=!0;var l;_.each(t.data,function(a){o.minX=_.isUndefined(o.minX)?a.x:Math.min(o.minX,a.x),o.maxX=_.isUndefined(o.maxX)?a.x:Math.max(o.maxX,a.x),o.minY=_.isUndefined(o.minY)?a.y:Math.min(o.minY,a.y),o.maxY=_.isUndefined(o.maxY)?a.y:Math.max(o.maxY,a.y),l&&(o.decreasingX=o.decreasingX&&a.x<l.x,o.decreasingY=o.decreasingY&&a.y<l.y,o.nonDecreasingX=o.nonDecreasingX&&a.x>=l.x,o.nonDecreasingY=o.nonDecreasingY&&a.y>=l.y),_.contains(e,a.x)||e.push(a.x),_.contains(i,a.y)||i.push(a.y),(n[a.x]||(n[a.x]=[])).push({serie:t,x:a.x,y:a.y}),(r[a.y]||(r[a.y]=[])).push({serie:t,x:a.x,y:a.y}),l=a})});var s=this.model.get("axis")||{},o=s["x-axis"]||{},l=s["y-axis"]||{};this.stats={minX:_.isUndefined(o.min)?_.min(e):o.min,maxX:_.isUndefined(o.max)?_.max(e):o.max,minY:_.isUndefined(l.min)?_.min(i):l.min,maxY:_.isUndefined(l.max)?_.max(i):l.max,bySerie:a,xValues:e,yValues:i,xMap:n,yMap:r}},isEmpty:function(){return!this.stats.xValues.length},updateSeries:function(t){if(t=t||this.model.get("series"),this.elDataSeries.textContent="",!this.isEmpty()){var e=[this.stats.minX,this.stats.maxX],i=[this.stats.minY,this.stats.maxY],n=[this.canvas.x,this.canvas.x+this.canvas.width],r=[this.canvas.y+this.canvas.height,this.canvas.y],a=this.model.get("attrs");_.each(t,function(t,s){var o=t.data,l=[],c=this.elSerie.clone().attr("class",t.name||"serie-"+s);V(this.elDataSeries).append(c),_.each(o,function(s){var o=g.scale.linear(e,n,s.x),c=g.scale.linear(i,r,s.y);l.push({x:o,y:c}),a[".point"]&&"none"!==a[".point"].display&&this.renderPoint(s,t),t.bars&&this.renderBar(s,t)},this);var h=c.findOne(".serie-clip"),u=this.model.get("size"),p=this.stats.bySerie[t.name||s],d=g.scale.linear(e,n,p.minX),f=g.scale.linear(e,n,p.maxX),m=h.findOne("rect");if(m.attr(g.rect(d,0,f-d,u.height)),!t.bars){var I=c.findOne("path");I.attr({d:this.seriePathData(l,t,s),"clip-path":"url(#"+h.node.id+")"})}},this)}},seriePathClipData:function(t){var e=10,i=this.model.get("size"),n=_.first(t);_.last(t);var r=["M",n.x,n.y,"V",i.height+e];return r.join(" ")},renderBar:function(t,e){var i=[this.stats.minX,this.stats.maxX],n=[this.stats.minY,this.stats.maxY],r=[this.canvas.x,this.canvas.x+this.canvas.width],a=[this.canvas.y+this.canvas.height,this.canvas.y],s=g.scale.linear(i,r,t.x),o=g.scale.linear(n,a,t.y),l=e.bars.barWidth||.8,c=l>1?l:this.canvas.width/(this.stats.maxX-this.stats.minX)*l,h=g.scale.linear(n,a,0)-o,u=t["top-rx"]||e.bars["top-rx"],p=t["top-ry"]||e.bars["top-ry"],d=t["bottom-rx"]||e.bars["bottom-rx"],f=t["bottom-ry"]||e.bars["bottom-ry"],m={left:s,middle:s-c/2,right:s-c}[e.bars.align||"middle"],I=this.elBar.clone();I.attr({"data-serie":e.name,"data-x":t.x,"data-y":t.y,d:V.rectToPath({x:m,y:o,width:c,height:h,"top-rx":u,"top-ry":p,"bottom-rx":d,"bottom-ry":f})});var y=e.name||"serie-"+this.model.get("series").indexOf(e);return V(this.elDataSeries).findOne("."+y+" .bars").append(I),I.node},renderPoint:function(t,e){var i=[this.stats.minX,this.stats.maxX],n=[this.stats.minY,this.stats.maxY],r=[this.canvas.x,this.canvas.x+this.canvas.width],a=[this.canvas.y+this.canvas.height,this.canvas.y],s=g.scale.linear(i,r,t.x),o=g.scale.linear(n,a,t.y),l=this.elPoint.clone();l.attr({"data-serie":e.name,"data-x":t.x,"data-y":t.y}),l.findOne("circle").attr({cx:s,cy:o}),l.findOne("text").attr({x:s,dy:o}).text(this.pointLabel(t,e));var c=e.name||"serie-"+this.model.get("series").indexOf(e);return V(this.elDataSeries).findOne("."+c+" .points").append(l),l.node},seriePathData:function(t,e,i){var n,r,a,s=_.isUndefined(e.interpolate)?this.model.get("interpolate"):e.interpolate,o=t.length;switch(s){case"bezier":n=g.bezier.curveThroughPoints(t);break;case"step":for(a=t[0],n=["M",a.x,a.y],r=1;o>r;r++)n.push("H",(a.x+t[r].x)/2,"V",t[r].y),a=t[r];break;case"stepBefore":for(n=["M",t[0].x,t[0].y],r=1;o>r;r++)n.push("V",t[r].y,"H",t[r].x);break;case"stepAfter":for(n=["M",t[0].x,t[0].y],r=1;o>r;r++)n.push("H",t[r].x,"V",t[r].y);break;default:for(n=["M"],r=0;o>r;r++)n.push(t[r].x,t[r].y)}return n=this.fixPathForFill(n,t,e,i),n.join(" ")},fixPathForFill:function(t,e,i,n){if(0===e.length)return t;var r=this.stats.bySerie[i.name||n];if(!r.nonDecreasingX)return t;var a=10,s=this.model.get("size"),o=_.first(e),l=_.last(e),c=["M",l.x,s.height+a,"H",o.x-a,"V",o.y];return t[0]="L",c.concat(t)},updateAxis:function(){var t=this.model.get("size"),e=t.width,i=t.height,n=this.model.get("axis"),r=this.canvas.height/i;if(this.canvas.width/e,V(this.elYAxisPath).attr("d",["M",0,0,"L",0,i].join(" ")),V(this.elXAxisPath).attr("d",["M",0,i,"L",e,i].join(" ")),this.elXAxisTicks.textContent="",this.elYAxisTicks.textContent="",!this.isEmpty()){var a=[this.stats.minX,this.stats.maxX],s=[this.stats.minY,this.stats.maxY],o=[this.canvas.x,this.canvas.x+this.canvas.width],l=[0,this.canvas.height];a[1]-a[0];var c=s[1]-s[0],h=n&&n["y-axis"]||{},u=n&&n["x-axis"]||{},p=c>0?h.ticks-1||10:0,d=c/p/r,f=s[0];_.each(_.range(p+1),function(){var t=g.scale.linear(s,l,f),e=this.elTick.clone();e.translate(0,t),V(this.elYAxisTicks).append(e);var i=s[1]-(f-s[0]);i+=g.scale.linear(l,s,this.canvas.y)-s[0],e.findOne("text").text(this.tickLabel(i,h)),f+=d
+},this),_.each(this.stats.xValues,function(t,n){if(0===n%(u.tickStep||1)){var r=g.scale.linear(a,o,t);if(!(r>e)){var s=this.elTick.clone();s.translate(r,i),V(this.elXAxisTicks).append(s),s.findOne("text").text(this.tickLabel(t,u))}}},this)}},tickLabel:function(t,e){if(_.isFunction(e.tickFormat))return e.tickFormat(t);var i=e.tickFormat||".1f",n=joint.util.format.number(i,t);return n+(_.isFunction(e.tickSuffix)?e.tickSuffix(t):e.tickSuffix||"")},pointLabel:function(t,e){if(_.isFunction(e.pointFormat))return e.pointFormat(t);var i=e.pointFormat||".1f",n=joint.util.format.number(i,t.y);return n+(e.pointSuffix||"")},updateMarkings:function(){function t(t,e){return _.isUndefined(t)?e:t}this.elMarkings.textContent="";var e=this.model.get("markings");if(e&&0!==e.length){var i=this.model.get("size"),n=i.width,r=i.height,a=[this.stats.minX,this.stats.maxX],s=[this.stats.minY,this.stats.maxY],o=[this.canvas.x,this.canvas.x+this.canvas.width],l=[this.canvas.y,this.canvas.y+this.canvas.height];_.each(e,function(e,i){var c=e.start||e.end,h=e.end||e.start,u=Math.min(t(c.x,this.stats.minX),t(h.x,this.stats.minX)),p=Math.max(t(c.x,this.stats.maxX),t(h.x,this.stats.maxX)),d=Math.min(t(c.y,this.stats.minY),t(h.y,this.stats.minY)),f=Math.max(t(c.y,this.stats.maxY),t(h.y,this.stats.maxY)),m=_.isUndefined(c.x)||_.isUndefined(h.x),I=_.isUndefined(c.y)||_.isUndefined(h.y);m&&(o=[0,n]),I&&(l=[0,r]);var y=g.scale.linear(a,o,u),v=g.scale.linear(a,o,p),C=g.scale.linear(s,l,d),b=g.scale.linear(s,l,f),A=y,w=l[1]-b+l[0],x=v-y,M=b-C;x=Math.max(x,1),M=Math.max(M,1);var j=this.elMarking.clone();j.findOne("rect").attr({x:A,y:w,width:x,height:M}),j.findOne("text").text(e.label||"").attr({x:A+x,y:w});var N=j.attr("class")+" "+(e.name||"marking-"+i);j.attr(_.extend({"class":N},e.attrs)),V(this.elMarkings).append(j)},this)}},updateLegend:function(){var t=this.model.get("series");this.elLegendItems.textContent="",_.each(t,function(t,e){var i=this.elLegendItem.clone();_.contains(this._disabledSeries,t.name)&&i.addClass("disabled"),i.attr("data-serie",t.name),i.findOne("circle").attr({fill:this.getSerieColor(t.name)}),i.findOne("text").text(t.label||t.name),i.translate(0,16*e),V(this.elLegendItems).append(i)},this)},getSerieColor:function(t){var e=this.model.get("attrs"),i=_.find(e,function(e,i){return _.contains(i,t)?!0:void 0});return i?i.stroke||i.fill:"black"},hideSerie:function(t){_.contains(this._disabledSeries,t)||this._disabledSeries.push(t);var e=this.filterSeries();this.update(e)},showSerie:function(t){this._disabledSeries=_.without(this._disabledSeries,t);var e=this.filterSeries();this.update(e)},filterSeries:function(t){return t=t||this.model.get("series"),t=_.reject(t,function(t){return _.contains(this._disabledSeries,t.name)},this)},onPointerDown:function(t){var e=$(t.target).closest(".legend-item")[0];e&&(V(e).toggleClass("disabled"),V(e).hasClass("disabled")?this.hideSerie(V(e).attr("data-serie")):this.showSerie(V(e).attr("data-serie")))},onMouseMove:function(t){this.showGuidelines(t.clientX,t.clientY,t)},onMouseOut:function(t){this.hideGuidelines(),this.trigger("mouseout",t)},showGuidelines:function(t,e,i){var n=this.model.get("angle"),r=this.model.getBBox();this.model.get("series");var a=g.point(V(this.paper.viewport).toLocalPoint(t,e)).rotate(r.center(),n);if(g.rect(r).containsPoint(a)){var s=this.model.get("size"),o=a.x-r.x,l=a.y-r.y;V(this.elXGuideline).attr({x1:o,y1:0,x2:o,y2:s.height,visibility:"visible"}),V(this.elYGuideline).attr({x1:0,y1:l,x2:s.width,y2:l,visibility:"visible"});var c=g.scale.linear([this.canvas.x,this.canvas.x+this.canvas.width],[this.stats.minX,this.stats.maxX],o),h=g.scale.linear([this.canvas.y,this.canvas.y+this.canvas.height],[this.stats.minY,this.stats.maxY],l),u={x:c,y:this.stats.minY+this.stats.maxY-h},p={x:t,y:e},d=this.closestPoints(c);this.trigger("mouseover",u,p,d,i)}},closestPoints:function(t){var e=_.sortedIndex(this.stats.xValues,t),i=this.stats.xValues[e],n=this.stats.xValues[e-1],r=_.isUndefined(n)?i:Math.abs(t-i)<Math.abs(t-n)?i:n;return this.stats.xMap[r]},hideGuidelines:function(){V(this.elXGuideline).attr("visibility","hidden"),V(this.elYGuideline).attr("visibility","hidden")}}),"object"==typeof exports&&(module.exports=joint.shapes.chart),"object"==typeof exports)var joint={util:require("../src/core").util,shapes:{},dia:{Element:require("../src/joint.dia.element").Element,Link:require("../src/joint.dia.link").Link}};joint.shapes.bpmn={},joint.shapes.bpmn.icons={none:"",message:"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUxMiA1MTIiIGhlaWdodD0iNTEycHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB3aWR0aD0iNTEycHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik00NzkuOTk4LDY0SDMyQzE0LjMyOSw2NCwwLDc4LjMxMiwwLDk2djMyMGMwLDE3LjY4OCwxNC4zMjksMzIsMzIsMzJoNDQ3Ljk5OEM0OTcuNjcxLDQ0OCw1MTIsNDMzLjY4OCw1MTIsNDE2Vjk2ICBDNTEyLDc4LjMxMiw0OTcuNjcxLDY0LDQ3OS45OTgsNjR6IE00MTYsMTI4TDI1NiwyNTZMOTYsMTI4SDQxNnogTTQ0OCwzODRINjRWMTYwbDE5MiwxNjBsMTkyLTE2MFYzODR6Ii8+PC9zdmc+",plus:"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDI0IDI0IiBoZWlnaHQ9IjI0cHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjI0cHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTIyLjUsMTRIMTR2OC41YzAsMC4yNzYtMC4yMjQsMC41LTAuNSwwLjVoLTRDOS4yMjQsMjMsOSwyMi43NzYsOSwyMi41VjE0SDAuNSAgQzAuMjI0LDE0LDAsMTMuNzc2LDAsMTMuNXYtNEMwLDkuMjI0LDAuMjI0LDksMC41LDlIOVYwLjVDOSwwLjIyNCw5LjIyNCwwLDkuNSwwaDRDMTMuNzc2LDAsMTQsMC4yMjQsMTQsMC41VjloOC41ICBDMjIuNzc2LDksMjMsOS4yMjQsMjMsOS41djRDMjMsMTMuNzc2LDIyLjc3NiwxNCwyMi41LDE0eiIgZmlsbC1ydWxlPSJldmVub2RkIi8+PC9zdmc+",cross:"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDI0IDI0IiBoZWlnaHQ9IjI0cHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjI0cHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik0yMi4yNDUsNC4wMTVjMC4zMTMsMC4zMTMsMC4zMTMsMC44MjYsMCwxLjEzOWwtNi4yNzYsNi4yN2MtMC4zMTMsMC4zMTItMC4zMTMsMC44MjYsMCwxLjE0bDYuMjczLDYuMjcyICBjMC4zMTMsMC4zMTMsMC4zMTMsMC44MjYsMCwxLjE0bC0yLjI4NSwyLjI3N2MtMC4zMTQsMC4zMTItMC44MjgsMC4zMTItMS4xNDIsMGwtNi4yNzEtNi4yNzFjLTAuMzEzLTAuMzEzLTAuODI4LTAuMzEzLTEuMTQxLDAgIGwtNi4yNzYsNi4yNjdjLTAuMzEzLDAuMzEzLTAuODI4LDAuMzEzLTEuMTQxLDBsLTIuMjgyLTIuMjhjLTAuMzEzLTAuMzEzLTAuMzEzLTAuODI2LDAtMS4xNGw2LjI3OC02LjI2OSAgYzAuMzEzLTAuMzEyLDAuMzEzLTAuODI2LDAtMS4xNEwxLjcwOSw1LjE0N2MtMC4zMTQtMC4zMTMtMC4zMTQtMC44MjcsMC0xLjE0bDIuMjg0LTIuMjc4QzQuMzA4LDEuNDE3LDQuODIxLDEuNDE3LDUuMTM1LDEuNzMgIEwxMS40MDUsOGMwLjMxNCwwLjMxNCwwLjgyOCwwLjMxNCwxLjE0MSwwLjAwMWw2LjI3Ni02LjI2N2MwLjMxMi0wLjMxMiwwLjgyNi0wLjMxMiwxLjE0MSwwTDIyLjI0NSw0LjAxNXoiLz48L3N2Zz4=",user:"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDI0IDI0IiBoZWlnaHQ9IjI0cHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjI0cHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTIyLDIwLjk5OGgtMWMwLDAtMSwwLTEtMVYxNy41YzAtMC4yNzctMC4yMjQtMC41LTAuNS0wLjVTMTksMTcuMjIzLDE5LDE3LjUgIGwtMC4wMDgsNC4yOTVjMCwwLjYwOS0yLjAxLDIuMjA1LTYuNDkyLDIuMjA1cy02LjQ5Mi0xLjU5Ni02LjQ5Mi0yLjIwNUw2LDE3LjVDNiwxNy4yMjMsNS43NzYsMTcsNS41LDE3UzUsMTcuMjIzLDUsMTcuNXYyLjQ5OCAgYzAsMS0xLDEtMSwxSDNjMCwwLTEsMC0xLTFWMTUuNzVjMC0yLjkyMiwyLjg5Mi01LjQwMSw2LjkzLTYuMzQxYzAsMCwxLjIzNCwxLjEwNywzLjU3LDEuMTA3czMuNTctMS4xMDcsMy41Ny0xLjEwNyAgYzQuMDM4LDAuOTQsNi45MywzLjQxOSw2LjkzLDYuMzQxdjQuMjQ4QzIzLDIwLjk5OCwyMiwyMC45OTgsMjIsMjAuOTk4eiBNMTIuNDc3LDljLTIuNDg1LDAtNC41LTIuMDE1LTQuNS00LjVTOS45OTEsMCwxMi40NzcsMCAgczQuNSwyLjAxNSw0LjUsNC41UzE0Ljk2Miw5LDEyLjQ3Nyw5eiIgZmlsbC1ydWxlPSJldmVub2RkIi8+PC9zdmc+",circle:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gULEBE3DEP64QAAAwlJREFUaN7dmktrU0EUx38ZmmBbfEIL2hSjkYKC1EW6EDFudC+404/gE6WKSvGxERQfIH4AX1T9EOKrCrYurVrbgsZWoaBVixDbpC6ci+Fyz9ybZG478cBs7syc+Z+5c86c+c8ksCPrgW1ADtgEbARafG1+AW+AYWAIGADGWUTZAJwHxoD5GssocA7ILiTwLcADoFQHcH8pAfeB7jiBtwO3gLJF4P5S1mO02wa/C5iMEbi/TAI7bYE/Y3m5VLOs+sLAJULqrgKHIxhZBp4DT4FX2jkLGoinq1M7fg7YDmwFVATd14CjFboiy5UIs/QBOAmka/izaeCU1hE2zuVqlZ8IUfgVOAA0WViiTcBBrdM0Zm9UhTuAOYOiRzXOeJh0Ak8M484B+TAlK4BPBiU3gWSMoTqpw6g0fgFYblJww9D5dojT25IEcMeA47rUsdsQLp9FmPmURSNSOqpJS2lzUKd+ocN3IBNx5mz+oXXADwHTXX/jjMFxjy1iwtgrYJoF1lY27BMafozZaaMspYKA7XRlw7f1xt4Y5biA7bXXIGv4TW0OGNCmsQRhzCidlwTJADDlgAFTwAuhLq+AHqHyMe6IhKVHAV1C5ZBDBkhYupThPPreIQNGJTJBGXKLLw4Z8NmQu/Fb8PCkQwakBIxFRWPLvAJmhMpWh4AuFb7PKGBaqFzjkAGrhe/TSjNrQZJ1yAAJy5gCRoTKnEMGSFhGFDBoOBu7IhKWQe8wLRFLHQ6A7zCcFNNK59vvAjoqYK8DBuwTCLBhTUD8Hweahj9S2jjU297VqzrU26BVmi2yEjXRKg1PbHnpqYla7AeWxAi+GbhHHdSit2mYyN2XQQ5kQTJ6Y6qL3PUkCr2+H7v0+jcs0eueRLngGNeKa9mxY73g8JzpEtHusorAQ/7e+e7WUWIl//jSVTrK7QEu6KgW9d7tYr3B44iBWPJfkZZ8pZ4r2VngkC0HywMTLNwN5YSBcKtZWoGzernEBbyox2iJc6Np2KcGfnHisYet1CDouc2yCjbhp07MrD+3+QNxi4JkAscRswAAAABJRU5ErkJggg=="},joint.shapes.bpmn.IconInterface={initialize:function(){this._parent=(this._parent||this).constructor.__super__,this._parent.initialize.apply(this,arguments),this.listenTo(this,"change:icon",this._onIconChange),this._onIconChange(this,this.get("icon")||"none")},_onIconChange:function(t,e){var i=joint.shapes.bpmn.icons;if(!_.has(i,e))throw"BPMN: Unknown icon: "+e;t.attr("image/xlink:href",i[e])}},joint.shapes.bpmn.SubProcessInterface={initialize:function(){this._parent=(this._parent||this).constructor.__super__,this._parent.initialize.apply(this,arguments),this.listenTo(this,"change:subProcess",this._onSubProcessChange),this._onSubProcessChange(this,this.get("subProcess")||null)},_onSubProcessChange:function(t,e){t.attr({".sub-process":{visibility:e?"visible":"hidden","data-sub-process":e||""}})}},joint.shapes.bpmn.ActivityView=joint.shapes.basic.TextBlockView,joint.shapes.bpmn.Activity=joint.shapes.basic.TextBlock.extend({markup:['<g class="rotatable">','<g class="scalable"><rect class="body outer"/><rect class="body inner"/></g>',"<switch>",'<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">','<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',"</foreignObject>",'<text class="content"/>','</switch><path class="sub-process"/><image class="icon"/></g>'].join(""),defaults:joint.util.deepSupplement({size:{width:100,height:100},type:"bpmn.Activity",attrs:{rect:{rx:8,ry:8,width:100,height:100},".body":{fill:"#ffffff",stroke:"#000000"},".inner":{transform:"scale(0.9,0.9) translate(5,5)"},path:{d:"M 0 0 L 30 0 30 30 0 30 z M 15 4 L 15 26 M 4 15 L 26 15",ref:".inner","ref-x":.5,"ref-dy":-30,"x-alignment":"middle",stroke:"#000000",fill:"transparent"},image:{ref:".inner","ref-x":5,width:20,height:20}},activityType:"task",subProcess:null},joint.shapes.basic.TextBlock.prototype.defaults),initialize:function(){joint.shapes.basic.TextBlock.prototype.initialize.apply(this,arguments),this.listenTo(this,"change:activityType",this.onActivityTypeChange),this.listenTo(this,"change:subProcess",this.onSubProcessChange),this.onSubProcessChange(this,this.get("subProcess")),this.onActivityTypeChange(this,this.get("activityType"))},onActivityTypeChange:function(t,e){switch(e){case"task":t.attr({".inner":{visibility:"hidden"},".outer":{"stroke-width":1,"stroke-dasharray":"none"},path:{ref:".outer"},image:{ref:".outer"}});break;case"transaction":t.attr({".inner":{visibility:"visible"},".outer":{"stroke-width":1,"stroke-dasharray":"none"},path:{ref:".inner"},image:{ref:".inner"}});break;case"event-sub-process":t.attr({".inner":{visibility:"hidden"},".outer":{"stroke-width":1,"stroke-dasharray":"1,2"},path:{ref:".outer"},image:{ref:".outer"}});break;case"call-activity":t.attr({".inner":{visibility:"hidden"},".outer":{"stroke-width":5,"stroke-dasharray":"none"},path:{ref:".outer"},image:{ref:".outer"}});break;default:throw"BPMN: Unknown Activity Type: "+e}},onSubProcessChange:function(t,e){e?t.attr({".fobj div":{style:{verticalAlign:"baseline",paddingTop:10}},image:{"ref-dy":-25,"ref-y":""},text:{"ref-y":25}}):t.attr({".fobj div":{style:{verticalAlign:"middle",paddingTop:0}},image:{"ref-dy":"","ref-y":5},text:{"ref-y":.5}})}}).extend(joint.shapes.bpmn.IconInterface).extend(joint.shapes.bpmn.SubProcessInterface),joint.shapes.bpmn.AnnotationView=joint.shapes.basic.TextBlockView,joint.shapes.bpmn.Annotation=joint.shapes.basic.TextBlock.extend({markup:['<g class="rotatable">','<g class="scalable"><rect class="body"/></g>',"<switch>",'<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">','<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',"</foreignObject>",'<text class="content"/>','</switch><path class="stroke"/></g>'].join(""),defaults:joint.util.deepSupplement({size:{width:100,height:100},type:"bpmn.Annotation",attrs:{rect:{width:100,height:100},".body":{"fill-opacity":.1,fill:"#ffffff",stroke:"none"},".fobj div":{style:{textAlign:"left",paddingLeft:10}},".stroke":{stroke:"#000000",fill:"none","stroke-width":3}},wingLength:20},joint.shapes.basic.TextBlock.prototype.defaults),initialize:function(){joint.shapes.basic.TextBlock.prototype.initialize.apply(this,arguments),this.listenTo(this,"change:size",this.onSizeChange),this.onSizeChange(this,this.get("size"))},onSizeChange:function(t,e){t.attr(".stroke",{d:t.getStrokePathData(e.width,e.height,t.get("wingLength"))})},getStrokePathData:function(t,e,i){return i=Math.min(i,t),["M",i,"0 L 0 0 0",e,i,e].join(" ")}}),joint.shapes.bpmn.Gateway=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><polygon class="body"/><image/></g></g><text class="label"/>',defaults:joint.util.deepSupplement({type:"bpmn.Gateway",size:{width:80,height:80},attrs:{".body":{points:"40,0 80,40 40,80 0,40",fill:"#ffffff",stroke:"#000000"},".label":{text:"",ref:".body","ref-x":.5,"ref-dy":20,"y-alignment":"middle","x-alignment":"middle","font-size":14,"font-family":"Arial, helvetica, sans-serif",fill:"#000000"},image:{width:40,height:40,"xlink:href":"",transform:"translate(20,20)"}}},joint.dia.Element.prototype.defaults)}).extend(joint.shapes.bpmn.IconInterface),joint.shapes.bpmn.Event=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><circle class="body outer"/><circle class="body inner"/><image/></g><text class="label"/></g>',defaults:joint.util.deepSupplement({type:"bpmn.Event",size:{width:60,height:60},attrs:{".body":{fill:"#ffffff",stroke:"#000000"},".outer":{"stroke-width":1,r:30,transform:"translate(30,30)"},".inner":{"stroke-width":1,r:26,transform:"translate(30,30)"},image:{width:40,height:40,"xlink:href":"",transform:"translate(10,10)"},".label":{text:"",fill:"#000000","font-family":"Arial","font-size":14,ref:".outer","ref-x":.5,"ref-dy":20,"x-alignment":"middle","y-alignment":"middle"}},eventType:"start"},joint.dia.Element.prototype.defaults),initialize:function(){joint.dia.Element.prototype.initialize.apply(this,arguments),this.listenTo(this,"change:eventType",this.onEventTypeChange),this.onEventTypeChange(this,this.get("eventType"))},onEventTypeChange:function(t,e){switch(e){case"start":t.attr({".inner":{visibility:"hidden"},".outer":{"stroke-width":1}});break;case"end":t.attr({".inner":{visibility:"hidden"},".outer":{"stroke-width":5}});break;case"intermediate":t.attr({".inner":{visibility:"visible"},".outer":{"stroke-width":1}});break;default:throw"BPMN: Unknown Event Type: "+e}}}).extend(joint.shapes.bpmn.IconInterface),joint.shapes.bpmn.Pool=joint.dia.Element.extend({markup:['<g class="rotatable">','<g class="scalable"><rect class="body"/></g>','<svg overflow="hidden" class="blackbox-wrap"><text class="blackbox-label"/></svg>','<rect class="header"/><text class="label"/>','<g class="lanes"/>',"</g>"].join(""),laneMarkup:'<g class="lane"><rect class="lane-body"/><rect class="lane-header"/><text class="lane-label"/></g>',defaults:joint.util.deepSupplement({type:"bpmn.Pool",size:{width:600,height:300},attrs:{".body":{fill:"#ffffff",stroke:"#000000",width:500,height:200,"pointer-events":"stroke"},".header":{fill:"#ffffff",stroke:"#000000",width:20,ref:".body","ref-height":1,"pointer-events":"visiblePainted"},".label":{transform:"rotate(-90)",ref:".header","ref-x":10,"ref-y":.5,"font-family":"Arial","font-size":14,"x-alignment":"middle","text-anchor":"middle"},".lane-body":{fill:"#ffffff",stroke:"#000000","pointer-events":"stroke"},".lane-header":{fill:"#ffffff",stroke:"#000000","pointer-events":"visiblePainted"},".lane-label":{transform:"rotate(-90)","text-anchor":"middle","font-family":"Arial","font-size":13},".blackbox-wrap":{ref:".body","ref-width":1,"ref-height":1},".blackbox-label":{text:"Black Box",dx:"50%",dy:"50%","text-anchor":"middle",transform:"translate(0,-7)"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.bpmn.PoolView=joint.dia.ElementView.extend({options:{headerWidth:20},initialize:function(){this.listenTo(this.model,"change:lanes",function(t,e){this.renderLanes(e)}),joint.dia.ElementView.prototype.initialize.apply(this,arguments)},update:function(){return _.isUndefined(this.lanesAttrs)?this.renderLanes(this.model.get("lanes")):joint.dia.ElementView.prototype.update.call(this,this.model,_.merge({},this.model.get("attrs"),this.lanesAttrs||{}))},renderMarkup:function(){joint.dia.ElementView.prototype.renderMarkup.apply(this,arguments),this.$lanes=this.$(".lanes"),this.laneMarkup=V(this.model.laneMarkup)},renderLanes:function(t){t=t||{},this.index=0,this.lanesAttrs={".header":{width:this.options.headerWidth},".label":{text:t.label||""}},this.$lanes.empty(),t.sublanes&&this.renderSublanes(t.sublanes,0,0,1),this.update(this.model,_.merge({},this.model.get("attrs"),this.lanesAttrs))},renderSublanes:function(t,e,i,n){var r=this.options.headerWidth,a=1/t.length*n;_.each(t,function(t,n){var s="lane"+this.index,o="."+s+" .lane-body",l="."+s+" .lane-header",c="."+s+" .lane-label";t.name&&(s+=" "+t.name),this.$lanes.append(this.laneMarkup.clone().addClass(s).node);var h=e+r,u=i+a*n;this.lanesAttrs[o]={ref:".body","ref-height":a,"ref-width":-h,"ref-x":h,"ref-y":u},this.lanesAttrs[l]={width:r,ref:".body","ref-height":a,"ref-x":h,"ref-y":u},this.lanesAttrs[c]={text:t.label,ref:l,"ref-x":10,"ref-y":.5,"x-alignment":"middle"},this.index++,t.sublanes&&this.renderSublanes(t.sublanes,h,u,a)},this)}}),joint.shapes.bpmn.Group=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><rect class="body"/></g><rect class="label-rect"/><g class="label-group"><svg overflow="hidden" class="label-wrap"><text class="label"/></svg></g></g>',defaults:joint.util.deepSupplement({type:"bpmn.Group",size:{width:200,height:200},attrs:{".body":{width:200,height:200,stroke:"#000000","stroke-dasharray":"6,6","stroke-width":2,fill:"transparent",rx:15,ry:15,"pointer-events":"stroke"},".label-rect":{ref:".body","ref-width":.6,"ref-x":.4,"ref-y":-30,height:25,fill:"#ffffff",stroke:"#000000"},".label-group":{ref:".label-rect","ref-x":0,"ref-y":0},".label-wrap":{ref:".label-rect","ref-width":1,"ref-height":1},".label":{text:"",x:"50%",dy:5,"text-anchor":"middle","font-family":"Arial","font-size":14,fill:"#000000"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.bpmn.DataObject=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><polygon class="body"/></g><text class="label"/></g>',defaults:joint.util.deepSupplement({type:"bpmn.DataObject",size:{width:60,height:80},attrs:{".body":{points:"20,0 60,0 60,80 0,80 0,20 20,0 20,20 0,20",stroke:"#000000",fill:"#ffffff"},".label":{ref:".body","ref-x":.5,"ref-dy":5,text:"","text-anchor":"middle"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.bpmn.Conversation=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><polygon class="body"/></g><text class="label"/><path class="sub-process"/></g>',defaults:joint.util.deepSupplement({type:"bpmn.Conversation",size:{width:100,height:100},attrs:{".body":{points:"25,0 75,0 100,50 75,100 25,100 0,50",stroke:"#000000",fill:"#ffffff"},".label":{text:"",ref:".body","ref-x":.5,"ref-dy":5,"text-anchor":"middle"},path:{d:"M 0 0 L 30 0 30 30 0 30 z M 15 4 L 15 26 M 4 15 L 26 15",ref:".body","ref-x":.5,"ref-dy":-30,"x-alignment":"middle",fill:"#ffffff",stroke:"#000000","fill-opacity":0}},conversationType:"conversation"},joint.dia.Element.prototype.defaults),initialize:function(){joint.dia.Element.prototype.initialize.apply(this,arguments),this.listenTo(this,"change:conversationType",this.onConversationTypeChange),this.onConversationTypeChange(this,this.get("conversationType"))},onConversationTypeChange:function(t,e){switch(e){case"conversation":t.attr("polygon/stroke-width",1);break;case"call-conversation":t.attr("polygon/stroke-width",4);break;default:throw"BPMN: Unknown Conversation Type: "+e}}}).extend(joint.shapes.bpmn.SubProcessInterface),joint.shapes.bpmn.Choreography=joint.shapes.basic.TextBlock.extend({markup:['<g class="rotatable">','<g class="scalable"><rect class="body"/></g>',"<switch>",'<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">','<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',"</foreignObject>",'<text class="content"/>',"</switch>",'<text class="label"/><path class="sub-process"/><g class="participants"/>',"</g>"].join(""),participantMarkup:'<g class="participant"><rect class="participant-rect"/><text class="participant-label"/></g>',defaults:joint.util.deepSupplement({type:"bpmn.Choreography",size:{width:60,height:80},attrs:{rect:{},".body":{width:60,height:80,stroke:"#000000",fill:"#ffffff"},".label":{ref:".body","ref-x":.5,"ref-dy":5,text:"","text-anchor":"middle"},".participant-rect":{stroke:"#000000",fill:"#aaaaaa",ref:".body","ref-width":1},".participant-label":{"text-anchor":"middle",ref:".participant_0 .participant-rect","ref-x":.5,"ref-y":.5,"y-alignment":"middle"},".sub-process":{d:"M 0 0 L 30 0 30 30 0 30 z M 15 4 L 15 26 M 4 15 L 26 15",ref:".body","ref-x":.5,"ref-dy":-30,"x-alignment":"middle",fill:"transparent",stroke:"#000000"}},participants:[],initiatingParticipant:0},joint.shapes.basic.TextBlock.prototype.defaults)}).extend(joint.shapes.bpmn.SubProcessInterface),joint.shapes.bpmn.ChoreographyView=joint.shapes.basic.TextBlockView.extend({options:{participantHeight:20},initialize:function(){this.listenTo(this.model,"change:participants",function(t,e){this.renderParticipants(e)}),this.listenTo(this.model,"change:size",this.layoutAndUpdate),this.listenTo(this.model,"change:initiatingParticipant",this.layoutAndUpdate),joint.shapes.basic.TextBlockView.prototype.initialize.apply(this,arguments),this.noSVGForeignObjectElement&&this.off(null,"change:content").listenTo(this.model,"change:content",function(t){this.updateContent(t,this.participantsAttrs)})},update:function(){return _.isUndefined(this.participantsAttrs)?this.renderParticipants(this.model.get("participants")):(this.layoutAndUpdate(),this)},renderMarkup:function(){joint.dia.ElementView.prototype.renderMarkup.apply(this,arguments),this.$participants=this.$(".participants"),this.participantMarkup=V(this.model.participantMarkup)},renderParticipants:function(t){this.$participants.empty(),this.participantsAttrs={},_.each(t,function(t,e){var i="participant_"+e,n="."+i;this.participantsAttrs[n+" .participant-rect"]={height:this.options.participantHeight},this.participantsAttrs[n+" .participant-label"]={text:t},this.$participants.append(this.participantMarkup.clone().addClass(i).node)},this),this.layoutAndUpdate()},layoutAndUpdate:function(){var t=this.model.get("participants")||[],e=t.length,i=this.options.participantHeight,n=this.model.get("size").height,r=Math.max(0,n-i*e),a=0,s=this.model.get("initiatingParticipant"),o=Math.max(_.isNumber(s)?Math.abs(s):t.indexOf(s),0),l=Math.min(o,e-2);_.each(t,function(t,e){var n=".participant_"+e;this.participantsAttrs[n]={transform:"translate(0,"+a+")"},this.participantsAttrs[n+" .participant-rect"].fill=o==e?this.model.attr(".body/fill"):this.model.attr(".participant-rect/fill"),this.participantsAttrs[n+" .participant-rect"].stroke=o==e?this.model.attr(".body/stroke"):this.model.attr(".participant-rect/stroke"),a+=i+(l==e?r:0)},this);var c=2>e?0:l-e+1;this.participantsAttrs[".sub-process"]={"ref-dy":Math.max(-n,c*i-30)};var h=2>e?0:l+1;this.participantsAttrs[".fobj div"]={style:{height:r,paddingTop:i*h}},this.participantsAttrs[".content"]={"ref-y":i*h+r/2};var u=_.merge({},this.model.get("attrs"),this.participantsAttrs||{});joint.shapes.basic.TextBlockView.prototype.update.call(this,this.model,u)}}),joint.shapes.bpmn.Message=joint.dia.Element.extend({markup:'<g class="rotatable"><g class="scalable"><polygon class="body"/></g><text class="label"/></g>',defaults:joint.util.deepSupplement({type:"bpmn.Message",size:{width:60,height:40},attrs:{".body":{points:"0,0 60,0 60,40 0,40 0,0 60,0 30,20 0,0",stroke:"#000000",fill:"#ffffff"},".label":{ref:".body","ref-x":.5,"ref-dy":5,text:"","text-anchor":"middle"}}},joint.dia.Element.prototype.defaults)}),joint.shapes.bpmn.Flow=joint.dia.Link.extend({defaults:{type:"bpmn.Flow",attrs:{".marker-source":{d:"M 0 0"},".marker-target":{d:"M 10 0 L 0 5 L 10 10 z",fill:"#000000"},".connection":{"stroke-dasharray":" ","stroke-width":1},".connection-wrap":{style:"",onMouseOver:"",onMouseOut:""}},flowType:"normal"},initialize:function(){joint.dia.Link.prototype.initialize.apply(this,arguments),this.listenTo(this,"change:flowType",this.onFlowTypeChange),this.onFlowTypeChange(this,this.get("flowType"))},onFlowTypeChange:function(t,e){var i;switch(e){case"default":i={".marker-source":{d:"M 0 5 L 20 5 M 20 0 L 10 10",fill:"none"}};break;case"conditional":i={".marker-source":{d:"M 20 8 L 10 0 L 0 8 L 10 16 z",fill:"#FFF"}};break;case"normal":i={};break;case"message":i={".marker-target":{fill:"#FFF"},".connection":{"stroke-dasharray":"4,4"}};break;case"association":i={".marker-target":{d:"M 0 0"},".connection":{"stroke-dasharray":"4,4"}};break;case"conversation":i={".marker-target":{d:"M 0 0"},".connection":{"stroke-width":"7px"},".connection-wrap":{style:"stroke: #fff; stroke-width: 5px; opacity: 1;",onMouseOver:"var s=this.style;s.stroke='#000';s.strokeWidth=15;s.opacity=.4",onMouseOut:"var s=this.style;s.stroke='#fff';s.strokeWidth=5;s.opacity=1"}};break;default:throw"BPMN: Unknown Flow Type: "+e}t.attr(_.merge({},this.defaults.attrs,i))}}),joint.dia.CommandManager=Backbone.Model.extend({defaults:{cmdBeforeAdd:null,cmdNameRegex:/^(?:add|remove|change:\w+)$/},PREFIX_LENGTH:7,initialize:function(t){_.bindAll(this,"initBatchCommand","storeBatchCommand"),this.graph=t.graph,this.reset(),this.listen()},listen:function(){this.listenTo(this.graph,"all",this.addCommand,this),this.listenTo(this.graph,"batch:start",this.initBatchCommand,this),this.listenTo(this.graph,"batch:stop",this.storeBatchCommand,this)},createCommand:function(t){var e={action:void 0,data:{id:void 0,type:void 0,previous:{},next:{}},batch:t&&t.batch};return e},addCommand:function(t,e,i,n){if(this.get("cmdNameRegex").test(t)&&("function"!=typeof this.get("cmdBeforeAdd")||this.get("cmdBeforeAdd").apply(this,arguments))){var r=_.bind(function(t){this.redoStack=[],t.batch?(this.lastCmdIndex=Math.max(this.lastCmdIndex,0),this.trigger("batch",t)):(this.undoStack.push(t),this.trigger("add",t))},this),a=void 0;if(this.batchCommand?(a=this.batchCommand[Math.max(this.lastCmdIndex,0)],this.lastCmdIndex>=0&&(a.data.id!==e.id||a.action!==t)&&(a=_.find(this.batchCommand,function(i,n){return this.lastCmdIndex=n,i.data.id===e.id&&i.action===t},this),a||(this.lastCmdIndex=this.batchCommand.push(this.createCommand({batch:!0}))-1,a=_.last(this.batchCommand)))):(a=this.createCommand(),a.batch=!1),"add"===t||"remove"===t)return a.action=t,a.data.id=e.id,a.data.type=e.attributes.type,a.data.attributes=_.merge({},e.toJSON()),a.options=n||{},r(a);var s=t.substr(this.PREFIX_LENGTH);return a.batch&&a.action||(a.action=t,a.data.id=e.id,a.data.type=e.attributes.type,a.data.previous[s]=_.clone(e.previous(s)),a.options=n||{}),a.data.next[s]=_.clone(e.get(s)),r(a)}},initBatchCommand:function(){this.batchCommand?this.batchLevel++:(this.batchCommand=[this.createCommand({batch:!0})],this.lastCmdIndex=-1,this.batchLevel=0)},storeBatchCommand:function(){this.batchCommand&&0>=this.batchLevel?(this.lastCmdIndex>=0&&(this.redoStack=[],this.undoStack.push(this.batchCommand),this.trigger("add",this.batchCommand)),delete this.batchCommand,delete this.lastCmdIndex,delete this.batchLevel):this.batchCommand&&this.batchLevel>0&&this.batchLevel--},revertCommand:function(t){this.stopListening();var e;e=_.isArray(t)?t:[t];for(var i=e.length-1;i>=0;i--){var n=e[i],r=this.graph.getCell(n.data.id);switch(n.action){case"add":r.remove();break;case"remove":this.graph.addCell(n.data.attributes);break;default:var a=n.action.substr(this.PREFIX_LENGTH);r.set(a,n.data.previous[a])}}this.listen()},applyCommand:function(t){this.stopListening();var e;e=_.isArray(t)?t:[t];for(var i=0;e.length>i;i++){var n=e[i],r=this.graph.getCell(n.data.id);switch(n.action){case"add":this.graph.addCell(n.data.attributes);break;case"remove":r.remove();break;default:var a=n.action.substr(this.PREFIX_LENGTH);r.set(a,n.data.next[a])}}this.listen()},undo:function(){var t=this.undoStack.pop();t&&(this.revertCommand(t),this.redoStack.push(t))},redo:function(){var t=this.redoStack.pop();t&&(this.applyCommand(t),this.undoStack.push(t))},cancel:function(){this.hasUndo()&&(this.revertCommand(this.undoStack.pop()),this.redoStack=[])},reset:function(){this.undoStack=[],this.redoStack=[]},hasUndo:function(){return this.undoStack.length>0},hasRedo:function(){return this.redoStack.length>0}}),joint.dia.Validator=Backbone.Model.extend({initialize:function(t){this._map={},this._commandManager=t.commandManager,this.listenTo(this._commandManager,"add",this._onCommand)},defaults:{cancelInvalid:!0},_onCommand:function(t){return _.isArray(t)?_.find(t,function(t){return!this._validateCommand(t)},this):this._validateCommand(t)},_validateCommand:function(t){if(t.options&&t.options.validation===!1)return!0;var e;return _.each(this._map[t.action],function(i){function n(a){var s=i[r++];try{if(!s)return e=a,void 0;s(a,t,n)}catch(a){n(a)}}var r=0;n(e)}),e?(this.get("cancelInvalid")&&this._commandManager.cancel(),this.trigger("invalid",e),!1):!0},validate:function(t){var e=_.rest(arguments);return _.each(e,function(e){if(!_.isFunction(e))throw Error(t+" requires callback functions.")}),_.each(t.split(" "),function(t){(this._map[t]=this._map[t]||[]).push(e)},this),this}}),function(){function t(t,i,n){if(_.isUndefined(n))return e.call(this,t,i);n.direction=n.direction||"bottom-right";var r=g.normalizeAngle(this.get("angle")||0),a={"top-right":0,"top-left":1,"bottom-left":2,"bottom-right":3}[n.direction];n.absolute&&(a+=Math.floor((r+45)/90),a%=4);var s=this.getBBox(),o=s[["bottomLeft","corner","topRight","origin"][a]](),l=g.point(o).rotate(s.center(),-r),c=Math.sqrt(t*t+i*i)/2,h=a*Math.PI/2;h+=Math.atan(0==a%2?i/t:t/i),h-=g.toRad(r);var u=g.point.fromPolar(c,h,l),p=g.point(u).offset(t/-2,i/-2);this.resize(t,i).position(p.x,p.y)}var e=joint.dia.Element.prototype.resize;joint.dia.Element.prototype.resize=t}(),joint.ui.PaperScroller=Backbone.View.extend({className:"paper-scroller",events:{mousemove:"pan",touchmove:"pan",mouseout:"stopPanning"},initialize:function(){_.bindAll(this,"startPanning","stopPanning"),$(document.body).on("mouseup touchend",this.stopPanning)
+},render:function(){return this.listenTo(this.options.paper,"scale resize",this.onScale),this.options.autoResizePaper&&(this._ow=this.options.paper.options.width,this._oh=this.options.paper.options.height,this.listenTo(this.options.paper.model,"all",function(){this.options.paper.fitToContent(this._ow,this._oh)})),this},onScale:function(t,e){var i=this.options.paper.viewport.getCTM(),n=i.a,r=i.d;V(this.options.paper.viewport).attr("transform",""),V(this.options.paper.viewport).scale(n,r),V(this.options.paper.svg).attr({width:this.options.paper.options.width*n,height:this.options.paper.options.height*r}),t&&e&&this.center(t,e)},center:function(t,e){(_.isUndefined(t)||_.isUndefined(e))&&(t=this.options.paper.options.width/2,e=this.options.paper.options.height/2);var i=this.options.paper.viewport.getCTM(),n=i.a,r=i.d,a=this.el.clientWidth/n/2,s=this.el.clientHeight/r/2;this.el.scrollLeft=(t-a)*n,this.el.scrollTop=(e-s)*r},centerContent:function(){var t=V(this.options.paper.viewport).bbox(!0,this.options.paper.svg);this.center(t.x+t.width/2,t.y+t.height/2)},startPanning:function(t){t=joint.util.normalizeEvent(t),this._panning=!0,this._clientX=t.clientX,this._clientY=t.clientY},pan:function(t){if(this._panning){t=joint.util.normalizeEvent(t);var e=t.clientX-this._clientX,i=t.clientY-this._clientY;this.el.scrollTop-=i,this.el.scrollLeft-=e,this._clientX=t.clientX,this._clientY=t.clientY}},stopPanning:function(){delete this._panning}}),joint.ui.SelectionView=Backbone.View.extend({options:{paper:void 0,graph:void 0},className:"selection",events:{"mousedown .selection-box":"startTranslatingSelection","touchstart .selection-box":"startTranslatingSelection"},initialize:function(){_.bindAll(this,"startSelecting","stopSelecting","adjustSelection"),$(document.body).on("mousemove.selectionView touchmove.selectionView",this.adjustSelection),this.listenTo(this.options.graph,"reset",this.cancelSelection),this.listenTo(this.options.paper,"scale",this.updateSelectionBoxes),this.listenTo(this.options.graph,"remove change",function(t,e){e["selectionView_"+this.cid]||this.updateSelectionBoxes()}),this.options.paper.$el.append(this.$el),this._boxCount=0},startTranslatingSelection:function(t){t.stopPropagation(),t=joint.util.normalizeEvent(t),this._action="translating",this.options.graph.trigger("batch:start");var e=this.options.paper.snapToGrid(g.point(t.clientX,t.clientY));this._snappedClientX=e.x,this._snappedClientY=e.y,this.trigger("selection-box:pointerdown",t),this.mouseupRegister()},startSelecting:function(t){t=joint.util.normalizeEvent(t),this.cancelSelection(),this._action="selecting",this._clientX=t.clientX,this._clientY=t.clientY;var e=t.target.parentElement||t.target.parentNode,i=$(e).offset(),n=e.scrollLeft,r=e.scrollTop;this._offsetX=void 0===t.offsetX?t.clientX-i.left+window.pageXOffset+n:t.offsetX,this._offsetY=void 0===t.offsetY?t.clientY-i.top+window.pageYOffset+r:t.offsetY,this.$el.css({width:1,height:1,left:this._offsetX,top:this._offsetY}).show(),this.mouseupRegister()},adjustSelection:function(t){t=joint.util.normalizeEvent(t);var e,i;switch(this._action){case"selecting":e=t.clientX-this._clientX,i=t.clientY-this._clientY,this.$el.width(),this.$el.height();var n=parseInt(this.$el.css("left"),10),r=parseInt(this.$el.css("top"),10);this.$el.css({left:0>e?this._offsetX+e:n,top:0>i?this._offsetY+i:r,width:Math.abs(e),height:Math.abs(i)});break;case"translating":var a=this.options.paper.snapToGrid(g.point(t.clientX,t.clientY)),s=a.x,o=a.y;e=s-this._snappedClientX,i=o-this._snappedClientY;var l={};if(this.model.each(function(t){var n={};n["selectionView_"+this.cid]=!0,t.translate(e,i,n);var r=this.options.graph.getConnectedLinks(t);_.each(r,function(t){if(!l[t.id]){var r=t.get("vertices");if(r&&r.length){var a=[];_.each(r,function(t){a.push({x:t.x+e,y:t.y+i})}),t.set("vertices",a,n)}l[t.id]=!0}})},this),e||i){var c=V(this.options.paper.viewport).scale();e*=c.sx,i*=c.sy,this.$(".selection-box").each(function(){var t=parseFloat($(this).css("left"),10),n=parseFloat($(this).css("top"),10);$(this).css({left:t+e,top:n+i})}),this._snappedClientX=s,this._snappedClientY=o}this.trigger("selection-box:pointermove",t)}},stopSelecting:function(t){switch(this._action){case"selecting":var e=this.$el.offset(),i=this.$el.width(),n=this.$el.height(),r=V(this.options.paper.viewport).toLocalPoint(e.left,e.top);r.x-=window.pageXOffset,r.y-=window.pageYOffset;var a=V(this.options.paper.viewport).scale();i/=a.sx,n/=a.sy;var s=this.options.paper.findViewsInArea(g.rect(r.x,r.y,i,n));s.length?(_.each(s,this.createSelectionBox,this),this.$el.addClass("selected")):this.$el.hide(),this.model.reset(_.pluck(s,"model"));break;case"translating":this.options.graph.trigger("batch:stop"),this.trigger("selection-box:pointerup",t);break;default:this.cancelSelection()}delete this._action},cancelSelection:function(){this.$el.hide().empty().removeClass("selected"),this.model.reset([]),this._boxCount=0},destroySelectionBox:function(t){this.$('[data-model="'+t.model.get("id")+'"]').remove(),0===this.$(".selection-box").length&&this.$el.hide().removeClass("selected"),this._boxCount=Math.max(0,this._boxCount-1)},createSelectionBox:function(t){var e=t.getBBox(),i=$("<div/>",{"class":"selection-box","data-model":t.model.get("id")});i.css({left:e.x,top:e.y,width:e.width,height:e.height}),this.$el.append(i),this.$el.addClass("selected").show(),this._boxCount++},updateSelectionBoxes:function(){this._boxCount&&this.$el.hide().removeClass("selected").find(".selection-box").each(_.bind(function(t,e){var i=$(e).remove().attr("data-model"),n=this.options.paper.findViewByModel(this.model.get(i));n&&this.createSelectionBox(n)},this))},mouseupRegister:function(){var t="function"==typeof window.ontouchend?"touchend.selectionView":"mouseup.selectionView";$(document.body).one(t,this.stopSelecting)},remove:function(){Backbone.View.prototype.remove.apply(this,arguments),$(document.body).off(".selectionView")}}),joint.ui.Clipboard=Backbone.Collection.extend({copyElements:function(t,e,i){i=i||{};var n=[],r=[],a={};t.each(function(s){var o=e.getConnectedLinks(s);n=n.concat(_.filter(o,function(e){return t.get(e.get("source").id)&&t.get(e.get("target").id)?!0:!1}));var l=s.clone();i.translate&&l.translate(i.translate.dx||20,i.translate.dy||20),r.push(l),a[s.get("id")]=l.get("id")});var s=_.unique(n);return n=_.map(s,function(t){var e=t.clone(),n=e.get("source"),r=e.get("target");return n.id=a[n.id],r.id=a[r.id],e.set({source:_.clone(n),target:_.clone(r)}),i.translate&&_.each(e.get("vertices"),function(t){t.x+=i.translate.dx||20,t.y+=i.translate.dy||20}),e}),this.reset(r.concat(n)),i.useLocalStorage&&window.localStorage&&localStorage.setItem("joint.ui.Clipboard.cells",JSON.stringify(this.toJSON())),(t.models||[]).concat(s)},pasteCells:function(t,e){e=e||{},e.useLocalStorage&&0===this.length&&window.localStorage&&this.reset(JSON.parse(localStorage.getItem("joint.ui.Clipboard.cells"))),t.trigger("batch:start"),this.each(function(i){i.unset("z"),i instanceof joint.dia.Link&&e.link&&i.set(e.link),t.addCell(i.toJSON())}),t.trigger("batch:stop")},clear:function(){this.reset([]),window.localStorage&&localStorage.removeItem("joint.ui.Clipboard.cells")}});var Handlebars={};(function(t,e){t.VERSION="1.0.0",t.COMPILER_REVISION=4,t.REVISION_CHANGES={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"},t.helpers={},t.partials={};var i=Object.prototype.toString,n="[object Function]",r="[object Object]";t.registerHelper=function(e,n,a){if(i.call(e)===r){if(a||n)throw new t.Exception("Arg not supported with multiple helpers");t.Utils.extend(this.helpers,e)}else a&&(n.not=a),this.helpers[e]=n},t.registerPartial=function(e,n){i.call(e)===r?t.Utils.extend(this.partials,e):this.partials[e]=n},t.registerHelper("helperMissing",function(t){if(2===arguments.length)return e;throw Error("Missing helper: '"+t+"'")}),t.registerHelper("blockHelperMissing",function(e,r){var a=r.inverse||function(){},s=r.fn,o=i.call(e);return o===n&&(e=e.call(this)),e===!0?s(this):e===!1||null==e?a(this):"[object Array]"===o?e.length>0?t.helpers.each(e,r):a(this):s(e)}),t.K=function(){},t.createFrame=Object.create||function(e){t.K.prototype=e;var i=new t.K;return t.K.prototype=null,i},t.logger={DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,methodMap:{0:"debug",1:"info",2:"warn",3:"error"},log:function(e,i){if(e>=t.logger.level){var n=t.logger.methodMap[e];"undefined"!=typeof console&&console[n]&&console[n].call(console,i)}}},t.log=function(e,i){t.logger.log(e,i)},t.registerHelper("each",function(e,r){var a,s=r.fn,o=r.inverse,l=0,c="",h=i.call(e);if(h===n&&(e=e.call(this)),r.data&&(a=t.createFrame(r.data)),e&&"object"==typeof e)if(e instanceof Array)for(var u=e.length;u>l;l++)a&&(a.index=l),c+=s(e[l],{data:a});else for(var p in e)e.hasOwnProperty(p)&&(a&&(a.key=p),c+=s(e[p],{data:a}),l++);return 0===l&&(c=o(this)),c}),t.registerHelper("if",function(e,r){var a=i.call(e);return a===n&&(e=e.call(this)),!e||t.Utils.isEmpty(e)?r.inverse(this):r.fn(this)}),t.registerHelper("unless",function(e,i){return t.helpers["if"].call(this,e,{fn:i.inverse,inverse:i.fn})}),t.registerHelper("with",function(r,a){var s=i.call(r);return s===n&&(r=r.call(this)),t.Utils.isEmpty(r)?e:a.fn(r)}),t.registerHelper("log",function(e,i){var n=i.data&&null!=i.data.level?parseInt(i.data.level,10):1;t.log(n,e)});var a=["description","fileName","lineNumber","message","name","number","stack"];t.Exception=function(){for(var t=Error.prototype.constructor.apply(this,arguments),e=0;a.length>e;e++)this[a[e]]=t[a[e]]},t.Exception.prototype=Error(),t.SafeString=function(t){this.string=t},t.SafeString.prototype.toString=function(){return""+this.string};var s={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},o=/[&<>"'`]/g,l=/[&<>"'`]/,c=function(t){return s[t]||"&amp;"};t.Utils={extend:function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])},escapeExpression:function(e){return e instanceof t.SafeString?""+e:null==e||e===!1?"":(e=""+e,l.test(e)?e.replace(o,c):e)},isEmpty:function(t){return t||0===t?"[object Array]"===i.call(t)&&0===t.length?!0:!1:!0}},t.VM={template:function(e){var i={escapeExpression:t.Utils.escapeExpression,invokePartial:t.VM.invokePartial,programs:[],program:function(e,i,n){var r=this.programs[e];return n?r=t.VM.program(e,i,n):r||(r=this.programs[e]=t.VM.program(e,i)),r},merge:function(e,i){var n=e||i;return e&&i&&(n={},t.Utils.extend(n,i),t.Utils.extend(n,e)),n},programWithDepth:t.VM.programWithDepth,noop:t.VM.noop,compilerInfo:null};return function(n,r){r=r||{};var a=e.call(i,t,n,r.helpers,r.partials,r.data),s=i.compilerInfo||[],o=s[0]||1,l=t.COMPILER_REVISION;if(o!==l){if(l>o){var c=t.REVISION_CHANGES[l],h=t.REVISION_CHANGES[o];throw"Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+c+") or downgrade your runtime to an older version ("+h+")."}throw"Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+s[1]+")."}return a}},programWithDepth:function(t,e,i){var n=Array.prototype.slice.call(arguments,3),r=function(t,r){return r=r||{},e.apply(this,[t,r.data||i].concat(n))};return r.program=t,r.depth=n.length,r},program:function(t,e,i){var n=function(t,n){return n=n||{},e(t,n.data||i)};return n.program=t,n.depth=0,n},noop:function(){return""},invokePartial:function(i,n,r,a,s,o){var l={helpers:a,partials:s,data:o};if(i===e)throw new t.Exception("The partial "+n+" could not be found");if(i instanceof Function)return i(r,l);if(t.compile)return s[n]=t.compile(i,{data:o!==e}),s[n](r,l);throw new t.Exception("The partial "+n+" could not be compiled when running in runtime-only mode")}},t.template=t.VM.template})(Handlebars),this.joint=this.joint||{},this.joint.templates=this.joint.templates||{},this.joint.templates.halo=this.joint.templates.halo||{},this.joint.templates.halo["box.html"]=Handlebars.template(function(t,e,i,n,r){return this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{},'<label class="box"></label>\n'}),this.joint.templates.halo["handle.html"]=Handlebars.template(function(t,e,i,n,r){function a(t){var e="";return e+='style="background-image: url('+h(typeof t===c?t.apply(t):t)+')"'}this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var s,o,l="",c="function",h=this.escapeExpression,u=this,p=i.blockHelperMissing;return l+='<div class="handle ',(s=i.position)?s=s.call(e,{hash:{},data:r}):(s=e.position,s=typeof s===c?s.apply(e):s),l+=h(s)+" ",(s=i.name)?s=s.call(e,{hash:{},data:r}):(s=e.name,s=typeof s===c?s.apply(e):s),l+=h(s)+'" draggable="false" data-action="',(s=i.name)?s=s.call(e,{hash:{},data:r}):(s=e.name,s=typeof s===c?s.apply(e):s),l+=h(s)+'" ',o={hash:{},inverse:u.noop,fn:u.program(1,a,r),data:r},(s=i.icon)?s=s.call(e,o):(s=e.icon,s=typeof s===c?s.apply(e):s),i.icon||(s=p.call(e,s,o)),(s||0===s)&&(l+=s),l+=">\n    ",(s=i.content)?s=s.call(e,{hash:{},data:r}):(s=e.content,s=typeof s===c?s.apply(e):s),(s||0===s)&&(l+=s),l+="\n</div>\n\n"}),joint.ui.Halo=Backbone.View.extend({className:"halo",events:{"mousedown .handle":"onHandlePointerDown","touchstart .handle":"onHandlePointerDown"},options:{tinyTreshold:40,smallTreshold:80,loopLinkPreferredSide:"top",loopLinkWidth:40,boxContent:function(t){var e=_.template("x: <%= x %>, y: <%= y %>, width: <%= width %>, height: <%= height %>, angle: <%= angle %>"),i=t.model.getBBox();return e({x:Math.floor(i.x),y:Math.floor(i.y),width:i.width,height:i.height,angle:Math.floor(t.model.get("angle")||0)})},linkAttributes:{},smoothLinks:void 0,handles:[{name:"resize",position:"se",events:{pointerdown:"startResizing",pointermove:"doResize",pointerup:"stopBatch"}},{name:"remove",position:"nw",events:{pointerdown:"removeElement"}},{name:"clone",position:"n",events:{pointerdown:"startCloning",pointermove:"doClone",pointerup:"stopBatch"}},{name:"link",position:"e",events:{pointerdown:"startLinking",pointermove:"doLink",pointerup:"stopLinking"}},{name:"fork",position:"ne",events:{pointerdown:"startForking",pointermove:"doFork",pointerup:"stopBatch"}},{name:"unlink",position:"w",events:{pointerdown:"unlinkElement"}},{name:"rotate",position:"sw",events:{pointerdown:"startRotating",pointermove:"doRotate",pointerup:"stopBatch"}}]},initialize:function(){_.defaults(this.options,{paper:this.options.cellView.paper,graph:this.options.cellView.paper.model}),_.bindAll(this,"pointermove","pointerup","render","update","remove"),joint.ui.Halo.clear(this.options.paper),this.handles=[],_.each(this.options.handles,this.addHandle,this),this.listenTo(this.options.graph,"reset",this.remove),this.listenTo(this.options.graph,"all",this.update),this.listenTo(this.options.paper,"blank:pointerdown halo:create",this.remove),this.listenTo(this.options.paper,"scale",this.update),$(document.body).on("mousemove touchmove",this.pointermove),$(document).on("mouseup touchend",this.pointerup),this.options.paper.$el.append(this.$el)},render:function(){return this.options.cellView.model.on("remove",this.remove),this.$el.append(joint.templates.halo["box.html"]()),this.renderMagnets(),this.update(),this.$el.addClass("animate"),this.$el.attr("data-type",this.options.cellView.model.get("type")),this.toggleFork(),this},update:function(){if(!(this.options.cellView.model instanceof joint.dia.Link)){if(_.isFunction(this.options.boxContent)){var t=this.$(".box"),e=this.options.boxContent.call(this,this.options.cellView,t[0]);e&&t.html(e)}var i=this.options.cellView.getBBox();this.$el.toggleClass("tiny",i.width<this.options.tinyTreshold&&i.height<this.options.tinyTreshold),this.$el.toggleClass("small",!this.$el.hasClass("tiny")&&i.width<this.options.smallTreshold&&i.height<this.options.smallTreshold),this.$el.css({width:i.width,height:i.height,left:i.x,top:i.y}).show(),this.updateMagnets(),this.toggleUnlink()}},addHandle:function(t){return this.handles.push(t),this.$el.append(joint.templates.halo["handle.html"](t)),_.each(t.events,function(e,i){_.isString(e)?this.on("action:"+t.name+":"+i,this[e],this):this.on("action:"+t.name+":"+i,e)},this),this},removeHandle:function(t){var e=_.findIndex(this.handles,{name:t}),i=this.handles[e];return i&&(_.each(i.events,function(e,i){this.off("action:"+t+":"+i)},this),this.$(".handle."+t).remove(),this.handles.splice(e,1)),this},changeHandle:function(t,e){var i=_.findWhere(this.handles,{name:t});return i&&(this.removeHandle(t),this.addHandle(_.merge({name:t},i,e))),this},onHandlePointerDown:function(t){this._action=$(t.target).closest(".handle").attr("data-action"),this._action&&(this._clientX=t.clientX,this._clientY=t.clientY,this._startClientX=this._clientX,this._startClientY=this._clientY,this.triggerAction(this._action,"pointerdown",t))},triggerAction:function(t,e){var i=["action:"+t+":"+e].concat(_.rest(_.toArray(arguments),2));this.trigger.apply(this,i)},startCloning:function(t){t.preventDefault(),t.stopPropagation(),t=joint.util.normalizeEvent(t),this.options.graph.trigger("batch:start"),this._clone=this.options.cellView.model.clone(),this._clone.unset("z"),this.options.graph.addCell(this._clone,{halo:this.cid})},startLinking:function(t){t.preventDefault(),t.stopPropagation(),t=joint.util.normalizeEvent(t),this.options.graph.trigger("batch:start");var e=this.options.cellView,i=$.data(t.target,"selector"),n=this.options.paper.getDefaultLink(e,i&&e.el.querySelector(i));n.set("source",{id:e.model.id,selector:i}),n.set("target",{x:0,y:0}),n.attr(this.options.linkAttributes),_.isBoolean(this.options.smoothLinks)&&n.set("smooth",this.options.smoothLinks),this.options.graph.addCell(n,{validation:!1,halo:this.cid}),n.set("target",this.options.paper.snapToGrid({x:t.clientX,y:t.clientY})),this._linkView=this.options.paper.findViewByModel(n),this._linkView.startArrowheadMove("target")},startForking:function(t){t.preventDefault(),t.stopPropagation(),t=joint.util.normalizeEvent(t),this.options.graph.trigger("batch:start"),this._clone=this.options.cellView.model.clone(),this._clone.unset("z"),this.options.graph.addCell(this._clone,{halo:this.cid});var e=this.options.paper.getDefaultLink(this.options.cellView);e.set("source",{id:this.options.cellView.model.id}),e.set("target",{id:this._clone.id}),e.attr(this.options.linkAttributes),_.isBoolean(this.options.smoothLinks)&&e.set("smooth",this.options.smoothLinks),this.options.graph.addCell(e,{halo:this.cid})},startResizing:function(t){t.preventDefault(),t.stopPropagation(),t=joint.util.normalizeEvent(t),this.options.graph.trigger("batch:start"),this._flip=[1,0,0,1,1,0,0,1][Math.floor(g.normalizeAngle(this.options.cellView.model.get("angle"))/45)]},startRotating:function(t){t.preventDefault(),t.stopPropagation(),t=joint.util.normalizeEvent(t),this.options.graph.trigger("batch:start");var e=this.options.cellView.getBBox();if(this._center=g.rect(e).center(),t.offsetX===void 0||t.offsetY===void 0){var i=$(t.target).offset();t.offsetX=t.pageX-i.left,t.offsetY=t.pageY-i.top}this._rotationStart=g.point(t.offsetX+t.target.parentNode.offsetLeft,t.offsetY+t.target.parentNode.offsetTop+t.target.parentNode.offsetHeight);var n=this.options.cellView.model.get("angle");this._rotationStartAngle=n||0},doResize:function(t,e,i){var n=this.options.cellView.model.get("size"),r=Math.max(n.width+(this._flip?e:i),1),a=Math.max(n.height+(this._flip?i:e),1);this.options.cellView.model.resize(r,a,{absolute:!0})},doRotate:function(t,e,i,n,r){var a=g.point(this._rotationStart).offset(n,r),s=a.distance(this._center),o=this._center.distance(this._rotationStart),l=this._rotationStart.distance(a),c=(this._center.x-this._rotationStart.x)*(a.y-this._rotationStart.y)-(this._center.y-this._rotationStart.y)*(a.x-this._rotationStart.x),h=Math.acos((s*s+o*o-l*l)/(2*s*o));0>=c&&(h=-h);var u=-g.toDeg(h);u=g.snapToGrid(u,15),this.options.cellView.model.rotate(u+this._rotationStartAngle,!0)},doClone:function(t,e,i){this._clone.translate(e,i)},doFork:function(t,e,i){this._clone.translate(e,i)},doLink:function(t){var e=this.options.paper.snapToGrid({x:t.clientX,y:t.clientY});this._linkView.pointermove(t,e.x,e.y)},stopLinking:function(t){this._linkView.pointerup(t);var e=this._linkView.model.get("source").id,i=this._linkView.model.get("target").id;e&&i&&e===i&&this.makeLoopLink(this._linkView.model),this.stopBatch(),delete this._linkView},pointermove:function(t){if(this._action){t.preventDefault(),t.stopPropagation(),t=joint.util.normalizeEvent(t);var e=this.options.paper.snapToGrid({x:t.clientX,y:t.clientY}),i=this.options.paper.snapToGrid({x:this._clientX,y:this._clientY}),n=e.x-i.x,r=e.y-i.y;this.triggerAction(this._action,"pointermove",t,n,r,t.clientX-this._startClientX,t.clientY-this._startClientY),this._clientX=t.clientX,this._clientY=t.clientY}},pointerup:function(t){this._action&&(this.triggerAction(this._action,"pointerup",t),delete this._action)},stopBatch:function(){this.options.graph.trigger("batch:stop")},remove:function(){Backbone.View.prototype.remove.apply(this,arguments),$(document.body).off("mousemove touchmove",this.pointermove),$(document).off("mouseup touchend",this.pointerup)},removeElement:function(t){t.stopPropagation(),this.options.cellView.model.remove()},unlinkElement:function(t){t.stopPropagation(),this.options.graph.removeLinks(this.options.cellView.model)},toggleUnlink:function(){this.options.graph.getConnectedLinks(this.options.cellView.model).length>0?this.$(".unlink").show():this.$(".unlink").hide()},toggleFork:function(){var t=this.options.cellView.model.clone(),e=this.options.paper.createViewForModel(t);this.options.paper.options.validateConnection(this.options.cellView,null,e,null,"target")||this.$(".fork").hide(),e.remove(),t=null},makeLoopLink:function(t){var e,i,n=this.options.loopLinkWidth,r=this.options.paper.options,a=g.rect({x:0,y:0,width:r.width,height:r.height}),s=V(this.options.cellView.el).bbox(!1,this.options.paper.viewport),o=_.uniq([this.options.loopLinkPreferredSide,"top","bottom","left","right"]),l=_.find(o,function(t){var r,o=0,l=0;switch(t){case"top":r=g.point(s.x+s.width/2,s.y-n),o=n/2;break;case"bottom":r=g.point(s.x+s.width/2,s.y+s.height+n),o=n/2;break;case"left":r=g.point(s.x-n,s.y+s.height/2),l=n/2;break;case"right":r=g.point(s.x+s.width+n,s.y+s.height/2),l=n/2}return e=g.point(r).offset(-o,-l),i=g.point(r).offset(o,l),a.containsPoint(e)&&a.containsPoint(i)},this);l&&t.set("vertices",[e,i])},renderMagnets:function(){this._magnets=[];var t=this.$(".link"),e=this.options.cellView.$('[magnet="true"]');if(this.options.magnetFilter&&(e=_.isFunction(this.options.magnetFilter)?_.filter(e,this.options.magnetFilter):e.filter(this.options.magnetFilter)),t.length&&e.length){var i=t.width(),n=t.height();_.each(e,function(e){var r=e.getBoundingClientRect(),a=t.clone().addClass("halo-magnet").css({width:Math.min(r.width,i),height:Math.min(r.height,n),"background-size":"contain"}).data("selector",this.options.cellView.getSelector(e)).appendTo(this.$el);this._magnets.push({$halo:a,el:e})},this)}"false"==this.options.cellView.$el.attr("magnet")&&(t.hide(),this.$(".fork").hide())},updateMagnets:function(){if(this._magnets.length){var t=this.el.getBoundingClientRect();_.each(this._magnets,function(e){var i=e.el.getBoundingClientRect();e.$halo.css({left:i.left-t.left+(i.width-e.$halo.width())/2,top:i.top-t.top+(i.height-e.$halo.height())/2})},this)}}},{clear:function(t){t.trigger("halo:create")}});var Handlebars={};(function(t,e){t.VERSION="1.0.0",t.COMPILER_REVISION=4,t.REVISION_CHANGES={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"},t.helpers={},t.partials={};var i=Object.prototype.toString,n="[object Function]",r="[object Object]";t.registerHelper=function(e,n,a){if(i.call(e)===r){if(a||n)throw new t.Exception("Arg not supported with multiple helpers");t.Utils.extend(this.helpers,e)}else a&&(n.not=a),this.helpers[e]=n},t.registerPartial=function(e,n){i.call(e)===r?t.Utils.extend(this.partials,e):this.partials[e]=n},t.registerHelper("helperMissing",function(t){if(2===arguments.length)return e;throw Error("Missing helper: '"+t+"'")}),t.registerHelper("blockHelperMissing",function(e,r){var a=r.inverse||function(){},s=r.fn,o=i.call(e);return o===n&&(e=e.call(this)),e===!0?s(this):e===!1||null==e?a(this):"[object Array]"===o?e.length>0?t.helpers.each(e,r):a(this):s(e)}),t.K=function(){},t.createFrame=Object.create||function(e){t.K.prototype=e;var i=new t.K;return t.K.prototype=null,i},t.logger={DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,methodMap:{0:"debug",1:"info",2:"warn",3:"error"},log:function(e,i){if(e>=t.logger.level){var n=t.logger.methodMap[e];"undefined"!=typeof console&&console[n]&&console[n].call(console,i)}}},t.log=function(e,i){t.logger.log(e,i)},t.registerHelper("each",function(e,r){var a,s=r.fn,o=r.inverse,l=0,c="",h=i.call(e);if(h===n&&(e=e.call(this)),r.data&&(a=t.createFrame(r.data)),e&&"object"==typeof e)if(e instanceof Array)for(var u=e.length;u>l;l++)a&&(a.index=l),c+=s(e[l],{data:a});else for(var p in e)e.hasOwnProperty(p)&&(a&&(a.key=p),c+=s(e[p],{data:a}),l++);return 0===l&&(c=o(this)),c}),t.registerHelper("if",function(e,r){var a=i.call(e);return a===n&&(e=e.call(this)),!e||t.Utils.isEmpty(e)?r.inverse(this):r.fn(this)}),t.registerHelper("unless",function(e,i){return t.helpers["if"].call(this,e,{fn:i.inverse,inverse:i.fn})}),t.registerHelper("with",function(r,a){var s=i.call(r);return s===n&&(r=r.call(this)),t.Utils.isEmpty(r)?e:a.fn(r)}),t.registerHelper("log",function(e,i){var n=i.data&&null!=i.data.level?parseInt(i.data.level,10):1;t.log(n,e)});var a=["description","fileName","lineNumber","message","name","number","stack"];t.Exception=function(){for(var t=Error.prototype.constructor.apply(this,arguments),e=0;a.length>e;e++)this[a[e]]=t[a[e]]},t.Exception.prototype=Error(),t.SafeString=function(t){this.string=t},t.SafeString.prototype.toString=function(){return""+this.string};var s={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},o=/[&<>"'`]/g,l=/[&<>"'`]/,c=function(t){return s[t]||"&amp;"};t.Utils={extend:function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])},escapeExpression:function(e){return e instanceof t.SafeString?""+e:null==e||e===!1?"":(e=""+e,l.test(e)?e.replace(o,c):e)},isEmpty:function(t){return t||0===t?"[object Array]"===i.call(t)&&0===t.length?!0:!1:!0}},t.VM={template:function(e){var i={escapeExpression:t.Utils.escapeExpression,invokePartial:t.VM.invokePartial,programs:[],program:function(e,i,n){var r=this.programs[e];return n?r=t.VM.program(e,i,n):r||(r=this.programs[e]=t.VM.program(e,i)),r},merge:function(e,i){var n=e||i;return e&&i&&(n={},t.Utils.extend(n,i),t.Utils.extend(n,e)),n},programWithDepth:t.VM.programWithDepth,noop:t.VM.noop,compilerInfo:null};return function(n,r){r=r||{};var a=e.call(i,t,n,r.helpers,r.partials,r.data),s=i.compilerInfo||[],o=s[0]||1,l=t.COMPILER_REVISION;if(o!==l){if(l>o){var c=t.REVISION_CHANGES[l],h=t.REVISION_CHANGES[o];throw"Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+c+") or downgrade your runtime to an older version ("+h+")."}throw"Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+s[1]+")."}return a}},programWithDepth:function(t,e,i){var n=Array.prototype.slice.call(arguments,3),r=function(t,r){return r=r||{},e.apply(this,[t,r.data||i].concat(n))};return r.program=t,r.depth=n.length,r},program:function(t,e,i){var n=function(t,n){return n=n||{},e(t,n.data||i)};return n.program=t,n.depth=0,n},noop:function(){return""},invokePartial:function(i,n,r,a,s,o){var l={helpers:a,partials:s,data:o};if(i===e)throw new t.Exception("The partial "+n+" could not be found");if(i instanceof Function)return i(r,l);if(t.compile)return s[n]=t.compile(i,{data:o!==e}),s[n](r,l);throw new t.Exception("The partial "+n+" could not be compiled when running in runtime-only mode")}},t.template=t.VM.template})(Handlebars),this.joint=this.joint||{},this.joint.templates=this.joint.templates||{},this.joint.templates.stencil=this.joint.templates.stencil||{},this.joint.templates.stencil["elements.html"]=Handlebars.template(function(t,e,i,n,r){return this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{},'<div class="elements"></div>\n'}),this.joint.templates.stencil["group.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+='<div class="group">\n    <h3 class="group-label">',(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+"</h3>\n</div>\n"}),this.joint.templates.stencil["stencil.html"]=Handlebars.template(function(t,e,i,n,r){return this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{},'<div class="stencil-paper-drag"></div>\n'}),joint.ui.Stencil=Backbone.View.extend({className:"stencil",events:{"click .group-label":"onGroupLabelClick","touchstart .group-label":"onGroupLabelClick"},options:{width:200,height:800},initialize:function(){this.graphs={},this.papers={},$(document.body).on("mousemove touchmove",_.bind(this.onDrag,this)),$(document.body).on("mouseup touchend",_.bind(this.onDragEnd,this))},render:function(){this.$el.html(joint.templates.stencil["stencil.html"](this.template));var t={width:this.options.width,height:this.options.height,interactive:!1};if(this.options.groups){var e=_.sortBy(_.pairs(this.options.groups),function(t){return t[1].index});_.each(e,function(e){var i=e[0],n=e[1],r=$(joint.templates.stencil["group.html"]({label:n.label||i}));r.attr("data-name",i),n.closed&&r.addClass("closed"),r.append($(joint.templates.stencil["elements.html"]())),this.$el.append(r);var a=new joint.dia.Graph;this.graphs[i]=a;var s=new joint.dia.Paper(_.extend({},t,{el:r.find(".elements"),model:a,width:n.width||t.width,height:n.height||t.height}));this.papers[i]=s},this)}else{this.$el.append($(joint.templates.stencil["elements.html"]()));var i=new joint.dia.Graph;this.graphs.__default__=i;var n=new joint.dia.Paper(_.extend(t,{el:this.$(".elements"),model:i}));this.papers.__default__=n}return this._graphDrag=new joint.dia.Graph,this._paperDrag=new joint.dia.Paper({el:this.$(".stencil-paper-drag"),width:1,height:1,model:this._graphDrag}),_.each(this.papers,function(t){t.on("cell:pointerdown",this.onDragStart,this)},this),this},load:function(t,e){var i=this.graphs[e||"__default__"];if(!i)throw Error("Stencil: group "+e+" does not exist.");i.resetCells(t);var n=this.options.height;e&&this.options.groups[e]&&(n=this.options.groups[e].height),n||this.papers[e||"__default__"].fitToContent(1,1,this.options.paperPadding||10)},getGraph:function(t){return this.graphs[t||"__default__"]},getPaper:function(t){return this.papers[t||"__default__"]},onDragStart:function(t,e){this.$el.addClass("dragging"),this._paperDrag.$el.addClass("dragging"),$(document.body).append(this._paperDrag.$el),this._clone=t.model.clone(),this._cloneBbox=t.getBBox();var i=5,n=g.point(this._cloneBbox.x-this._clone.get("position").x,this._cloneBbox.y-this._clone.get("position").y);this._clone.set("position",{x:-n.x+i,y:-n.y+i}),this._graphDrag.addCell(this._clone),this._paperDrag.setDimensions(this._cloneBbox.width+2*i,this._cloneBbox.height+2*i);var r=document.body.scrollTop||document.documentElement.scrollTop;this._paperDrag.$el.offset({left:e.clientX-this._cloneBbox.width/2,top:e.clientY+r-this._cloneBbox.height/2})},onDrag:function(t){if(t=joint.util.normalizeEvent(t),this._clone){var e=document.body.scrollTop||document.documentElement.scrollTop;this._paperDrag.$el.offset({left:t.clientX-this._cloneBbox.width/2,top:t.clientY+e-this._cloneBbox.height/2})}},onDragEnd:function(t){t=joint.util.normalizeEvent(t),this._clone&&this._cloneBbox&&(this.drop(t,this._clone.clone(),this._cloneBbox),this.$el.append(this._paperDrag.$el),this.$el.removeClass("dragging"),this._paperDrag.$el.removeClass("dragging"),this._clone.remove(),this._clone=void 0)
+},drop:function(t,e,i){var n=this.options.paper,r=this.options.graph,a=n.$el.offset(),s=document.body.scrollTop||document.documentElement.scrollTop,o=document.body.scrollLeft||document.documentElement.scrollLeft,l=g.rect(a.left+parseInt(n.$el.css("border-left-width"),10)-o,a.top+parseInt(n.$el.css("border-top-width"),10)-s,n.$el.innerWidth(),n.$el.innerHeight()),c=n.svg.createSVGPoint();if(c.x=t.clientX,c.y=t.clientY,l.containsPoint(c)){var h=V("rect",{width:n.options.width,height:n.options.height,x:0,y:0,opacity:0});V(n.svg).prepend(h);var u=$(n.svg).offset();h.remove(),c.x+=o-u.left,c.y+=s-u.top;var p=c.matrixTransform(n.viewport.getCTM().inverse()),d=e.getBBox();p.x+=d.x-i.width/2,p.y+=d.y-i.height/2,e.set("position",{x:g.snapToGrid(p.x,n.options.gridSize),y:g.snapToGrid(p.y,n.options.gridSize)}),e.unset("z"),r.addCell(e,{stencil:this.cid})}},onGroupLabelClick:function(t){t.preventDefault();var e=$(t.target).closest(".group");this.toggleGroup(e.data("name"))},toggleGroup:function(t){this.$('.group[data-name="'+t+'"]').toggleClass("closed")},closeGroup:function(t){this.$('.group[data-name="'+t+'"]').addClass("closed")},openGroup:function(t){this.$('.group[data-name="'+t+'"]').removeClass("closed")},closeGroups:function(){this.$(".group").addClass("closed")},openGroups:function(){this.$(".group").removeClass("closed")}});var Handlebars={};(function(t,e){t.VERSION="1.0.0",t.COMPILER_REVISION=4,t.REVISION_CHANGES={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"},t.helpers={},t.partials={};var i=Object.prototype.toString,n="[object Function]",r="[object Object]";t.registerHelper=function(e,n,a){if(i.call(e)===r){if(a||n)throw new t.Exception("Arg not supported with multiple helpers");t.Utils.extend(this.helpers,e)}else a&&(n.not=a),this.helpers[e]=n},t.registerPartial=function(e,n){i.call(e)===r?t.Utils.extend(this.partials,e):this.partials[e]=n},t.registerHelper("helperMissing",function(t){if(2===arguments.length)return e;throw Error("Missing helper: '"+t+"'")}),t.registerHelper("blockHelperMissing",function(e,r){var a=r.inverse||function(){},s=r.fn,o=i.call(e);return o===n&&(e=e.call(this)),e===!0?s(this):e===!1||null==e?a(this):"[object Array]"===o?e.length>0?t.helpers.each(e,r):a(this):s(e)}),t.K=function(){},t.createFrame=Object.create||function(e){t.K.prototype=e;var i=new t.K;return t.K.prototype=null,i},t.logger={DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,methodMap:{0:"debug",1:"info",2:"warn",3:"error"},log:function(e,i){if(e>=t.logger.level){var n=t.logger.methodMap[e];"undefined"!=typeof console&&console[n]&&console[n].call(console,i)}}},t.log=function(e,i){t.logger.log(e,i)},t.registerHelper("each",function(e,r){var a,s=r.fn,o=r.inverse,l=0,c="",h=i.call(e);if(h===n&&(e=e.call(this)),r.data&&(a=t.createFrame(r.data)),e&&"object"==typeof e)if(e instanceof Array)for(var u=e.length;u>l;l++)a&&(a.index=l),c+=s(e[l],{data:a});else for(var p in e)e.hasOwnProperty(p)&&(a&&(a.key=p),c+=s(e[p],{data:a}),l++);return 0===l&&(c=o(this)),c}),t.registerHelper("if",function(e,r){var a=i.call(e);return a===n&&(e=e.call(this)),!e||t.Utils.isEmpty(e)?r.inverse(this):r.fn(this)}),t.registerHelper("unless",function(e,i){return t.helpers["if"].call(this,e,{fn:i.inverse,inverse:i.fn})}),t.registerHelper("with",function(r,a){var s=i.call(r);return s===n&&(r=r.call(this)),t.Utils.isEmpty(r)?e:a.fn(r)}),t.registerHelper("log",function(e,i){var n=i.data&&null!=i.data.level?parseInt(i.data.level,10):1;t.log(n,e)});var a=["description","fileName","lineNumber","message","name","number","stack"];t.Exception=function(){for(var t=Error.prototype.constructor.apply(this,arguments),e=0;a.length>e;e++)this[a[e]]=t[a[e]]},t.Exception.prototype=Error(),t.SafeString=function(t){this.string=t},t.SafeString.prototype.toString=function(){return""+this.string};var s={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},o=/[&<>"'`]/g,l=/[&<>"'`]/,c=function(t){return s[t]||"&amp;"};t.Utils={extend:function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])},escapeExpression:function(e){return e instanceof t.SafeString?""+e:null==e||e===!1?"":(e=""+e,l.test(e)?e.replace(o,c):e)},isEmpty:function(t){return t||0===t?"[object Array]"===i.call(t)&&0===t.length?!0:!1:!0}},t.VM={template:function(e){var i={escapeExpression:t.Utils.escapeExpression,invokePartial:t.VM.invokePartial,programs:[],program:function(e,i,n){var r=this.programs[e];return n?r=t.VM.program(e,i,n):r||(r=this.programs[e]=t.VM.program(e,i)),r},merge:function(e,i){var n=e||i;return e&&i&&(n={},t.Utils.extend(n,i),t.Utils.extend(n,e)),n},programWithDepth:t.VM.programWithDepth,noop:t.VM.noop,compilerInfo:null};return function(n,r){r=r||{};var a=e.call(i,t,n,r.helpers,r.partials,r.data),s=i.compilerInfo||[],o=s[0]||1,l=t.COMPILER_REVISION;if(o!==l){if(l>o){var c=t.REVISION_CHANGES[l],h=t.REVISION_CHANGES[o];throw"Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+c+") or downgrade your runtime to an older version ("+h+")."}throw"Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+s[1]+")."}return a}},programWithDepth:function(t,e,i){var n=Array.prototype.slice.call(arguments,3),r=function(t,r){return r=r||{},e.apply(this,[t,r.data||i].concat(n))};return r.program=t,r.depth=n.length,r},program:function(t,e,i){var n=function(t,n){return n=n||{},e(t,n.data||i)};return n.program=t,n.depth=0,n},noop:function(){return""},invokePartial:function(i,n,r,a,s,o){var l={helpers:a,partials:s,data:o};if(i===e)throw new t.Exception("The partial "+n+" could not be found");if(i instanceof Function)return i(r,l);if(t.compile)return s[n]=t.compile(i,{data:o!==e}),s[n](r,l);throw new t.Exception("The partial "+n+" could not be compiled when running in runtime-only mode")}},t.template=t.VM.template})(Handlebars),this.joint=this.joint||{},this.joint.templates=this.joint.templates||{},this.joint.templates.inspector=this.joint.templates.inspector||{},this.joint.templates.inspector["color.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+="<label>",(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+':</label>\n<input type="color" class="color" data-type="',(a=i.type)?a=a.call(e,{hash:{},data:r}):(a=e.type,a=typeof a===o?a.apply(e):a),s+=l(a)+'" data-attribute="',(a=i.attribute)?a=a.call(e,{hash:{},data:r}):(a=e.attribute,a=typeof a===o?a.apply(e):a),s+=l(a)+'" value="',(a=i.value)?a=a.call(e,{hash:{},data:r}):(a=e.value,a=typeof a===o?a.apply(e):a),s+=l(a)+'" />\n'}),this.joint.templates.inspector["group.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+='<div class="group">\n    <h3 class="group-label">',(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+"</h3>\n</div>\n"}),this.joint.templates.inspector["list-item.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+='<div class="list-item" data-index="',(a=i.index)?a=a.call(e,{hash:{},data:r}):(a=e.index,a=typeof a===o?a.apply(e):a),s+=l(a)+'">\n    <button class="btn-list-del">-</button>\n</div>\n'}),this.joint.templates.inspector["list.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+="<label>",(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+':</label>\n<div class="list" data-type="',(a=i.type)?a=a.call(e,{hash:{},data:r}):(a=e.type,a=typeof a===o?a.apply(e):a),s+=l(a)+'" data-attribute="',(a=i.attribute)?a=a.call(e,{hash:{},data:r}):(a=e.attribute,a=typeof a===o?a.apply(e):a),s+=l(a)+'">\n    <button class="btn-list-add">+</button>\n    <div class="list-items">\n    </div>\n</div>\n'}),this.joint.templates.inspector["number.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+="<label>",(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+':</label>\n<input type="number" class="number" data-type="',(a=i.type)?a=a.call(e,{hash:{},data:r}):(a=e.type,a=typeof a===o?a.apply(e):a),s+=l(a)+'" data-attribute="',(a=i.attribute)?a=a.call(e,{hash:{},data:r}):(a=e.attribute,a=typeof a===o?a.apply(e):a),s+=l(a)+'" value="',(a=i.value)?a=a.call(e,{hash:{},data:r}):(a=e.value,a=typeof a===o?a.apply(e):a),s+=l(a)+'"/>\n'}),this.joint.templates.inspector["object-property.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+='<div class="object-property" data-property="',(a=i.property)?a=a.call(e,{hash:{},data:r}):(a=e.property,a=typeof a===o?a.apply(e):a),s+=l(a)+'">\n</div>\n'}),this.joint.templates.inspector["object.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+="<label>",(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+':</label>\n<div class="object" data-type="',(a=i.type)?a=a.call(e,{hash:{},data:r}):(a=e.type,a=typeof a===o?a.apply(e):a),s+=l(a)+'" data-attribute="',(a=i.attribute)?a=a.call(e,{hash:{},data:r}):(a=e.attribute,a=typeof a===o?a.apply(e):a),s+=l(a)+'">\n    <div class="object-properties"></div>\n</div>\n'}),this.joint.templates.inspector["range.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s,o="",l="function",c=this.escapeExpression;return o+="<form onchange=\"$(this).find('output').text(range.value)\">\n    <label>",(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===l?a.apply(e):a),o+=c(a)+": (<output>",(a=i.value)?a=a.call(e,{hash:{},data:r}):(a=e.value,a=typeof a===l?a.apply(e):a),o+=c(a)+"</output>"+c((a=e.options,a=null==a||a===!1?a:a.unit,typeof a===l?a.apply(e):a))+')</label>\n    <input type="range" class="range" name="range" data-type="',(s=i.type)?s=s.call(e,{hash:{},data:r}):(s=e.type,s=typeof s===l?s.apply(e):s),o+=c(s)+'" data-attribute="',(s=i.attribute)?s=s.call(e,{hash:{},data:r}):(s=e.attribute,s=typeof s===l?s.apply(e):s),o+=c(s)+'" min="'+c((a=e.options,a=null==a||a===!1?a:a.min,typeof a===l?a.apply(e):a))+'" max="'+c((a=e.options,a=null==a||a===!1?a:a.max,typeof a===l?a.apply(e):a))+'" step="'+c((a=e.options,a=null==a||a===!1?a:a.step,typeof a===l?a.apply(e):a))+'" value="',(s=i.value)?s=s.call(e,{hash:{},data:r}):(s=e.value,s=typeof s===l?s.apply(e):s),o+=c(s)+'"/>\n</form>\n'}),this.joint.templates.inspector["select.html"]=Handlebars.template(function(t,e,i,n,r){function a(t){var e,i="";return i+=' multiple size="'+p((e=t.options,e=null==e||e===!1?e:e.options,e=null==e||e===!1?e:e.length,typeof e===u?e.apply(t):e))+'" '}function s(t,e,n){var r,a,s,l="";return l+='\n    <option val="'+p(typeof t===u?t.apply(t):t)+'" ',s={hash:{},inverse:g.noop,fn:g.program(4,o,e),data:e},r=i["is-or-contains"]||t["is-or-contains"],a=r?r.call(t,t,n.value,s):d.call(t,"is-or-contains",t,n.value,s),(a||0===a)&&(l+=a),l+=">"+p(typeof t===u?t.apply(t):t)+"</option>\n    "}function o(){return" selected "}this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var l,c,h="",u="function",p=this.escapeExpression,g=this,d=i.helperMissing;return h+="<label>",(l=i.label)?l=l.call(e,{hash:{},data:r}):(l=e.label,l=typeof l===u?l.apply(e):l),h+=p(l)+':</label>\n<select class="select" data-type="',(l=i.type)?l=l.call(e,{hash:{},data:r}):(l=e.type,l=typeof l===u?l.apply(e):l),h+=p(l)+'" data-attribute="',(l=i.attribute)?l=l.call(e,{hash:{},data:r}):(l=e.attribute,l=typeof l===u?l.apply(e):l),h+=p(l)+'" value="',(l=i.value)?l=l.call(e,{hash:{},data:r}):(l=e.value,l=typeof l===u?l.apply(e):l),h+=p(l)+'" ',c=i["if"].call(e,(l=e.options,null==l||l===!1?l:l.multiple),{hash:{},inverse:g.noop,fn:g.program(1,a,r),data:r}),(c||0===c)&&(h+=c),h+=">\n    ",c=i.each.call(e,(l=e.options,null==l||l===!1?l:l.items),{hash:{},inverse:g.noop,fn:g.programWithDepth(3,s,r,e),data:r}),(c||0===c)&&(h+=c),h+="\n</select>\n"}),this.joint.templates.inspector["text.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+="<label>",(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+':</label>\n<input type="text" class="text" data-type="',(a=i.type)?a=a.call(e,{hash:{},data:r}):(a=e.type,a=typeof a===o?a.apply(e):a),s+=l(a)+'" data-attribute="',(a=i.attribute)?a=a.call(e,{hash:{},data:r}):(a=e.attribute,a=typeof a===o?a.apply(e):a),s+=l(a)+'" value="',(a=i.value)?a=a.call(e,{hash:{},data:r}):(a=e.value,a=typeof a===o?a.apply(e):a),s+=l(a)+'" />\n'}),this.joint.templates.inspector["textarea.html"]=Handlebars.template(function(t,e,i,n,r){this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var a,s="",o="function",l=this.escapeExpression;return s+="<label>",(a=i.label)?a=a.call(e,{hash:{},data:r}):(a=e.label,a=typeof a===o?a.apply(e):a),s+=l(a)+':</label>\n<textarea class="textarea" data-type="',(a=i.type)?a=a.call(e,{hash:{},data:r}):(a=e.type,a=typeof a===o?a.apply(e):a),s+=l(a)+'" data-attribute="',(a=i.attribute)?a=a.call(e,{hash:{},data:r}):(a=e.attribute,a=typeof a===o?a.apply(e):a),s+=l(a)+'">',(a=i.value)?a=a.call(e,{hash:{},data:r}):(a=e.value,a=typeof a===o?a.apply(e):a),s+=l(a)+"</textarea>\n"}),this.joint.templates.inspector["toggle.html"]=Handlebars.template(function(t,e,i,n,r){function a(){return" checked "}this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{};var s,o="",l="function",c=this.escapeExpression,h=this;return o+="<label>",(s=i.label)?s=s.call(e,{hash:{},data:r}):(s=e.label,s=typeof s===l?s.apply(e):s),o+=c(s)+':</label>\n<div class="toggle">\n    <input type="checkbox" data-type="',(s=i.type)?s=s.call(e,{hash:{},data:r}):(s=e.type,s=typeof s===l?s.apply(e):s),o+=c(s)+'" data-attribute="',(s=i.attribute)?s=s.call(e,{hash:{},data:r}):(s=e.attribute,s=typeof s===l?s.apply(e):s),o+=c(s)+'" ',s=i["if"].call(e,e.value,{hash:{},inverse:h.noop,fn:h.program(1,a,r),data:r}),(s||0===s)&&(o+=s),o+=" />\n    <span><i></i></span>\n</div>\n"}),Handlebars.registerHelper("is",function(t,e,i){return t==e?i.fn(this):i.inverse(this)}),Handlebars.registerHelper("is-or-contains",function(t,e,i){return(_.isArray(e)?_.contains(e,t):t==e)?i.fn(this):i.inverse(this)}),Handlebars.registerPartial("list-item",joint.templates.inspector["list-item.html"]),joint.ui.Inspector=Backbone.View.extend({className:"inspector",options:{cellView:void 0,cell:void 0,live:!0},events:{mousedown:"startBatchCommand",change:"onChangeInput","click .group-label":"onGroupLabelClick","click .btn-list-add":"addListItem","click .btn-list-del":"deleteListItem"},initialize:function(){this.options.groups=this.options.groups||{},_.bindAll(this,"stopBatchCommand"),$(document).on("mouseup",this.stopBatchCommand),this.flatAttributes=joint.util.flattenObject(this.options.inputs,"/",function(t){return t.type}),this._when={},this._bound={};var t=_.map(this.flatAttributes,function(t,e){return t.when&&t.when.eq&&_.each(t.when.eq,function(t,i){var n={value:t,path:e};(this._when[i]||(this._when[i]=[])).push(n)},this),t.when&&t.when.regex&&_.each(t.when.regex,function(t,i){var n={regex:t,path:e};(this._when[i]||(this._when[i]=[])).push(n)},this),"select"==t.type&&_.isString(t.options)&&(this._bound[e]=t.options),t.path=e,t},this);this.groupedFlatAttributes=_.sortBy(t,function(t){var e=this.options.groups[t.group];return e?"a"+e.index+"b"+t.index:Number.MAX_VALUE},this),this.on("render",function(){this._byPath={},_.each(this.$("[data-attribute]"),function(t){var e=$(t);this._byPath[e.attr("data-attribute")]=e},this)},this),this.listenTo(this.getModel(),"all",this.onCellChange,this)},getModel:function(){return this.options.cell||this.options.cellView.model},onCellChange:function(t,e,i,n){if(n=n||{},!n["inspector_"+this.cid])switch(t){case"remove":this.remove();break;case"change:position":this.updateInputPosition();break;case"change:size":this.updateInputSize();break;case"change:angle":this.updateInputAngle();break;case"change:source":case"change:target":break;default:var r="change:";t.slice(0,r.length)===r&&this.render()}},render:function(){this.$el.empty();var t,e,i=[];return _.each(this.groupedFlatAttributes,function(n){if(t!==n.group){var r=this.options.groups[n.group],a=r?r.label||n.group:n.group;e=$(joint.templates.inspector["group.html"]({label:a})),e.attr("data-name",n.group),r&&r.closed&&e.addClass("closed"),i.push(e)}this.renderTemplate(e,n,n.path),t=n.group},this),this.$el.append(i),this.trigger("render"),this},getCellAttributeValue:function(t,e){var i=this.getModel(),n=joint.util.getByPath(i.attributes,t,"/");if(!e)return n;if(_.isUndefined(n)&&!_.isUndefined(e.defaultValue)&&(n=e.defaultValue),e.valueRegExp){if(_.isUndefined(n))throw Error("Inspector: defaultValue must be present when valueRegExp is used.");var r=n.match(RegExp(e.valueRegExp));n=r&&r[2]}return n},guard:function(t){var e=!0;if(t.when&&t.when.eq){var i=_.find(t.when.eq,function(t,e){var i=this.getCellAttributeValue(e);return i!==t?!0:!1},this);i&&(e=!1)}if(t.when&&t.when.regex){var i=_.find(t.when.regex,function(t,e){var i=this.getCellAttributeValue(e);return RegExp(t).test(i)?!1:!0},this);i&&(e=!1)}return!e},resolveBindings:function(t){switch(t.type){case"select":var e=t.options;t.items=_.isString(e)?joint.util.getByPath(this.getModel().attributes,e,"/"):e}},updateBindings:function(t){var e=_.reduce(this._bound,function(e,i,n){return t.indexOf(i)||e.push(n),e},[]);_.isEmpty(e)||(_.each(e,function(t){this.renderTemplate(null,this.flatAttributes[t],t,{replace:!0})},this),this.trigger("render"))},renderTemplate:function(t,e,i,n){t=t||this.$el,n=n||{},this.resolveBindings(e);var r=this.getCellAttributeValue(i,e),a=joint.templates.inspector[e.type+".html"]({options:e,type:e.type,label:e.label||i,attribute:i,value:r}),s=$('<div class="field"></div>').attr("data-field",i),o=$(a);if(s.append(o),this.guard(e)&&s.addClass("hidden"),_.each(e.attrs,function(t,e){s.find(e).addBack().filter(e).attr(t)}),"list"===e.type)_.each(r,function(t,n){var r=$(joint.templates.inspector["list-item.html"]({index:n}));this.renderTemplate(r,e.item,i+"/"+n),o.children(".list-items").append(r)},this);else if("object"===e.type){e.flatAttributes=joint.util.flattenObject(e.properties,"/",function(t){return t.type});var l=_.map(e.flatAttributes,function(t,e){return t.path=e,t});l=_.sortBy(l,function(t){return t.index}),_.each(l,function(t){var e=$(joint.templates.inspector["object-property.html"]({property:t.path}));this.renderTemplate(e,t,i+"/"+t.path),o.children(".object-properties").append(e)},this)}n.replace?t.find("[data-field="+i+"]").replaceWith(s):t.append(s)},updateInputPosition:function(){var t=this._byPath["position/x"],e=this._byPath["position/y"],i=this.getModel().get("position");t&&t.val(i.x),e&&e.val(i.y)},updateInputSize:function(){var t=this._byPath["size/width"],e=this._byPath["size/height"],i=this.getModel().get("size");t&&t.val(i.width),e&&e.val(i.height)},updateInputAngle:function(){var t=this._byPath.angle,e=this.getModel().get("angle");t&&t.val(e)},onChangeInput:function(t){var e=$(t.target),i=e.attr("data-attribute");this.options.live&&this.updateCell(e,i);var n=e.attr("data-type"),r=this.parse(n,e.val(),e[0]),a=this._when[i];this.trigger("change:"+i,r,e[0]),a&&_.each(a,function(t){var e=this._byPath[t.path],i=e.closest(".field"),n=!1;t.regex&&RegExp(t.regex).test(r)?n=!0:r===t.value&&(n=!0),n?i.removeClass("hidden"):i.addClass("hidden")},this)},getOptions:function(t){if(0===t.length)return void 0;var e=t.attr("data-attribute");t.attr("data-type");var i=this.flatAttributes[e];if(!i){var n=t.parent().closest("[data-attribute]"),r=n.attr("data-attribute");i=this.getOptions(n);var a=e.replace(r+"/",""),s=i;i=s.item||s.flatAttributes[a],i.parent=s}return i},updateCell:function(t,e){var i=this.getModel(),n={};t?n[e]=t:n=this._byPath,_.each(n,function(t,e){if(!t.hasClass("hidden")){var n,r,a=t.attr("data-type");switch(a){case"list":joint.util.unsetByPath(i.attributes,e,"/"),this.setProperty(e,[]);break;case"object":break;default:if(n=this.parse(a,t.val(),t[0]),r=this.getOptions(t),r.valueRegExp){var s=joint.util.getByPath(i.attributes,e,"/")||r.defaultValue;n=s.replace(RegExp(r.valueRegExp),"$1"+n+"$3")}this.setProperty(e,n)}this.updateBindings(e)}},this)},setProperty:function(t,e){var i,n=this.getModel(),r=t.split("/"),a=r[0],s={};if(s["inspector_"+this.cid]=!0,r.length>1){var o=_.cloneDeep(n.attributes);i=joint.util.getByPath(o,t,"/");var l={},c=l,h=a;_.each(_.rest(r),function(t){c=c[h]=_.isFinite(Number(t))?[]:{},h=t}),l=joint.util.setByPath(l,t,e,"/"),_.merge(o,l),n.set(a,o[a],s)}else i=n.get(a),n.set(a,e,s)},parse:function(t,e,i){switch(t){case"number":e=parseFloat(e);break;case"toggle":e=i.checked;break;default:e=e}return e},startBatchCommand:function(){this.getModel().trigger("batch:start")},stopBatchCommand:function(){this.getModel().trigger("batch:stop")},addListItem:function(t){var e=$(t.target),i=e.closest("[data-attribute]"),n=i.attr("data-attribute"),r=this.getOptions(i),a=i.children(".list-items").children(".list-item").last(),s=0===a.length?-1:parseInt(a.attr("data-index"),10),o=s+1,l=$(joint.templates.inspector["list-item.html"]({index:o}));this.renderTemplate(l,r.item,n+"/"+o),e.parent().children(".list-items").append(l),l.find("input").focus(),this.trigger("render"),this.options.live&&this.updateCell()},deleteListItem:function(t){var e=$(t.target).closest(".list-item");e.nextAll(".list-item").each(function(){var t=parseInt($(this).attr("data-index"),10),e=t-1;$(this).find("[data-attribute]").each(function(){$(this).attr("data-attribute",$(this).attr("data-attribute").replace("/"+t,"/"+e))}),$(this).attr("data-index",e)}),e.remove(),this.trigger("render"),this.options.live&&this.updateCell()},remove:function(){return $(document).off("mouseup",this.stopBatchCommand),Backbone.View.prototype.remove.apply(this,arguments)},onGroupLabelClick:function(t){t.preventDefault();var e=$(t.target).closest(".group");this.toggleGroup(e.data("name"))},toggleGroup:function(t){this.$('.group[data-name="'+t+'"]').toggleClass("closed")},closeGroup:function(t){this.$('.group[data-name="'+t+'"]').addClass("closed")},openGroup:function(t){this.$('.group[data-name="'+t+'"]').removeClass("closed")},closeGroups:function(){this.$(".group").addClass("closed")},openGroups:function(){this.$(".group").removeClass("closed")}});var Handlebars={};(function(t,e){t.VERSION="1.0.0",t.COMPILER_REVISION=4,t.REVISION_CHANGES={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"},t.helpers={},t.partials={};var i=Object.prototype.toString,n="[object Function]",r="[object Object]";t.registerHelper=function(e,n,a){if(i.call(e)===r){if(a||n)throw new t.Exception("Arg not supported with multiple helpers");t.Utils.extend(this.helpers,e)}else a&&(n.not=a),this.helpers[e]=n},t.registerPartial=function(e,n){i.call(e)===r?t.Utils.extend(this.partials,e):this.partials[e]=n},t.registerHelper("helperMissing",function(t){if(2===arguments.length)return e;throw Error("Missing helper: '"+t+"'")}),t.registerHelper("blockHelperMissing",function(e,r){var a=r.inverse||function(){},s=r.fn,o=i.call(e);return o===n&&(e=e.call(this)),e===!0?s(this):e===!1||null==e?a(this):"[object Array]"===o?e.length>0?t.helpers.each(e,r):a(this):s(e)}),t.K=function(){},t.createFrame=Object.create||function(e){t.K.prototype=e;var i=new t.K;return t.K.prototype=null,i},t.logger={DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,methodMap:{0:"debug",1:"info",2:"warn",3:"error"},log:function(e,i){if(e>=t.logger.level){var n=t.logger.methodMap[e];"undefined"!=typeof console&&console[n]&&console[n].call(console,i)}}},t.log=function(e,i){t.logger.log(e,i)},t.registerHelper("each",function(e,r){var a,s=r.fn,o=r.inverse,l=0,c="",h=i.call(e);if(h===n&&(e=e.call(this)),r.data&&(a=t.createFrame(r.data)),e&&"object"==typeof e)if(e instanceof Array)for(var u=e.length;u>l;l++)a&&(a.index=l),c+=s(e[l],{data:a});else for(var p in e)e.hasOwnProperty(p)&&(a&&(a.key=p),c+=s(e[p],{data:a}),l++);return 0===l&&(c=o(this)),c}),t.registerHelper("if",function(e,r){var a=i.call(e);return a===n&&(e=e.call(this)),!e||t.Utils.isEmpty(e)?r.inverse(this):r.fn(this)}),t.registerHelper("unless",function(e,i){return t.helpers["if"].call(this,e,{fn:i.inverse,inverse:i.fn})}),t.registerHelper("with",function(r,a){var s=i.call(r);return s===n&&(r=r.call(this)),t.Utils.isEmpty(r)?e:a.fn(r)}),t.registerHelper("log",function(e,i){var n=i.data&&null!=i.data.level?parseInt(i.data.level,10):1;t.log(n,e)});var a=["description","fileName","lineNumber","message","name","number","stack"];t.Exception=function(){for(var t=Error.prototype.constructor.apply(this,arguments),e=0;a.length>e;e++)this[a[e]]=t[a[e]]},t.Exception.prototype=Error(),t.SafeString=function(t){this.string=t},t.SafeString.prototype.toString=function(){return""+this.string};var s={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},o=/[&<>"'`]/g,l=/[&<>"'`]/,c=function(t){return s[t]||"&amp;"};t.Utils={extend:function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])},escapeExpression:function(e){return e instanceof t.SafeString?""+e:null==e||e===!1?"":(e=""+e,l.test(e)?e.replace(o,c):e)},isEmpty:function(t){return t||0===t?"[object Array]"===i.call(t)&&0===t.length?!0:!1:!0}},t.VM={template:function(e){var i={escapeExpression:t.Utils.escapeExpression,invokePartial:t.VM.invokePartial,programs:[],program:function(e,i,n){var r=this.programs[e];return n?r=t.VM.program(e,i,n):r||(r=this.programs[e]=t.VM.program(e,i)),r},merge:function(e,i){var n=e||i;return e&&i&&(n={},t.Utils.extend(n,i),t.Utils.extend(n,e)),n},programWithDepth:t.VM.programWithDepth,noop:t.VM.noop,compilerInfo:null};return function(n,r){r=r||{};var a=e.call(i,t,n,r.helpers,r.partials,r.data),s=i.compilerInfo||[],o=s[0]||1,l=t.COMPILER_REVISION;if(o!==l){if(l>o){var c=t.REVISION_CHANGES[l],h=t.REVISION_CHANGES[o];throw"Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+c+") or downgrade your runtime to an older version ("+h+")."}throw"Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+s[1]+")."}return a}},programWithDepth:function(t,e,i){var n=Array.prototype.slice.call(arguments,3),r=function(t,r){return r=r||{},e.apply(this,[t,r.data||i].concat(n))};return r.program=t,r.depth=n.length,r},program:function(t,e,i){var n=function(t,n){return n=n||{},e(t,n.data||i)};return n.program=t,n.depth=0,n},noop:function(){return""},invokePartial:function(i,n,r,a,s,o){var l={helpers:a,partials:s,data:o};if(i===e)throw new t.Exception("The partial "+n+" could not be found");if(i instanceof Function)return i(r,l);if(t.compile)return s[n]=t.compile(i,{data:o!==e}),s[n](r,l);throw new t.Exception("The partial "+n+" could not be compiled when running in runtime-only mode")}},t.template=t.VM.template})(Handlebars),this.joint=this.joint||{},this.joint.templates=this.joint.templates||{},this.joint.templates["freetransform.html"]=Handlebars.template(function(t,e,i,n,r){return this.compilerInfo=[4,">= 1.0.0"],i=this.merge(i,t.helpers),r=r||{},'<div class="resize" data-position="top-left" draggable="false"/>\n<div class="resize" data-position="top" draggable="false"/>\n<div class="resize" data-position="top-right" draggable="false"/>\n<div class="resize" data-position="right" draggable="false"/>\n<div class="resize" data-position="bottom-right" draggable="false"/>\n<div class="resize" data-position="bottom" draggable="false"/>\n<div class="resize" data-position="bottom-left" draggable="false"/>\n<div class="resize" data-position="left" draggable="false"/>\n<div class="rotate" draggable="false"/>\n\n'}),joint.ui.FreeTransform=Backbone.View.extend({className:"free-transform",template:"freetransform",events:{"mousedown .resize":"startResizing","mousedown .rotate":"startRotating","touchstart .resize":"startResizing","touchstart .rotate":"startRotating"},options:{directions:["nw","n","ne","e","se","s","sw","w"]},initialize:function(){this.options.cellView&&_.defaults(this.options,{cell:this.options.cellView.model,paper:this.options.cellView.paper,graph:this.options.cellView.paper.model}),_.bindAll(this,"update","remove","pointerup","pointermove"),joint.ui.FreeTransform.clear(this.options.paper),$(document.body).on("mousemove touchmove",this.pointermove),$(document).on("mouseup touchend",this.pointerup),this.listenTo(this.options.graph,"all",this.update),this.listenTo(this.options.graph,"reset",this.remove),this.listenTo(this.options.cell,"remove",this.remove),this.listenTo(this.options.paper,"blank:pointerdown freetransform:create",this.remove),this.listenTo(this.options.paper,"scale",this.update),this.options.paper.$el.append(this.el)},render:function(){this.$el.html(joint.templates["freetransform.html"](this.template)),this.$el.attr("data-type",this.options.cell.get("type")),this.update()},update:function(){var t=this.options.paper.viewport.getCTM(),e=this.options.cell.getBBox();e.x*=t.a,e.x+=t.e,e.y*=t.d,e.y+=t.f,e.width*=t.a,e.height*=t.d;var i=g.normalizeAngle(this.options.cell.get("angle")||0),n="rotate("+i+"deg)";this.$el.css({width:e.width+4,height:e.height+4,left:e.x-3,top:e.y-3,transform:n,"-webkit-transform":n,"-ms-transform":n});var r=Math.floor(i*(this.options.directions.length/360));if(r!=this._previousDirectionsShift){var a=_.rest(this.options.directions,r).concat(_.first(this.options.directions,r));this.$(".resize").removeClass("nw n ne e se s sw w").each(function(t,e){$(e).addClass(a[t])}),this._previousDirectionsShift=r}},startResizing:function(t){t.stopPropagation(),this.options.graph.trigger("batch:start");var e=$(t.target).data("position"),i=0,n=0;_.each(e.split("-"),function(t){i={left:-1,right:1}[t]||i,n={top:-1,bottom:1}[t]||n}),e={top:"top-left",bottom:"bottom-right",left:"bottom-left",right:"top-right"}[e]||e;var r={"top-right":"bottomLeft","top-left":"corner","bottom-left":"topRight","bottom-right":"origin"}[e];this._initial={angle:g.normalizeAngle(this.options.cell.get("angle")||0),resizeX:i,resizeY:n,selector:r,direction:e},this._action="resize",this.startOp(t.target)},startRotating:function(t){t.stopPropagation(),this.options.graph.trigger("batch:start");var e=this.options.cell.getBBox().center(),i=this.options.paper.snapToGrid({x:t.clientX,y:t.clientY});this._initial={centerRotation:e,modelAngle:g.normalizeAngle(this.options.cell.get("angle")||0),startAngle:g.point(i).theta(e)},this._action="rotate",this.startOp(t.target)},pointermove:function(t){if(this._action){t=joint.util.normalizeEvent(t);var e=this.options.paper.snapToGrid({x:t.clientX,y:t.clientY}),i=this.options.paper.options.gridSize,n=this.options.cell,r=this._initial;switch(this._action){case"resize":var a=n.getBBox(),s=g.point(e).rotate(a.center(),r.angle),o=s.difference(a[r.selector]()),l=r.resizeX?o.x*r.resizeX:a.width,c=r.resizeY?o.y*r.resizeY:a.height;l=i>l?i:g.snapToGrid(l,i),c=i>c?i:g.snapToGrid(c,i),(a.width!=l||a.height!=c)&&n.resize(l,c,{direction:r.direction});break;case"rotate":var h=r.startAngle-g.point(e).theta(r.centerRotation);n.rotate(g.snapToGrid(r.modelAngle+h,15),!0)}}},pointerup:function(){this._action&&(this.stopOp(),this.options.graph.trigger("batch:stop"),delete this._action,delete this._initial)
+},remove:function(){Backbone.View.prototype.remove.apply(this,arguments),$("body").off("mousemove touchmove",this.pointermove),$(document).off("mouseup touchend",this.pointerup)},startOp:function(t){t&&($(t).addClass("in-operation"),this._elementOp=t),this.$el.addClass("in-operation")},stopOp:function(){this._elementOp&&($(this._elementOp).removeClass("in-operation"),delete this._elementOp),this.$el.removeClass("in-operation")}},{clear:function(t){t.trigger("freetransform:create")}}),joint.ui.Tooltip=Backbone.View.extend({className:"tooltip",options:{left:void 0,right:void 0,top:void 0,bottom:void 0,padding:10,target:void 0,rootTarget:void 0},initialize:function(){_.bindAll(this,"render","hide","position"),this.options.rootTarget?(this.$rootTarget=$(this.options.rootTarget),this.$rootTarget.on("mouseover",this.options.target,this.render),this.$rootTarget.on("mouseout",this.options.target,this.hide),this.$rootTarget.on("mousedown",this.options.target,this.hide)):(this.$target=$(this.options.target),this.$target.on("mouseover",this.render),this.$target.on("mouseout",this.hide),this.$target.on("mousedown",this.hide)),this.$el.addClass(this.options.direction)},remove:function(){this.$target.off("mouseover",this.render),this.$target.off("mouseout",this.hide),this.$target.off("mousedown",this.hide),Backbone.View.prototype.remove.apply(this,arguments)},hide:function(){Backbone.View.prototype.remove.apply(this,arguments)},render:function(t){var e,i=!_.isUndefined(t.x)&&!_.isUndefined(t.y);i?e=t:(this.$target=$(t.target).closest(this.options.target),e=this.$target[0]),this.$el.html(_.isFunction(this.options.content)?this.options.content(e):this.options.content),this.$el.hide(),$(document.body).append(this.$el);var n=this.$("img");n.length?n.on("load",_.bind(function(){this.position(i?e:void 0)},this)):this.position(i?e:void 0)},getElementBBox:function(t){var e,i=$(t),n=i.offset(),r=document.body.scrollTop||document.documentElement.scrollTop,a=document.body.scrollLeft||document.documentElement.scrollLeft;return n.top-=r||0,n.left-=a||0,t.ownerSVGElement?(e=V(t).bbox(),e.x=n.left,e.y=n.top):e={x:n.left,y:n.top,width:i.outerWidth(),height:i.outerHeight()},e},position:function(t){var e;e=t?{x:t.x,y:t.y,width:1,height:1}:this.getElementBBox(this.$target[0]);var i=this.options.padding;this.$el.show();var n=this.$el.outerHeight(),r=this.$el.outerWidth();if(this.options.left){var a=$(_.isFunction(this.options.left)?this.options.left(this.$target[0]):this.options.left),s=this.getElementBBox(a[0]);this.$el.css({left:s.x+s.width+i,top:e.y+e.height/2-n/2})}else if(this.options.right){var o=$(_.isFunction(this.options.right)?this.options.right(this.$target[0]):this.options.right),l=this.getElementBBox(o[0]);this.$el.css({left:l.x-r-i,top:e.y+e.height/2-n/2})}else if(this.options.top){var c=$(_.isFunction(this.options.top)?this.options.top(this.$target[0]):this.options.top),h=this.getElementBBox(c[0]);this.$el.css({top:h.y+h.height+i,left:e.x+e.width/2-r/2})}else if(this.options.bottom){var u=$(_.isFunction(this.options.bottom)?this.options.bottom(this.$target[0]):this.options.bottom),p=this.getElementBBox(u[0]);this.$el.css({top:p.y-n-i,left:e.x+e.width/2-r/2})}else this.$el.css({left:e.x+e.width+i,top:e.y+e.height/2-n/2})}}),function e(t,i,n){function r(s,o){if(!i[s]){if(!t[s]){var l="function"==typeof require&&require;if(!o&&l)return l(s,!0);if(a)return a(s,!0);throw Error("Cannot find module '"+s+"'")}var c=i[s]={exports:{}};t[s][0].call(c.exports,function(e){var i=t[s][1][e];return r(i?i:e)},c,c.exports,e,t,i,n)}return i[s].exports}for(var a="function"==typeof require&&require,s=0;n.length>s;s++)r(n[s]);return r}({1:[function(t){var e="undefined"!=typeof self?self:"undefined"!=typeof window?window:{};e.dagre=t("./index")},{"./index":2}],2:[function(t,e,i){i.Digraph=t("graphlib").Digraph,i.Graph=t("graphlib").Graph,i.layout=t("./lib/layout"),i.version=t("./lib/version")},{"./lib/layout":3,"./lib/version":18,graphlib:24}],3:[function(t,e){var i=t("./util"),n=t("./rank"),r=t("./order"),a=t("graphlib").CGraph,s=t("graphlib").CDigraph;e.exports=function(){function e(t){var e=new s;t.eachNode(function(t,i){void 0===i&&(i={}),e.addNode(t,{width:i.width,height:i.height}),i.hasOwnProperty("rank")&&(e.node(t).prefRank=i.rank)}),t.parent&&t.nodes().forEach(function(i){e.parent(i,t.parent(i))}),t.eachEdge(function(t,i,n,r){void 0===r&&(r={});var a={e:t,minLen:r.minLen||1,width:r.width||0,height:r.height||0,points:[]};e.addEdge(null,i,n,a)});var i=t.graph()||{};return e.graph({rankDir:i.rankDir||g.rankDir,orderRestarts:i.orderRestarts}),e}function o(t){var a,s=f.rankSep();try{return a=i.time("initLayoutGraph",e)(t),0===a.order()?a:(a.eachEdge(function(t,e,i,n){n.minLen*=2}),f.rankSep(s/2),i.time("rank.run",n.run)(a,g.rankSimplex),i.time("normalize",l)(a),i.time("order",r)(a,g.orderMaxSweeps),i.time("position",d.run)(a),i.time("undoNormalize",c)(a),i.time("fixupEdgePoints",h)(a),i.time("rank.restoreEdges",n.restoreEdges)(a),i.time("createFinalGraph",u)(a,t.isDirected()))}finally{f.rankSep(s)}}function l(t){var e=0;t.eachEdge(function(i,n,r,a){var s=t.node(n).rank,o=t.node(r).rank;if(o>s+1){for(var l=n,c=s+1,h=0;o>c;++c,++h){var u="_D"+ ++e,p={width:a.width,height:a.height,edge:{id:i,source:n,target:r,attrs:a},rank:c,dummy:!0};0===h?p.index=0:c+1===o&&(p.index=1),t.addNode(u,p),t.addEdge(null,l,u,{}),l=u}t.addEdge(null,l,r,{}),t.delEdge(i)}})}function c(t){t.eachNode(function(e,i){if(i.dummy){if("index"in i){var n=i.edge;t.hasEdge(n.id)||t.addEdge(n.id,n.source,n.target,n.attrs);var r=t.edge(n.id).points;r[i.index]={x:i.x,y:i.y,ul:i.ul,ur:i.ur,dl:i.dl,dr:i.dr}}t.delNode(e)}})}function h(t){t.eachEdge(function(t,e,i,n){n.reversed&&n.points.reverse()})}function u(t,e){var i=e?new s:new a;i.graph(t.graph()),t.eachNode(function(t,e){i.addNode(t,e)}),t.eachNode(function(e){i.parent(e,t.parent(e))}),t.eachEdge(function(t,e,n,r){i.addEdge(r.e,e,n,r)});var n=0,r=0;return t.eachNode(function(e,i){t.children(e).length||(n=Math.max(n,i.x+i.width/2),r=Math.max(r,i.y+i.height/2))}),t.eachEdge(function(t,e,i,a){var s=Math.max.apply(Math,a.points.map(function(t){return t.x})),o=Math.max.apply(Math,a.points.map(function(t){return t.y}));n=Math.max(n,s+a.width/2),r=Math.max(r,o+a.height/2)}),i.graph().width=n,i.graph().height=r,i}function p(t){return function(){return arguments.length?(t.apply(null,arguments),f):t()}}var g={debugLevel:0,orderMaxSweeps:r.DEFAULT_MAX_SWEEPS,rankSimplex:!1,rankDir:"TB"},d=t("./position")(),f={};return f.orderIters=i.propertyAccessor(f,g,"orderMaxSweeps"),f.rankSimplex=i.propertyAccessor(f,g,"rankSimplex"),f.nodeSep=p(d.nodeSep),f.edgeSep=p(d.edgeSep),f.universalSep=p(d.universalSep),f.rankSep=p(d.rankSep),f.rankDir=i.propertyAccessor(f,g,"rankDir"),f.debugAlignment=p(d.debugAlignment),f.debugLevel=i.propertyAccessor(f,g,"debugLevel",function(t){i.log.level=t,d.debugLevel(t)}),f.run=i.time("Total layout",o),f._normalize=l,f}},{"./order":4,"./position":9,"./rank":10,"./util":17,graphlib:24}],4:[function(t,e){function n(t,e){function i(){t.eachNode(function(t,e){g[t]=e.order})}2>arguments.length&&(e=d);var n=t.graph().orderRestarts||0,r=u(t);r.forEach(function(e){e=e.filterNodes(function(e){return!t.children(e).length})});for(var a,o=0,l=Number.MAX_VALUE,g={},f=0;Number(n)+1>f&&0!==l;++f){a=Number.MAX_VALUE,p(t,n>0),c.log(2,"Order phase start cross count: "+t.graph().orderInitCC);var m,I,y;for(m=0,I=0;4>I&&e>m&&a>0;++m,++I,++o)s(t,r,m),y=h(t),a>y&&(I=0,a=y,l>y&&(i(),l=y)),c.log(3,"Order phase start "+f+" iter "+m+" cross count: "+y)}Object.keys(g).forEach(function(e){t.children&&t.children(e).length||(t.node(e).order=g[e])}),t.graph().orderCC=l,c.log(2,"Order iterations: "+o),c.log(2,"Order phase best cross count: "+t.graph().orderCC)}function r(t,e){var i={};return e.forEach(function(e){i[e]=t.inEdges(e).map(function(e){return t.node(t.source(e)).order})}),i}function a(t,e){var i={};return e.forEach(function(e){i[e]=t.outEdges(e).map(function(e){return t.node(t.target(e)).order})}),i}function s(t,e,i){0===i%2?o(t,e,i):l(t,e,i)}function o(t,e){var n;for(i=1;e.length>i;++i)n=g(e[i],n,r(t,e[i].nodes()))}function l(t,e){var n;for(i=e.length-2;i>=0;--i)g(e[i],n,a(t,e[i].nodes()))}var c=t("./util"),h=t("./order/crossCount"),u=t("./order/initLayerGraphs"),p=t("./order/initOrder"),g=t("./order/sortLayer");e.exports=n;var d=24;n.DEFAULT_MAX_SWEEPS=d},{"./order/crossCount":5,"./order/initLayerGraphs":6,"./order/initOrder":7,"./order/sortLayer":8,"./util":17}],5:[function(t,e){function i(t){for(var e=0,i=r.ordering(t),a=1;i.length>a;++a)e+=n(t,i[a-1],i[a]);return e}function n(t,e,i){var n=[];e.forEach(function(e){var i=[];t.outEdges(e).forEach(function(e){i.push(t.node(t.target(e)).order)}),i.sort(function(t,e){return t-e}),n=n.concat(i)});for(var r=1;i.length>r;)r<<=1;var a=2*r-1;r-=1;for(var s=[],o=0;a>o;++o)s[o]=0;var l=0;return n.forEach(function(t){var e=t+r;for(++s[e];e>0;)e%2&&(l+=s[e+1]),e=e-1>>1,++s[e]}),l}var r=t("../util");e.exports=i},{"../util":17}],6:[function(t,e){function i(t){function e(n){if(null===n)return t.children(n).forEach(function(t){e(t)}),void 0;var a=t.node(n);a.minRank="rank"in a?a.rank:Number.MAX_VALUE,a.maxRank="rank"in a?a.rank:Number.MIN_VALUE;var s=new r;return t.children(n).forEach(function(i){var n=e(i);s=r.union([s,n]),a.minRank=Math.min(a.minRank,t.node(i).minRank),a.maxRank=Math.max(a.maxRank,t.node(i).maxRank)}),"rank"in a&&s.add(a.rank),s.keys().forEach(function(t){t in i||(i[t]=[]),i[t].push(n)}),s}var i=[];e(null);var a=[];return i.forEach(function(e,i){a[i]=t.filterNodes(n(e))}),a}var n=t("graphlib").filter.nodesFromList,r=t("cp-data").Set;e.exports=i},{"cp-data":19,graphlib:24}],7:[function(t,e){function i(t,e){var i=[];t.eachNode(function(e,n){var r=i[n.rank];t.children&&t.children(e).length>0||(r||(r=i[n.rank]=[]),r.push(e))}),i.forEach(function(i){e&&r.shuffle(i),i.forEach(function(e,i){t.node(e).order=i})});var a=n(t);t.graph().orderInitCC=a,t.graph().orderCC=Number.MAX_VALUE}var n=t("./crossCount"),r=t("../util");e.exports=i},{"../util":17,"./crossCount":5}],8:[function(t,e){function i(t,e,i){var r=[],a={};t.eachNode(function(t,e){r[e.order]=t;var s=i[t];s.length&&(a[t]=n.sum(s)/s.length)});var s=t.nodes().filter(function(t){return void 0!==a[t]});s.sort(function(e,i){return a[e]-a[i]||t.node(e).order-t.node(i).order});for(var o=0,l=0,c=s.length;c>l;++o)void 0!==a[r[o]]&&(t.node(s[l++]).order=o)}var n=t("../util");e.exports=i},{"../util":17}],9:[function(t,e){var i=t("./util");e.exports=function(){function t(t){t=t.filterNodes(i.filterNonSubgraphs(t));var e=i.ordering(t),s=n(t,e),o={};["u","d"].forEach(function(i){"d"===i&&e.reverse(),["l","r"].forEach(function(n){"r"===n&&h(e);var l=i+n,u=r(t,e,s,"u"===i?"predecessors":"successors");o[l]=a(t,e,u.pos,u.root,u.align),y.debugLevel>=3&&I(i+n,t,e,o[l]),"r"===n&&c(o[l]),"r"===n&&h(e)}),"d"===i&&e.reverse()}),l(t,e,o),t.eachNode(function(e){var i=[];for(var n in o){var r=o[n][e];f(n,t,e,r),i.push(r)}i.sort(function(t,e){return t-e}),d(t,e,(i[1]+i[2])/2)});var g=0,v="BT"===t.graph().rankDir||"RL"===t.graph().rankDir;e.forEach(function(e){var n=i.max(e.map(function(e){return p(t,e)}));g+=n/2,e.forEach(function(e){m(t,e,v?-g:g)}),g+=n/2+y.rankSep});var C=i.min(t.nodes().map(function(e){return d(t,e)-u(t,e)/2})),b=i.min(t.nodes().map(function(e){return m(t,e)-p(t,e)/2}));t.eachNode(function(e){d(t,e,d(t,e)-C),m(t,e,m(t,e)-b)})}function e(t,e){return e>t?(""+t).length+":"+t+"-"+e:(""+e).length+":"+e+"-"+t}function n(t,i){function n(t){var i=h[t];(s>i||i>l)&&(c[e(a[o],t)]=!0)}var r,a,s,o,l,c={},h={};if(2>=i.length)return c;i[1].forEach(function(t,e){h[t]=e});for(var u=1;i.length-1>u;++u){r=i[u],a=i[u+1],s=0,o=0;for(var p=0;a.length>p;++p){var g=a[p];if(h[g]=p,l=void 0,t.node(g).dummy){var d=t.predecessors(g)[0];void 0!==d&&t.node(d).dummy&&(l=h[d])}if(void 0===l&&p===a.length-1&&(l=r.length-1),void 0!==l){for(;p>=o;++o)t.predecessors(a[o]).forEach(n);s=l}}}return c}function r(t,i,n,r){var a={},s={},o={};return i.forEach(function(t){t.forEach(function(t,e){s[t]=t,o[t]=t,a[t]=e})}),i.forEach(function(i){var l=-1;i.forEach(function(i){var c,h=t[r](i);h.length>0&&(h.sort(function(t,e){return a[t]-a[e]}),c=(h.length-1)/2,h.slice(Math.floor(c),Math.ceil(c)+1).forEach(function(t){o[i]===i&&!n[e(t,i)]&&a[t]>l&&(o[t]=i,o[i]=s[i]=s[t],l=a[t])}))})}),{pos:a,root:s,align:o}}function a(t,e,n,r,a){function s(t,e,i){c[t][e]=e in c[t]?Math.min(c[t][e],i):i}function o(e){if(!(e in p)){p[e]=0;var i=e;do{if(n[i]>0){var c=r[u[i]];o(c),l[e]===e&&(l[e]=l[c]);var h=g(t,u[i])+g(t,i);l[e]!==l[c]?s(l[c],l[e],p[e]-p[c]-h):p[e]=Math.max(p[e],p[c]+h)}i=a[i]}while(i!==e)}}var l={},c={},h={},u={},p={};return e.forEach(function(t){t.forEach(function(e,i){l[e]=e,c[e]={},i>0&&(u[e]=t[i-1])})}),i.values(r).forEach(function(t){o(t)}),e.forEach(function(t){t.forEach(function(t){if(p[t]=p[r[t]],t===r[t]&&t===l[t]){var e=0;t in c&&Object.keys(c[t]).length>0&&(e=i.min(Object.keys(c[t]).map(function(e){return c[t][e]+(e in h?h[e]:0)}))),h[t]=e}})}),e.forEach(function(t){t.forEach(function(t){p[t]+=h[l[r[t]]]||0})}),p}function s(t,e,n){return i.min(e.map(function(t){var e=t[0];return n[e]}))}function o(t,e,n){return i.max(e.map(function(t){var e=t[t.length-1];return n[e]}))}function l(t,e,i){function n(t){i[u][t]+=c[u]}var r,a={},l={},c={},h=Number.POSITIVE_INFINITY;for(var u in i){var p=i[u];a[u]=s(t,e,p),l[u]=o(t,e,p);var g=l[u]-a[u];h>g&&(h=g,r=u)}["u","d"].forEach(function(t){["l","r"].forEach(function(e){var i=t+e;c[i]="l"===e?a[r]-a[i]:l[r]-l[i]})});for(u in i)t.eachNode(n)}function c(t){for(var e in t)t[e]=-t[e]}function h(t){t.forEach(function(t){t.reverse()})}function u(t,e){switch(t.graph().rankDir){case"LR":return t.node(e).height;case"RL":return t.node(e).height;default:return t.node(e).width}}function p(t,e){switch(t.graph().rankDir){case"LR":return t.node(e).width;case"RL":return t.node(e).width;default:return t.node(e).height}}function g(t,e){if(null!==y.universalSep)return y.universalSep;var i=u(t,e),n=t.node(e).dummy?y.edgeSep:y.nodeSep;return(i+n)/2}function d(t,e,i){if("LR"===t.graph().rankDir||"RL"===t.graph().rankDir){if(3>arguments.length)return t.node(e).y;t.node(e).y=i}else{if(3>arguments.length)return t.node(e).x;t.node(e).x=i}}function f(t,e,i,n){if("LR"===e.graph().rankDir||"RL"===e.graph().rankDir){if(3>arguments.length)return e.node(i)[t];e.node(i)[t]=n}else{if(3>arguments.length)return e.node(i)[t];e.node(i)[t]=n}}function m(t,e,i){if("LR"===t.graph().rankDir||"RL"===t.graph().rankDir){if(3>arguments.length)return t.node(e).x;t.node(e).x=i}else{if(3>arguments.length)return t.node(e).y;t.node(e).y=i}}function I(t,e,i,n){i.forEach(function(i,r){var a,s;i.forEach(function(i){var o=n[i];if(a){var l=g(e,a)+g(e,i);l>o-s&&console.log("Position phase: sep violation. Align: "+t+". Layer: "+r+". "+"U: "+a+" V: "+i+". Actual sep: "+(o-s)+" Expected sep: "+l)}a=i,s=o})})}var y={nodeSep:50,edgeSep:10,universalSep:null,rankSep:30},v={};return v.nodeSep=i.propertyAccessor(v,y,"nodeSep"),v.edgeSep=i.propertyAccessor(v,y,"edgeSep"),v.universalSep=i.propertyAccessor(v,y,"universalSep"),v.rankSep=i.propertyAccessor(v,y,"rankSep"),v.debugLevel=i.propertyAccessor(v,y,"debugLevel"),v.run=t,v}},{"./util":17}],10:[function(t,e,i){function n(t,e){a(t),u.time("constraints.apply",f.apply)(t),s(t),u.time("acyclic",p)(t);var i=t.filterNodes(u.filterNonSubgraphs(t));g(i),I(i).forEach(function(t){var n=i.filterNodes(y.nodesFromList(t));c(n,e)}),u.time("constraints.relax",f.relax(t)),u.time("reorientEdges",l)(t)}function r(t){p.undo(t)}function a(t){t.eachEdge(function(e,i,n,r){if(i===n){var a=o(t,e,i,n,r,0,!1),s=o(t,e,i,n,r,1,!0),l=o(t,e,i,n,r,2,!1);t.addEdge(null,a,i,{minLen:1,selfLoop:!0}),t.addEdge(null,a,s,{minLen:1,selfLoop:!0}),t.addEdge(null,i,l,{minLen:1,selfLoop:!0}),t.addEdge(null,s,l,{minLen:1,selfLoop:!0}),t.delEdge(e)}})}function s(t){t.eachEdge(function(e,i,n,r){if(i===n){var a=r.originalEdge,s=o(t,a.e,a.u,a.v,a.value,0,!0);t.addEdge(null,i,s,{minLen:1}),t.addEdge(null,s,n,{minLen:1}),t.delEdge(e)}})}function o(t,e,i,n,r,a,s){return t.addNode(null,{width:s?r.width:0,height:s?r.height:0,edge:{id:e,source:i,target:n,attrs:r},dummy:!0,index:a})}function l(t){t.eachEdge(function(e,i,n,r){t.node(i).rank>t.node(n).rank&&(t.delEdge(e),r.reversed=!0,t.addEdge(e,n,i,r))})}function c(t,e){var i=d(t);e&&(u.log(1,"Using network simplex for ranking"),m(t,i)),h(t)}function h(t){var e=u.min(t.nodes().map(function(e){return t.node(e).rank}));t.eachNode(function(t,i){i.rank-=e})}var u=t("./util"),p=t("./rank/acyclic"),g=t("./rank/initRank"),d=t("./rank/feasibleTree"),f=t("./rank/constraints"),m=t("./rank/simplex"),I=t("graphlib").alg.components,y=t("graphlib").filter;i.run=n,i.restoreEdges=r},{"./rank/acyclic":11,"./rank/constraints":12,"./rank/feasibleTree":13,"./rank/initRank":14,"./rank/simplex":16,"./util":17,graphlib:24}],11:[function(t,e){function i(t){function e(r){r in n||(n[r]=i[r]=!0,t.outEdges(r).forEach(function(n){var s,o=t.target(n);r===o?console.error('Warning: found self loop "'+n+'" for node "'+r+'"'):o in i?(s=t.edge(n),t.delEdge(n),s.reversed=!0,++a,t.addEdge(n,o,r,s)):e(o)}),delete i[r])}var i={},n={},a=0;return t.eachNode(function(t){e(t)}),r.log(2,"Acyclic Phase: reversed "+a+" edge(s)"),a}function n(t){t.eachEdge(function(e,i,n,r){r.reversed&&(delete r.reversed,t.delEdge(e),t.addEdge(e,n,i,r))})}var r=t("../util");e.exports=i,e.exports.undo=n},{"../util":17}],12:[function(t,e,i){function n(t){return"min"!==t&&"max"!==t&&0!==t.indexOf("same_")?(console.error("Unsupported rank type: "+t),!1):!0}function r(t,e,i,n){t.inEdges(e).forEach(function(e){var r,a=t.edge(e);r=a.originalEdge?a:{originalEdge:{e:e,u:t.source(e),v:t.target(e),value:a},minLen:t.edge(e).minLen},a.selfLoop&&(n=!1),n?(t.addEdge(null,i,t.source(e),r),r.reversed=!0):t.addEdge(null,t.source(e),i,r)})}function a(t,e,i,n){t.outEdges(e).forEach(function(e){var r,a=t.edge(e);r=a.originalEdge?a:{originalEdge:{e:e,u:t.source(e),v:t.target(e),value:a},minLen:t.edge(e).minLen},a.selfLoop&&(n=!1),n?(t.addEdge(null,t.target(e),i,r),r.reversed=!0):t.addEdge(null,i,t.target(e),r)})}function s(t,e,i){void 0!==i&&t.children(e).forEach(function(e){e===i||t.outEdges(i,e).length||t.node(e).dummy||t.addEdge(null,i,e,{minLen:0})})}function o(t,e,i){void 0!==i&&t.children(e).forEach(function(e){e===i||t.outEdges(e,i).length||t.node(e).dummy||t.addEdge(null,e,i,{minLen:0})})}i.apply=function(t){function e(i){var l={};t.children(i).forEach(function(s){if(t.children(s).length)return e(s),void 0;var o=t.node(s),c=o.prefRank;if(void 0!==c){if(!n(c))return;c in l?l.prefRank.push(s):l.prefRank=[s];var h=l[c];void 0===h&&(h=l[c]=t.addNode(null,{originalNodes:[]}),t.parent(h,i)),r(t,s,h,"min"===c),a(t,s,h,"max"===c),t.node(h).originalNodes.push({u:s,value:o,parent:i}),t.delNode(s)}}),s(t,i,l.min),o(t,i,l.max)}e(null)},i.relax=function(t){var e=[];t.eachEdge(function(t,i,n,r){var a=r.originalEdge;a&&e.push(a)}),t.eachNode(function(e,i){var n=i.originalNodes;n&&(n.forEach(function(e){e.value.rank=i.rank,t.addNode(e.u,e.value),t.parent(e.u,e.parent)}),t.delNode(e))}),e.forEach(function(e){t.addEdge(e.e,e.u,e.v,e.value)})}},{}],13:[function(t,e){function i(t){function e(i){var r=!0;return t.predecessors(i).forEach(function(a){s.has(a)&&!n(t,a,i)&&(s.has(i)&&(o.addNode(i,{}),s.remove(i),o.graph({root:i})),o.addNode(a,{}),o.addEdge(null,a,i,{reversed:!0}),s.remove(a),e(a),r=!1)}),t.successors(i).forEach(function(a){s.has(a)&&!n(t,i,a)&&(s.has(i)&&(o.addNode(i,{}),s.remove(i),o.graph({root:i})),o.addNode(a,{}),o.addEdge(null,i,a,{}),s.remove(a),e(a),r=!1)}),r}function i(){var e=Number.MAX_VALUE;s.keys().forEach(function(i){t.predecessors(i).forEach(function(r){if(!s.has(r)){var a=n(t,r,i);Math.abs(a)<Math.abs(e)&&(e=-a)}}),t.successors(i).forEach(function(r){if(!s.has(r)){var a=n(t,i,r);Math.abs(a)<Math.abs(e)&&(e=a)}})}),o.eachNode(function(i){t.node(i).rank-=e})}var s=new r(t.nodes()),o=new a;if(1===s.size()){var l=t.nodes()[0];return o.addNode(l,{}),o.graph({root:l}),o}for(;s.size();){for(var c=o.order()?o.nodes():s.keys(),h=0,u=c.length;u>h&&e(c[h]);++h);s.size()&&i()}return o}function n(t,e,i){var n=t.node(i).rank-t.node(e).rank,r=s.max(t.outEdges(e,i).map(function(e){return t.edge(e).minLen}));return n-r}var r=t("cp-data").Set,a=t("graphlib").Digraph,s=t("../util");e.exports=i},{"../util":17,"cp-data":19,graphlib:24}],14:[function(t,e){function i(t){var e=r(t);e.forEach(function(e){var i=t.inEdges(e);if(0===i.length)return t.node(e).rank=0,void 0;var r=i.map(function(e){return t.node(t.source(e)).rank+t.edge(e).minLen});t.node(e).rank=n.max(r)})}var n=t("../util"),r=t("graphlib").alg.topsort;e.exports=i},{"../util":17,graphlib:24}],15:[function(t,e){function i(t,e,i,n){return Math.abs(t.node(e).rank-t.node(i).rank)-n}e.exports={slack:i}},{}],16:[function(t,e){function i(t,e){for(n(t,e);;){var i=o(e);if(null===i)break;var r=l(t,e,i);c(t,e,i,r)}}function n(t,e){function i(n){var r=e.successors(n);for(var s in r){var o=r[s];i(o)}n!==e.graph().root&&a(t,e,n)}r(e),e.eachEdge(function(t,e,i,n){n.cutValue=0}),i(e.graph().root)}function r(t){function e(n){var r=t.successors(n),a=i;for(var s in r){var o=r[s];e(o),a=Math.min(a,t.node(o).low)}t.node(n).low=a,t.node(n).lim=i++}var i=0;e(t.graph().root)}function a(t,e,i){var n=e.inEdges(i)[0],r=[],a=e.outEdges(i);for(var o in a)r.push(e.target(a[o]));var l,c=0,h=0,u=0,p=0,g=0,d=t.outEdges(i);for(var f in d){var m=t.target(d[f]);for(l in r)s(e,m,r[l])&&h++;s(e,m,i)||p++}var I=t.inEdges(i);for(var y in I){var v=t.source(I[y]);for(l in r)s(e,v,r[l])&&u++;s(e,v,i)||g++}var C=0;for(l in r){var b=e.edge(a[l]).cutValue;e.edge(a[l]).reversed?C-=b:C+=b}e.edge(n).reversed?c-=C-h+u-p+g:c+=C-h+u-p+g,e.edge(n).cutValue=c}function s(t,e,i){return t.node(i).low<=t.node(e).lim&&t.node(e).lim<=t.node(i).lim}function o(t){var e=t.edges();for(var i in e){var n=e[i],r=t.edge(n);if(0>r.cutValue)return n}return null}function l(t,e,i){var n,r=e.source(i),a=e.target(i),o=e.node(a).lim<e.node(r).lim?a:r,l=!e.edge(i).reversed,c=Number.POSITIVE_INFINITY;if(l?t.eachEdge(function(r,a,l,h){if(r!==i&&s(e,a,o)&&!s(e,l,o)){var u=g.slack(t,a,l,h.minLen);c>u&&(c=u,n=r)}}):t.eachEdge(function(r,a,l,h){if(r!==i&&!s(e,a,o)&&s(e,l,o)){var u=g.slack(t,a,l,h.minLen);c>u&&(c=u,n=r)}}),void 0===n){var h=[],u=[];throw t.eachNode(function(t){s(e,t,o)?u.push(t):h.push(t)}),Error("No edge found from outside of tree to inside")}return n}function c(t,e,i,r){function a(t){var i=e.inEdges(t);for(var n in i){var r=i[n],s=e.source(r),o=e.edge(r);a(s),e.delEdge(r),o.reversed=!o.reversed,e.addEdge(r,t,s,o)}}e.delEdge(i);var s=t.source(r),o=t.target(r);a(o);for(var l=s,c=e.inEdges(l);c.length>0;)l=e.source(c[0]),c=e.inEdges(l);e.graph().root=l,e.addEdge(null,s,o,{cutValue:0}),n(t,e),h(t,e)}function h(t,e){function i(n){var r=e.successors(n);r.forEach(function(e){var r=u(t,n,e);t.node(e).rank=t.node(n).rank+r,i(e)})}i(e.graph().root)}function u(t,e,i){var n=t.outEdges(e,i);if(n.length>0)return p.max(n.map(function(e){return t.edge(e).minLen}));var r=t.inEdges(e,i);return r.length>0?-p.max(r.map(function(e){return t.edge(e).minLen})):void 0}var p=t("../util"),g=t("./rankUtil");e.exports=i},{"../util":17,"./rankUtil":15}],17:[function(t,e,n){function r(t,e){return function(){var i=(new Date).getTime();try{return e.apply(null,arguments)}finally{a(1,t+" time: "+((new Date).getTime()-i)+"ms")}}}function a(t){a.level>=t&&console.log.apply(console,Array.prototype.slice.call(arguments,1))}n.min=function(t){return Math.min.apply(Math,t)},n.max=function(t){return Math.max.apply(Math,t)},n.all=function(t,e){for(var i=0;t.length>i;++i)if(!e(t[i]))return!1;return!0},n.sum=function(t){return t.reduce(function(t,e){return t+e},0)},n.values=function(t){return Object.keys(t).map(function(e){return t[e]})},n.shuffle=function(t){for(i=t.length-1;i>0;--i){var e=Math.floor(Math.random()*(i+1)),n=t[e];t[e]=t[i],t[i]=n}},n.propertyAccessor=function(t,e,i,n){return function(r){return arguments.length?(e[i]=r,n&&n(r),t):e[i]}},n.ordering=function(t){var e=[];return t.eachNode(function(t,i){var n=e[i.rank]||(e[i.rank]=[]);n[i.order]=t}),e},n.filterNonSubgraphs=function(t){return function(e){return 0===t.children(e).length}},r.enabled=!1,n.time=r,a.level=0,n.log=a},{}],18:[function(t,e){e.exports="0.4.5"},{}],19:[function(t,e,i){i.Set=t("./lib/Set"),i.PriorityQueue=t("./lib/PriorityQueue"),i.version=t("./lib/version")},{"./lib/PriorityQueue":20,"./lib/Set":21,"./lib/version":23}],20:[function(t,e){function i(){this._arr=[],this._keyIndices={}}e.exports=i,i.prototype.size=function(){return this._arr.length},i.prototype.keys=function(){return this._arr.map(function(t){return t.key})},i.prototype.has=function(t){return t in this._keyIndices},i.prototype.priority=function(t){var e=this._keyIndices[t];return void 0!==e?this._arr[e].priority:void 0},i.prototype.min=function(){if(0===this.size())throw Error("Queue underflow");return this._arr[0].key},i.prototype.add=function(t,e){var i=this._keyIndices;if(!(t in i)){var n=this._arr,r=n.length;return i[t]=r,n.push({key:t,priority:e}),this._decrease(r),!0}return!1},i.prototype.removeMin=function(){this._swap(0,this._arr.length-1);var t=this._arr.pop();return delete this._keyIndices[t.key],this._heapify(0),t.key},i.prototype.decrease=function(t,e){var i=this._keyIndices[t];if(e>this._arr[i].priority)throw Error("New priority is greater than current priority. Key: "+t+" Old: "+this._arr[i].priority+" New: "+e);this._arr[i].priority=e,this._decrease(i)},i.prototype._heapify=function(t){var e=this._arr,i=2*t,n=i+1,r=t;e.length>i&&(r=e[i].priority<e[r].priority?i:r,e.length>n&&(r=e[n].priority<e[r].priority?n:r),r!==t&&(this._swap(t,r),this._heapify(r)))},i.prototype._decrease=function(t){for(var e,i=this._arr,n=i[t].priority;0!==t&&(e=t>>1,!(n>i[e].priority));)this._swap(t,e),t=e},i.prototype._swap=function(t,e){var i=this._arr,n=this._keyIndices,r=i[t],a=i[e];i[t]=a,i[e]=r,n[a.key]=t,n[r.key]=e}},{}],21:[function(t,e){function i(t){if(this._size=0,this._keys={},t)for(var e=0,i=t.length;i>e;++e)this.add(t[e])}function n(t){var e,i=Object.keys(t),n=i.length,r=Array(n);for(e=0;n>e;++e)r[e]=t[i[e]];return r}var r=t("./util");e.exports=i,i.intersect=function(t){if(0===t.length)return new i;for(var e=new i(r.isArray(t[0])?t[0]:t[0].keys()),n=1,a=t.length;a>n;++n)for(var s=e.keys(),o=r.isArray(t[n])?new i(t[n]):t[n],l=0,c=s.length;c>l;++l){var h=s[l];o.has(h)||e.remove(h)}return e},i.union=function(t){for(var e=r.reduce(t,function(t,e){return t+(e.size?e.size():e.length)},0),n=Array(e),a=0,s=0,o=t.length;o>s;++s)for(var l=t[s],c=r.isArray(l)?l:l.keys(),h=0,u=c.length;u>h;++h)n[a++]=c[h];return new i(n)},i.prototype.size=function(){return this._size},i.prototype.keys=function(){return n(this._keys)},i.prototype.has=function(t){return t in this._keys},i.prototype.add=function(t){return t in this._keys?!1:(this._keys[t]=t,++this._size,!0)},i.prototype.remove=function(t){return t in this._keys?(delete this._keys[t],--this._size,!0):!1}},{"./util":22}],22:[function(t,e,i){i.isArray=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},i.reduce="function"!=typeof Array.prototype.reduce?function(t,e,i){"use strict";if(null===t||t===void 0)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof e)throw new TypeError(e+" is not a function");var n,r,a=t.length>>>0,s=!1;for(arguments.length>1&&(r=i,s=!0),n=0;a>n;++n)t.hasOwnProperty(n)&&(s?r=e(r,t[n],n,t):(r=t[n],s=!0));if(!s)throw new TypeError("Reduce of empty array with no initial value");return r}:function(t,e,i){return t.reduce(e,i)}},{}],23:[function(t,e){e.exports="1.1.3"},{}],24:[function(t,e,i){i.Graph=t("./lib/Graph"),i.Digraph=t("./lib/Digraph"),i.CGraph=t("./lib/CGraph"),i.CDigraph=t("./lib/CDigraph"),t("./lib/graph-converters"),i.alg={isAcyclic:t("./lib/alg/isAcyclic"),components:t("./lib/alg/components"),dijkstra:t("./lib/alg/dijkstra"),dijkstraAll:t("./lib/alg/dijkstraAll"),findCycles:t("./lib/alg/findCycles"),floydWarshall:t("./lib/alg/floydWarshall"),postorder:t("./lib/alg/postorder"),preorder:t("./lib/alg/preorder"),prim:t("./lib/alg/prim"),tarjan:t("./lib/alg/tarjan"),topsort:t("./lib/alg/topsort")},i.converter={json:t("./lib/converter/json.js")};var n=t("./lib/filter");i.filter={all:n.all,nodesFromList:n.nodesFromList},i.version=t("./lib/version")},{"./lib/CDigraph":26,"./lib/CGraph":27,"./lib/Digraph":28,"./lib/Graph":29,"./lib/alg/components":30,"./lib/alg/dijkstra":31,"./lib/alg/dijkstraAll":32,"./lib/alg/findCycles":33,"./lib/alg/floydWarshall":34,"./lib/alg/isAcyclic":35,"./lib/alg/postorder":36,"./lib/alg/preorder":37,"./lib/alg/prim":38,"./lib/alg/tarjan":39,"./lib/alg/topsort":40,"./lib/converter/json.js":42,"./lib/filter":43,"./lib/graph-converters":44,"./lib/version":46}],25:[function(t,e){function i(){this._value=void 0,this._nodes={},this._edges={},this._nextId=0}function n(t,e,i){(t[e]||(t[e]=new a)).add(i)}function r(t,e,i){var n=t[e];n.remove(i),0===n.size()&&delete t[e]}var a=t("cp-data").Set;e.exports=i,i.prototype.order=function(){return Object.keys(this._nodes).length},i.prototype.size=function(){return Object.keys(this._edges).length},i.prototype.graph=function(t){return 0===arguments.length?this._value:(this._value=t,void 0)},i.prototype.hasNode=function(t){return t in this._nodes},i.prototype.node=function(t,e){var i=this._strictGetNode(t);return 1===arguments.length?i.value:(i.value=e,void 0)},i.prototype.nodes=function(){var t=[];return this.eachNode(function(e){t.push(e)}),t},i.prototype.eachNode=function(t){for(var e in this._nodes){var i=this._nodes[e];t(i.id,i.value)}},i.prototype.hasEdge=function(t){return t in this._edges},i.prototype.edge=function(t,e){var i=this._strictGetEdge(t);return 1===arguments.length?i.value:(i.value=e,void 0)},i.prototype.edges=function(){var t=[];return this.eachEdge(function(e){t.push(e)}),t},i.prototype.eachEdge=function(t){for(var e in this._edges){var i=this._edges[e];t(i.id,i.u,i.v,i.value)}},i.prototype.incidentNodes=function(t){var e=this._strictGetEdge(t);return[e.u,e.v]},i.prototype.addNode=function(t,e){if(void 0===t||null===t){do t="_"+ ++this._nextId;while(this.hasNode(t))}else if(this.hasNode(t))throw Error("Graph already has node '"+t+"'");return this._nodes[t]={id:t,value:e},t},i.prototype.delNode=function(t){this._strictGetNode(t),this.incidentEdges(t).forEach(function(t){this.delEdge(t)},this),delete this._nodes[t]},i.prototype._addEdge=function(t,e,i,r,a,s){if(this._strictGetNode(e),this._strictGetNode(i),void 0===t||null===t){do t="_"+ ++this._nextId;while(this.hasEdge(t))}else if(this.hasEdge(t))throw Error("Graph already has edge '"+t+"'");return this._edges[t]={id:t,u:e,v:i,value:r},n(a[i],e,t),n(s[e],i,t),t},i.prototype._delEdge=function(t,e,i){var n=this._strictGetEdge(t);r(e[n.v],n.u,t),r(i[n.u],n.v,t),delete this._edges[t]},i.prototype.copy=function(){var t=new this.constructor;return t.graph(this.graph()),this.eachNode(function(e,i){t.addNode(e,i)}),this.eachEdge(function(e,i,n,r){t.addEdge(e,i,n,r)}),t._nextId=this._nextId,t},i.prototype.filterNodes=function(t){var e=new this.constructor;return e.graph(this.graph()),this.eachNode(function(i,n){t(i)&&e.addNode(i,n)}),this.eachEdge(function(t,i,n,r){e.hasNode(i)&&e.hasNode(n)&&e.addEdge(t,i,n,r)}),e},i.prototype._strictGetNode=function(t){var e=this._nodes[t];if(void 0===e)throw Error("Node '"+t+"' is not in graph");return e},i.prototype._strictGetEdge=function(t){var e=this._edges[t];if(void 0===e)throw Error("Edge '"+t+"' is not in graph");return e}},{"cp-data":19}],26:[function(t,e){var i=t("./Digraph"),n=t("./compoundify"),r=n(i);e.exports=r,r.fromDigraph=function(t){var e=new r,i=t.graph();return void 0!==i&&e.graph(i),t.eachNode(function(t,i){void 0===i?e.addNode(t):e.addNode(t,i)}),t.eachEdge(function(t,i,n,r){void 0===r?e.addEdge(null,i,n):e.addEdge(null,i,n,r)}),e},r.prototype.toString=function(){return"CDigraph "+JSON.stringify(this,null,2)}},{"./Digraph":28,"./compoundify":41}],27:[function(t,e){var i=t("./Graph"),n=t("./compoundify"),r=n(i);
+e.exports=r,r.fromGraph=function(t){var e=new r,i=t.graph();return void 0!==i&&e.graph(i),t.eachNode(function(t,i){void 0===i?e.addNode(t):e.addNode(t,i)}),t.eachEdge(function(t,i,n,r){void 0===r?e.addEdge(null,i,n):e.addEdge(null,i,n,r)}),e},r.prototype.toString=function(){return"CGraph "+JSON.stringify(this,null,2)}},{"./Graph":29,"./compoundify":41}],28:[function(t,e){function i(){r.call(this),this._inEdges={},this._outEdges={}}var n=t("./util"),r=t("./BaseGraph"),a=t("cp-data").Set;e.exports=i,i.prototype=new r,i.prototype.constructor=i,i.prototype.isDirected=function(){return!0},i.prototype.successors=function(t){return this._strictGetNode(t),Object.keys(this._outEdges[t]).map(function(t){return this._nodes[t].id},this)},i.prototype.predecessors=function(t){return this._strictGetNode(t),Object.keys(this._inEdges[t]).map(function(t){return this._nodes[t].id},this)},i.prototype.neighbors=function(t){return a.union([this.successors(t),this.predecessors(t)]).keys()},i.prototype.sources=function(){var t=this;return this._filterNodes(function(e){return 0===t.inEdges(e).length})},i.prototype.sinks=function(){var t=this;return this._filterNodes(function(e){return 0===t.outEdges(e).length})},i.prototype.source=function(t){return this._strictGetEdge(t).u},i.prototype.target=function(t){return this._strictGetEdge(t).v},i.prototype.inEdges=function(t,e){this._strictGetNode(t);var i=a.union(n.values(this._inEdges[t])).keys();return arguments.length>1&&(this._strictGetNode(e),i=i.filter(function(t){return this.source(t)===e},this)),i},i.prototype.outEdges=function(t,e){this._strictGetNode(t);var i=a.union(n.values(this._outEdges[t])).keys();return arguments.length>1&&(this._strictGetNode(e),i=i.filter(function(t){return this.target(t)===e},this)),i},i.prototype.incidentEdges=function(t,e){return arguments.length>1?a.union([this.outEdges(t,e),this.outEdges(e,t)]).keys():a.union([this.inEdges(t),this.outEdges(t)]).keys()},i.prototype.toString=function(){return"Digraph "+JSON.stringify(this,null,2)},i.prototype.addNode=function(t,e){return t=r.prototype.addNode.call(this,t,e),this._inEdges[t]={},this._outEdges[t]={},t},i.prototype.delNode=function(t){r.prototype.delNode.call(this,t),delete this._inEdges[t],delete this._outEdges[t]},i.prototype.addEdge=function(t,e,i,n){return r.prototype._addEdge.call(this,t,e,i,n,this._inEdges,this._outEdges)},i.prototype.delEdge=function(t){r.prototype._delEdge.call(this,t,this._inEdges,this._outEdges)},i.prototype._filterNodes=function(t){var e=[];return this.eachNode(function(i){t(i)&&e.push(i)}),e}},{"./BaseGraph":25,"./util":45,"cp-data":19}],29:[function(t,e){function i(){r.call(this),this._incidentEdges={}}var n=t("./util"),r=t("./BaseGraph"),a=t("cp-data").Set;e.exports=i,i.prototype=new r,i.prototype.constructor=i,i.prototype.isDirected=function(){return!1},i.prototype.neighbors=function(t){return this._strictGetNode(t),Object.keys(this._incidentEdges[t]).map(function(t){return this._nodes[t].id},this)},i.prototype.incidentEdges=function(t,e){return this._strictGetNode(t),arguments.length>1?(this._strictGetNode(e),e in this._incidentEdges[t]?this._incidentEdges[t][e].keys():[]):a.union(n.values(this._incidentEdges[t])).keys()},i.prototype.toString=function(){return"Graph "+JSON.stringify(this,null,2)},i.prototype.addNode=function(t,e){return t=r.prototype.addNode.call(this,t,e),this._incidentEdges[t]={},t},i.prototype.delNode=function(t){r.prototype.delNode.call(this,t),delete this._incidentEdges[t]},i.prototype.addEdge=function(t,e,i,n){return r.prototype._addEdge.call(this,t,e,i,n,this._incidentEdges,this._incidentEdges)},i.prototype.delEdge=function(t){r.prototype._delEdge.call(this,t,this._incidentEdges,this._incidentEdges)}},{"./BaseGraph":25,"./util":45,"cp-data":19}],30:[function(t,e){function i(t){function e(i,n){r.has(i)||(r.add(i),n.push(i),t.neighbors(i).forEach(function(t){e(t,n)}))}var i=[],r=new n;return t.nodes().forEach(function(t){var n=[];e(t,n),n.length>0&&i.push(n)}),i}var n=t("cp-data").Set;e.exports=i},{"cp-data":19}],31:[function(t,e){function i(t,e,i,r){function a(e){var n=t.incidentNodes(e),r=n[0]!==l?n[0]:n[1],a=s[r],h=i(e),u=c.distance+h;if(0>h)throw Error("dijkstra does not allow negative edge weights. Bad edge: "+e+" Weight: "+h);a.distance>u&&(a.distance=u,a.predecessor=l,o.decrease(r,u))}var s={},o=new n;i=i||function(){return 1},r=r||(t.isDirected()?function(e){return t.outEdges(e)}:function(e){return t.incidentEdges(e)}),t.eachNode(function(t){var i=t===e?0:Number.POSITIVE_INFINITY;s[t]={distance:i},o.add(t,i)});for(var l,c;o.size()>0&&(l=o.removeMin(),c=s[l],c.distance!==Number.POSITIVE_INFINITY);)r(l).forEach(a);return s}var n=t("cp-data").PriorityQueue;e.exports=i},{"cp-data":19}],32:[function(t,e){function i(t,e,i){var r={};return t.eachNode(function(a){r[a]=n(t,a,e,i)}),r}var n=t("./dijkstra");e.exports=i},{"./dijkstra":31}],33:[function(t,e){function i(t){return n(t).filter(function(t){return t.length>1})}var n=t("./tarjan");e.exports=i},{"./tarjan":39}],34:[function(t,e){function i(t,e,i){var n={},r=t.nodes();return e=e||function(){return 1},i=i||(t.isDirected()?function(e){return t.outEdges(e)}:function(e){return t.incidentEdges(e)}),r.forEach(function(a){n[a]={},n[a][a]={distance:0},r.forEach(function(t){a!==t&&(n[a][t]={distance:Number.POSITIVE_INFINITY})}),i(a).forEach(function(i){var r=t.incidentNodes(i),s=r[0]!==a?r[0]:r[1],o=e(i);n[a][s].distance>o&&(n[a][s]={distance:o,predecessor:a})})}),r.forEach(function(t){var e=n[t];r.forEach(function(i){var a=n[i];r.forEach(function(i){var n=a[t],r=e[i],s=a[i],o=n.distance+r.distance;s.distance>o&&(s.distance=o,s.predecessor=r.predecessor)})})}),n}e.exports=i},{}],35:[function(t,e){function i(t){try{n(t)}catch(e){if(e instanceof n.CycleException)return!1;throw e}return!0}var n=t("./topsort");e.exports=i},{"./topsort":40}],36:[function(t,e){function i(t,e,i){function r(e,n){if(a.has(e))throw Error("The input graph is not a tree: "+t);a.add(e),t.neighbors(e).forEach(function(t){t!==n&&r(t,e)}),i(e)}var a=new n;if(t.isDirected())throw Error("This function only works for undirected graphs");r(e)}var n=t("cp-data").Set;e.exports=i},{"cp-data":19}],37:[function(t,e){function i(t,e,i){function r(e,n){if(a.has(e))throw Error("The input graph is not a tree: "+t);a.add(e),i(e),t.neighbors(e).forEach(function(t){t!==n&&r(t,e)})}var a=new n;if(t.isDirected())throw Error("This function only works for undirected graphs");r(e)}var n=t("cp-data").Set;e.exports=i},{"cp-data":19}],38:[function(t,e){function i(t,e){function i(i){var n=t.incidentNodes(i),r=n[0]!==a?n[0]:n[1],s=l.priority(r);if(void 0!==s){var c=e(i);s>c&&(o[r]=a,l.decrease(r,c))}}var a,s=new n,o={},l=new r;if(0===t.order())return s;t.eachNode(function(t){l.add(t,Number.POSITIVE_INFINITY),s.addNode(t)}),l.decrease(t.nodes()[0],0);for(var c=!1;l.size()>0;){if(a=l.removeMin(),a in o)s.addEdge(null,a,o[a]);else{if(c)throw Error("Input graph is not connected: "+t);c=!0}t.incidentEdges(a).forEach(i)}return s}var n=t("../Graph"),r=t("cp-data").PriorityQueue;e.exports=i},{"../Graph":29,"cp-data":19}],39:[function(t,e){function i(t){function e(s){var o=r[s]={onStack:!0,lowlink:i,index:i++};if(n.push(s),t.successors(s).forEach(function(t){t in r?r[t].onStack&&(o.lowlink=Math.min(o.lowlink,r[t].index)):(e(t),o.lowlink=Math.min(o.lowlink,r[t].lowlink))}),o.lowlink===o.index){var l,c=[];do l=n.pop(),r[l].onStack=!1,c.push(l);while(s!==l);a.push(c)}}if(!t.isDirected())throw Error("tarjan can only be applied to a directed graph. Bad input: "+t);var i=0,n=[],r={},a=[];return t.nodes().forEach(function(t){t in r||e(t)}),a}e.exports=i},{}],40:[function(t,e){function i(t){function e(s){if(s in r)throw new n;s in i||(r[s]=!0,i[s]=!0,t.predecessors(s).forEach(function(t){e(t)}),delete r[s],a.push(s))}if(!t.isDirected())throw Error("topsort can only be applied to a directed graph. Bad input: "+t);var i={},r={},a=[],s=t.sinks();if(0!==t.order()&&0===s.length)throw new n;return t.sinks().forEach(function(t){e(t)}),a}function n(){}e.exports=i,i.CycleException=n,n.prototype.toString=function(){return"Graph has at least one cycle"}},{}],41:[function(t,e){function i(t){function e(){t.call(this),this._parents={},this._children={},this._children[null]=new n}return e.prototype=new t,e.prototype.constructor=e,e.prototype.parent=function(t,e){if(this._strictGetNode(t),2>arguments.length)return this._parents[t];if(t===e)throw Error("Cannot make "+t+" a parent of itself");null!==e&&this._strictGetNode(e),this._children[this._parents[t]].remove(t),this._parents[t]=e,this._children[e].add(t)},e.prototype.children=function(t){return null!==t&&this._strictGetNode(t),this._children[t].keys()},e.prototype.addNode=function(e,i){return e=t.prototype.addNode.call(this,e,i),this._parents[e]=null,this._children[e]=new n,this._children[null].add(e),e},e.prototype.delNode=function(e){var i=this.parent(e);return this._children[e].keys().forEach(function(t){this.parent(t,i)},this),this._children[i].remove(e),delete this._parents[e],delete this._children[e],t.prototype.delNode.call(this,e)},e.prototype.copy=function(){var e=t.prototype.copy.call(this);return this.nodes().forEach(function(t){e.parent(t,this.parent(t))},this),e},e.prototype.filterNodes=function(e){function i(t){var e=n.parent(t);return null===e||r.hasNode(e)?(a[t]=e,e):e in a?a[e]:i(e)}var n=this,r=t.prototype.filterNodes.call(this,e),a={};return r.eachNode(function(t){r.parent(t,i(t))}),r},e}var n=t("cp-data").Set;e.exports=i},{"cp-data":19}],42:[function(t,e,i){function n(t){return Object.prototype.toString.call(t).slice(8,-1)}var r=t("../Graph"),a=t("../Digraph"),s=t("../CGraph"),o=t("../CDigraph");i.decode=function(t,e,i){if(i=i||a,"Array"!==n(t))throw Error("nodes is not an Array");if("Array"!==n(e))throw Error("edges is not an Array");if("string"==typeof i)switch(i){case"graph":i=r;break;case"digraph":i=a;break;case"cgraph":i=s;break;case"cdigraph":i=o;break;default:throw Error("Unrecognized graph type: "+i)}var l=new i;return t.forEach(function(t){l.addNode(t.id,t.value)}),l.parent&&t.forEach(function(t){t.children&&t.children.forEach(function(e){l.parent(e,t.id)})}),e.forEach(function(t){l.addEdge(t.id,t.u,t.v,t.value)}),l},i.encode=function(t){var e=[],i=[];t.eachNode(function(i,n){var r={id:i,value:n};if(t.children){var a=t.children(i);a.length&&(r.children=a)}e.push(r)}),t.eachEdge(function(t,e,n,r){i.push({id:t,u:e,v:n,value:r})});var n;if(t instanceof o)n="cdigraph";else if(t instanceof s)n="cgraph";else if(t instanceof a)n="digraph";else{if(!(t instanceof r))throw Error("Couldn't determine type of graph: "+t);n="graph"}return{nodes:e,edges:i,type:n}}},{"../CDigraph":26,"../CGraph":27,"../Digraph":28,"../Graph":29}],43:[function(t,e,i){var n=t("cp-data").Set;i.all=function(){return function(){return!0}},i.nodesFromList=function(t){var e=new n(t);return function(t){return e.has(t)}}},{"cp-data":19}],44:[function(t){var e=t("./Graph"),i=t("./Digraph");e.prototype.toDigraph=e.prototype.asDirected=function(){var t=new i;return this.eachNode(function(e,i){t.addNode(e,i)}),this.eachEdge(function(e,i,n,r){t.addEdge(null,i,n,r),t.addEdge(null,n,i,r)}),t},i.prototype.toGraph=i.prototype.asUndirected=function(){var t=new e;return this.eachNode(function(e,i){t.addNode(e,i)}),this.eachEdge(function(e,i,n,r){t.addEdge(e,i,n,r)}),t}},{"./Digraph":28,"./Graph":29}],45:[function(t,e,i){i.values=function(t){var e,i=Object.keys(t),n=i.length,r=Array(n);for(e=0;n>e;++e)r[e]=t[i[e]];return r}},{}],46:[function(t,e){e.exports="0.7.4"},{}]},{},[1]),joint.layout.DirectedGraph={layout:function(t,e){e=e||{};var i=this._prepareData(t),n=dagre.layout();e.debugLevel&&n.debugLevel(e.debugLevel),e.rankDir&&n.rankDir(e.rankDir),e.rankSep&&n.rankSep(e.rankSep),e.edgeSep&&n.edgeSep(e.edgeSep),e.nodeSep&&n.nodeSep(e.nodeSep);var r=n.run(i);return r.eachNode(function(e,i){i.dummy||t.get("cells").get(e).set("position",{x:i.x-i.width/2,y:i.y-i.height/2})}),e.setLinkVertices&&r.eachEdge(function(e,i,n,r){var a=t.get("cells").get(e);a&&t.get("cells").get(e).set("vertices",r.points)}),{width:r.graph().width,height:r.graph().height}},_prepareData:function(t){var e=new dagre.Digraph;return _.each(t.getElements(),function(t){e.hasNode(t.id)||e.addNode(t.id,{width:t.get("size").width,height:t.get("size").height,rank:t.get("rank")})}),_.each(t.getLinks(),function(t){if(!e.hasEdge(t.id)){var i=t.get("source").id,n=t.get("target").id;e.addEdge(t.id,i,n,{minLen:t.get("minLen")||1})}}),e}},joint.layout.ForceDirected=Backbone.Model.extend({defaults:{linkDistance:10,linkStrength:1,charge:10},initialize:function(){this.elements=this.get("graph").getElements(),this.links=this.get("graph").getLinks(),this.cells=this.get("graph").get("cells"),this.width=this.get("width"),this.height=this.get("height"),this.gravityCenter=this.get("gravityCenter"),this.t=1,this.energy=1/0,this.progress=0},start:function(){var t=this.get("width"),e=this.get("height");_.each(this.elements,function(i){i.set("position",{x:Math.random()*t,y:Math.random()*e}),i.charge=i.get("charge")||this.get("charge"),i.weight=i.get("weight")||1;var n=i.get("position");i.x=n.x,i.y=n.y,i.px=i.x,i.py=i.y,i.fx=0,i.fy=0},this),_.each(this.links,function(t){t.strength=t.get("strength")||this.get("linkStrength"),t.distance=t.get("distance")||this.get("linkDistance"),t.source=this.cells.get(t.get("source").id),t.target=this.cells.get(t.get("target").id)},this)},step:function(){if(.005>.99*this.t)return this.notifyEnd();var t=this.width,e=this.height,i=.1,n=this.gravityCenter,r=this.energy;this.energy=0;var a,s,o=0,l=0,c=0,h=0,u=this.elements.length,p=this.links.length;for(a=0;u-1>a;a++){var g=this.elements[a];for(o+=g.x,l+=g.y,s=a+1;u>s;s++){var d=this.elements[s],f=d.x-g.x,m=d.y-g.y,I=f*f+m*m,y=Math.sqrt(I),v=this.t*g.charge/I,C=v*f,b=v*m;g.fx-=C,g.fy-=b,d.fx+=C,d.fy+=b,this.energy+=C*C+b*b}}for(o+=this.elements[u-1].x,l+=this.elements[u-1].y,a=0;p>a;a++){var A=this.links[a],g=A.source,d=A.target,f=d.x-g.x,m=d.y-g.y,I=f*f+m*m,y=Math.sqrt(I),w=this.t*A.strength*(y-A.distance)/y,C=w*f,b=w*m,x=g.weight/(g.weight+d.weight);g.x+=C*(1-x),g.y+=b*(1-x),d.x-=C*x,d.y-=b*x,this.energy+=C*C+b*b}for(a=0;u>a;a++){var M=this.elements[a],j={x:M.x,y:M.y};n&&(j.x+=(n.x-j.x)*this.t*i,j.y+=(n.y-j.y)*this.t*i),j.x+=M.fx,j.y+=M.fy,j.x=Math.max(0,Math.min(t,j.x)),j.y=Math.max(0,Math.min(e,j.y));var N=.9;j.x+=(M.px-j.x)*N,j.y+=(M.py-j.y)*N,M.px=j.x,M.py=j.y,M.fx=M.fy=0,M.x=j.x,M.y=j.y,c+=M.x,h+=M.y,this.notify(M,a,j)}this.t=this.cool(this.t,this.energy,r);var k=o-c,D=l-h,z=Math.sqrt(k*k+D*D);1>z&&this.notifyEnd()},cool:function(t,e,i){return i>e?(this.progress+=1,this.progress>=5?(this.progress=0,t/.99):t):(this.progress=0,.99*t)},notify:function(t,e,i){t.set("position",i)},notifyEnd:function(){this.trigger("end")}}),joint.layout=joint.layout||{},joint.layout.GridLayout={layout:function(t,e){e=e||{};var i=t.getElements(),n=e.columns||1,r=e.dx||0,a=e.dy||0,s=e.columnWidth||this._maxDim(i,"width")+r,o=e.rowHeight||this._maxDim(i,"height")+a,l=_.isUndefined(e.centralize)||e.centralize!==!1,c=!!e.resizeToFit;_.each(i,function(t,e){var i=0,h=0,u=t.get("size");if(c){var p=s-2*r,g=o-2*a,d=u.height*(u.width?p/u.width:1),f=u.width*(u.height?g/u.height:1);d>o?p=f:g=d,u={width:p,height:g},t.set("size",u)}l&&(i=(s-u.width)/2,h=(o-u.height)/2),t.set("position",{x:e%n*s+r+i,y:Math.floor(e/n)*o+a+h})})},_maxDim:function(t,e){return _.reduce(t,function(t,i){return Math.max(i.get("size")[e],t)},0)}},joint.format.gexf={},joint.format.gexf.toCellsArray=function(t,e,i){var n=new DOMParser,r=n.parseFromString(t,"text/xml");if("parsererror"==r.documentElement.nodeName)throw Error("Error while parsing GEXF file.");var a=r.documentElement.querySelectorAll("node"),s=r.documentElement.querySelectorAll("edge"),o=[];return _.each(a,function(t){var i=parseFloat(t.querySelector("size").getAttribute("value")),n=e({id:t.getAttribute("id"),width:i,height:i,label:t.getAttribute("label")});o.push(n)}),_.each(s,function(t){var e=i({source:t.getAttribute("source"),target:t.getAttribute("target")});o.unshift(e)}),o},joint.dia.Paper.prototype.toSVG=function(t){t=t||{};var e=V(this.viewport).attr("transform");V(this.viewport).attr("transform","");var i=this.getContentBBox(),n=this.svg.cloneNode(!0);V(this.viewport).attr("transform",e||""),n.removeAttribute("style"),t.preserveDimensions?V(n).attr({width:i.width,height:i.height}):V(n).attr({width:"100%",height:"100%"}),V(n).attr("viewBox",i.x+" "+i.y+" "+i.width+" "+i.height);for(var r=document.styleSheets.length,a=[],s=r-1;s>=0;s--)a[s]=document.styleSheets[s],document.styleSheets[s].disabled=!0;var o={};$(this.svg).find("*").each(function(t){var e=window.getComputedStyle(this,null),i={};_.each(e,function(t){i[t]=e.getPropertyValue(t)}),o[t]=i}),r!=document.styleSheets.length&&_.each(a,function(t,e){document.styleSheets[e]=t});for(var s=0;r>s;s++)document.styleSheets[s].disabled=!1;var l={};$(this.svg).find("*").each(function(t){var e=window.getComputedStyle(this,null),i=o[t],n={};_.each(e,function(t){e.getPropertyValue(t)!==i[t]&&(n[t]=e.getPropertyValue(t))}),l[t]=n}),$(n).find("*").each(function(t){$(this).css(l[t])}),$(n).find(".connection-wrap, .marker-vertices, .link-tools, .marker-arrowheads").remove();var c;try{var h=new XMLSerializer;c=h.serializeToString(n)}catch(u){console.error("Error serializing paper to SVG:",u)}var p=!!window.chrome&&!window.opera,g="Microsoft Internet Explorer"==navigator.appName,d=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0;if(p&&(c=c.replace('xlink="','xmlns:xlink="')),g){var f='xmlns="'+this.svg.namespaceURI+'"',m=c.match(RegExp(f,"g"));m&&m.length>=2&&(c=c.replace(RegExp(f),""))}return d&&(c=c.replace('xlink="','xmlns:xlink="'),c=c.replace(/href="/g,'xlink:href="')),c},joint.dia.Paper.prototype.openAsSVG=function(){var t=this.toSVG(),e="menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes",i=_.uniqueId("svg_output"),n="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(t))),r=window.open("",i,e);r.document.write('<img src="'+n+'" style="max-height:100%" />')},function(){function t(){var t={};return t.FRAMERATE=30,t.MAX_VIRTUAL_PIXELS=3e4,t.init=function(e){var i=0;t.UniqueId=function(){return i++,"canvg"+i},t.Definitions={},t.Styles={},t.Animations=[],t.Images=[],t.ctx=e,t.ViewPort=new function(){this.viewPorts=[],this.Clear=function(){this.viewPorts=[]},this.SetCurrent=function(t,e){this.viewPorts.push({width:t,height:e})},this.RemoveCurrent=function(){this.viewPorts.pop()},this.Current=function(){return this.viewPorts[this.viewPorts.length-1]},this.width=function(){return this.Current().width},this.height=function(){return this.Current().height},this.ComputeSize=function(t){return null!=t&&"number"==typeof t?t:"x"==t?this.width():"y"==t?this.height():Math.sqrt(Math.pow(this.width(),2)+Math.pow(this.height(),2))/Math.sqrt(2)}}},t.init(),t.ImagesLoaded=function(){for(var e=0;t.Images.length>e;e++)if(!t.Images[e].loaded)return!1;return!0},t.trim=function(t){return t.replace(/^\s+|\s+$/g,"")},t.compressSpaces=function(t){return t.replace(/[\s\r\t\n]+/gm," ")},t.ajax=function(t){var e;return e=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),e?(e.open("GET",t,!1),e.send(null),e.responseText):null},t.parseXml=function(t){if(window.DOMParser){var e=new DOMParser;return e.parseFromString(t,"text/xml")}t=t.replace(/<!DOCTYPE svg[^>]*>/,"");var i=new ActiveXObject("Microsoft.XMLDOM");return i.async="false",i.loadXML(t),i},t.Property=function(t,e){this.name=t,this.value=e},t.Property.prototype.getValue=function(){return this.value},t.Property.prototype.hasValue=function(){return null!=this.value&&""!==this.value},t.Property.prototype.numValue=function(){if(!this.hasValue())return 0;var t=parseFloat(this.value);return(this.value+"").match(/%$/)&&(t/=100),t},t.Property.prototype.valueOrDefault=function(t){return this.hasValue()?this.value:t},t.Property.prototype.numValueOrDefault=function(t){return this.hasValue()?this.numValue():t},t.Property.prototype.addOpacity=function(e){var i=this.value;if(null!=e&&""!=e&&"string"==typeof this.value){var n=new RGBColor(this.value);n.ok&&(i="rgba("+n.r+", "+n.g+", "+n.b+", "+e+")")}return new t.Property(this.name,i)},t.Property.prototype.getDefinition=function(){var e=this.value.match(/#([^\)'"]+)/);return e&&(e=e[1]),e||(e=this.value),t.Definitions[e]},t.Property.prototype.isUrlDefinition=function(){return 0==this.value.indexOf("url(")},t.Property.prototype.getFillStyleDefinition=function(e,i){var n=this.getDefinition();if(null!=n&&n.createGradient)return n.createGradient(t.ctx,e,i);if(null!=n&&n.createPattern){if(n.getHrefAttribute().hasValue()){var r=n.attribute("patternTransform");n=n.getHrefAttribute().getDefinition(),r.hasValue()&&(n.attribute("patternTransform",!0).value=r.value)}return n.createPattern(t.ctx,e)}return null},t.Property.prototype.getDPI=function(){return 96},t.Property.prototype.getEM=function(e){var i=12,n=new t.Property("fontSize",t.Font.Parse(t.ctx.font).fontSize);return n.hasValue()&&(i=n.toPixels(e)),i},t.Property.prototype.getUnits=function(){var t=this.value+"";return t.replace(/[0-9\.\-]/g,"")},t.Property.prototype.toPixels=function(e,i){if(!this.hasValue())return 0;var n=this.value+"";if(n.match(/em$/))return this.numValue()*this.getEM(e);if(n.match(/ex$/))return this.numValue()*this.getEM(e)/2;if(n.match(/px$/))return this.numValue();if(n.match(/pt$/))return this.numValue()*this.getDPI(e)*(1/72);if(n.match(/pc$/))return 15*this.numValue();if(n.match(/cm$/))return this.numValue()*this.getDPI(e)/2.54;if(n.match(/mm$/))return this.numValue()*this.getDPI(e)/25.4;if(n.match(/in$/))return this.numValue()*this.getDPI(e);if(n.match(/%$/))return this.numValue()*t.ViewPort.ComputeSize(e);var r=this.numValue();return i&&1>r?r*t.ViewPort.ComputeSize(e):r},t.Property.prototype.toMilliseconds=function(){if(!this.hasValue())return 0;var t=this.value+"";return t.match(/s$/)?1e3*this.numValue():t.match(/ms$/)?this.numValue():this.numValue()},t.Property.prototype.toRadians=function(){if(!this.hasValue())return 0;var t=this.value+"";return t.match(/deg$/)?this.numValue()*(Math.PI/180):t.match(/grad$/)?this.numValue()*(Math.PI/200):t.match(/rad$/)?this.numValue():this.numValue()*(Math.PI/180)},t.Font=new function(){this.Styles="normal|italic|oblique|inherit",this.Variants="normal|small-caps|inherit",this.Weights="normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit",this.CreateFont=function(e,i,n,r,a,s){var o=null!=s?this.Parse(s):this.CreateFont("","","","","",t.ctx.font);return{fontFamily:a||o.fontFamily,fontSize:r||o.fontSize,fontStyle:e||o.fontStyle,fontWeight:n||o.fontWeight,fontVariant:i||o.fontVariant,toString:function(){return[this.fontStyle,this.fontVariant,this.fontWeight,this.fontSize,this.fontFamily].join(" ")}}};var e=this;this.Parse=function(i){for(var n={},r=t.trim(t.compressSpaces(i||"")).split(" "),a={fontSize:!1,fontStyle:!1,fontWeight:!1,fontVariant:!1},s="",o=0;r.length>o;o++)a.fontStyle||-1==e.Styles.indexOf(r[o])?a.fontVariant||-1==e.Variants.indexOf(r[o])?a.fontWeight||-1==e.Weights.indexOf(r[o])?a.fontSize?"inherit"!=r[o]&&(s+=r[o]):("inherit"!=r[o]&&(n.fontSize=r[o].split("/")[0]),a.fontStyle=a.fontVariant=a.fontWeight=a.fontSize=!0):("inherit"!=r[o]&&(n.fontWeight=r[o]),a.fontStyle=a.fontVariant=a.fontWeight=!0):("inherit"!=r[o]&&(n.fontVariant=r[o]),a.fontStyle=a.fontVariant=!0):("inherit"!=r[o]&&(n.fontStyle=r[o]),a.fontStyle=!0);return""!=s&&(n.fontFamily=s),n}},t.ToNumberArray=function(e){for(var i=t.trim(t.compressSpaces((e||"").replace(/,/g," "))).split(" "),n=0;i.length>n;n++)i[n]=parseFloat(i[n]);return i},t.Point=function(t,e){this.x=t,this.y=e},t.Point.prototype.angleTo=function(t){return Math.atan2(t.y-this.y,t.x-this.x)},t.Point.prototype.applyTransform=function(t){var e=this.x*t[0]+this.y*t[2]+t[4],i=this.x*t[1]+this.y*t[3]+t[5];this.x=e,this.y=i},t.CreatePoint=function(e){var i=t.ToNumberArray(e);return new t.Point(i[0],i[1])},t.CreatePath=function(e){for(var i=t.ToNumberArray(e),n=[],r=0;i.length>r;r+=2)n.push(new t.Point(i[r],i[r+1]));return n},t.BoundingBox=function(t,e,n,r){this.x1=Number.NaN,this.y1=Number.NaN,this.x2=Number.NaN,this.y2=Number.NaN,this.x=function(){return this.x1},this.y=function(){return this.y1},this.width=function(){return this.x2-this.x1},this.height=function(){return this.y2-this.y1},this.addPoint=function(t,e){null!=t&&((isNaN(this.x1)||isNaN(this.x2))&&(this.x1=t,this.x2=t),this.x1>t&&(this.x1=t),t>this.x2&&(this.x2=t)),null!=e&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=e,this.y2=e),this.y1>e&&(this.y1=e),e>this.y2&&(this.y2=e))},this.addX=function(t){this.addPoint(t,null)},this.addY=function(t){this.addPoint(null,t)},this.addBoundingBox=function(t){this.addPoint(t.x1,t.y1),this.addPoint(t.x2,t.y2)},this.addQuadraticCurve=function(t,e,i,n,r,a){var s=t+2/3*(i-t),o=e+2/3*(n-e),l=s+1/3*(r-t),c=o+1/3*(a-e);this.addBezierCurve(t,e,s,l,o,c,r,a)},this.addBezierCurve=function(t,e,n,r,a,s,o,l){var c=[t,e],h=[n,r],u=[a,s],p=[o,l];for(this.addPoint(c[0],c[1]),this.addPoint(p[0],p[1]),i=0;1>=i;i++){var g=function(t){return Math.pow(1-t,3)*c[i]+3*Math.pow(1-t,2)*t*h[i]+3*(1-t)*Math.pow(t,2)*u[i]+Math.pow(t,3)*p[i]},d=6*c[i]-12*h[i]+6*u[i],f=-3*c[i]+9*h[i]-9*u[i]+3*p[i],m=3*h[i]-3*c[i];if(0!=f){var I=Math.pow(d,2)-4*m*f;if(!(0>I)){var y=(-d+Math.sqrt(I))/(2*f);y>0&&1>y&&(0==i&&this.addX(g(y)),1==i&&this.addY(g(y)));var v=(-d-Math.sqrt(I))/(2*f);v>0&&1>v&&(0==i&&this.addX(g(v)),1==i&&this.addY(g(v)))}}else{if(0==d)continue;var C=-m/d;C>0&&1>C&&(0==i&&this.addX(g(C)),1==i&&this.addY(g(C)))}}},this.isPointInBox=function(t,e){return t>=this.x1&&this.x2>=t&&e>=this.y1&&this.y2>=e},this.addPoint(t,e),this.addPoint(n,r)},t.Transform=function(e){var i=this;this.Type={},this.Type.translate=function(e){this.p=t.CreatePoint(e),this.apply=function(t){t.translate(this.p.x||0,this.p.y||0)},this.unapply=function(t){t.translate(-1*this.p.x||0,-1*this.p.y||0)},this.applyToPoint=function(t){t.applyTransform([1,0,0,1,this.p.x||0,this.p.y||0])}},this.Type.rotate=function(e){var i=t.ToNumberArray(e);this.angle=new t.Property("angle",i[0]),this.cx=i[1]||0,this.cy=i[2]||0,this.apply=function(t){t.translate(this.cx,this.cy),t.rotate(this.angle.toRadians()),t.translate(-this.cx,-this.cy)},this.unapply=function(t){t.translate(this.cx,this.cy),t.rotate(-1*this.angle.toRadians()),t.translate(-this.cx,-this.cy)},this.applyToPoint=function(t){var e=this.angle.toRadians();t.applyTransform([1,0,0,1,this.p.x||0,this.p.y||0]),t.applyTransform([Math.cos(e),Math.sin(e),-Math.sin(e),Math.cos(e),0,0]),t.applyTransform([1,0,0,1,-this.p.x||0,-this.p.y||0])}},this.Type.scale=function(e){this.p=t.CreatePoint(e),this.apply=function(t){t.scale(this.p.x||1,this.p.y||this.p.x||1)},this.unapply=function(t){t.scale(1/this.p.x||1,1/this.p.y||this.p.x||1)},this.applyToPoint=function(t){t.applyTransform([this.p.x||0,0,0,this.p.y||0,0,0])}},this.Type.matrix=function(e){this.m=t.ToNumberArray(e),this.apply=function(t){t.transform(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5])},this.applyToPoint=function(t){t.applyTransform(this.m)}},this.Type.SkewBase=function(e){this.base=i.Type.matrix,this.base(e),this.angle=new t.Property("angle",e)},this.Type.SkewBase.prototype=new this.Type.matrix,this.Type.skewX=function(t){this.base=i.Type.SkewBase,this.base(t),this.m=[1,0,Math.tan(this.angle.toRadians()),1,0,0]},this.Type.skewX.prototype=new this.Type.SkewBase,this.Type.skewY=function(t){this.base=i.Type.SkewBase,this.base(t),this.m=[1,Math.tan(this.angle.toRadians()),0,1,0,0]},this.Type.skewY.prototype=new this.Type.SkewBase,this.transforms=[],this.apply=function(t){for(var e=0;this.transforms.length>e;e++)this.transforms[e].apply(t)},this.unapply=function(t){for(var e=this.transforms.length-1;e>=0;e--)this.transforms[e].unapply(t)},this.applyToPoint=function(t){for(var e=0;this.transforms.length>e;e++)this.transforms[e].applyToPoint(t)};for(var n=t.trim(t.compressSpaces(e)).replace(/\)(\s?,\s?)/g,") ").split(/\s(?=[a-z])/),r=0;n.length>r;r++){var a=t.trim(n[r].split("(")[0]),s=n[r].split("(")[1].replace(")",""),o=new this.Type[a](s);o.type=a,this.transforms.push(o)}},t.AspectRatio=function(e,i,n,r,a,s,o,l,c,h){i=t.compressSpaces(i),i=i.replace(/^defer\s/,"");var u=i.split(" ")[0]||"xMidYMid",p=i.split(" ")[1]||"meet",g=n/r,d=a/s,f=Math.min(g,d),m=Math.max(g,d);"meet"==p&&(r*=f,s*=f),"slice"==p&&(r*=m,s*=m),c=new t.Property("refX",c),h=new t.Property("refY",h),c.hasValue()&&h.hasValue()?e.translate(-f*c.toPixels("x"),-f*h.toPixels("y")):(u.match(/^xMid/)&&("meet"==p&&f==d||"slice"==p&&m==d)&&e.translate(n/2-r/2,0),u.match(/YMid$/)&&("meet"==p&&f==g||"slice"==p&&m==g)&&e.translate(0,a/2-s/2),u.match(/^xMax/)&&("meet"==p&&f==d||"slice"==p&&m==d)&&e.translate(n-r,0),u.match(/YMax$/)&&("meet"==p&&f==g||"slice"==p&&m==g)&&e.translate(0,a-s)),"none"==u?e.scale(g,d):"meet"==p?e.scale(f,f):"slice"==p&&e.scale(m,m),e.translate(null==o?0:-o,null==l?0:-l)},t.Element={},t.EmptyProperty=new t.Property("EMPTY",""),t.Element.ElementBase=function(e){if(this.attributes={},this.styles={},this.children=[],this.attribute=function(e,i){var n=this.attributes[e];return null!=n?n:(1==i&&(n=new t.Property(e,""),this.attributes[e]=n),n||t.EmptyProperty)},this.getHrefAttribute=function(){for(var e in this.attributes)if(e.match(/:href$/))return this.attributes[e];return t.EmptyProperty},this.style=function(e,i){var n=this.styles[e];if(null!=n)return n;var r=this.attribute(e);if(null!=r&&r.hasValue())return this.styles[e]=r,r;var a=this.parent;if(null!=a){var s=a.style(e);if(null!=s&&s.hasValue())return s}return 1==i&&(n=new t.Property(e,""),this.styles[e]=n),n||t.EmptyProperty},this.render=function(t){if("none"!=this.style("display").value&&"hidden"!=this.attribute("visibility").value){if(t.save(),this.attribute("mask").hasValue()){var e=this.attribute("mask").getDefinition();null!=e&&e.apply(t,this)}else if(this.style("filter").hasValue()){var i=this.style("filter").getDefinition();null!=i&&i.apply(t,this)}else this.setContext(t),this.renderChildren(t),this.clearContext(t);t.restore()}},this.setContext=function(){},this.clearContext=function(){},this.renderChildren=function(t){for(var e=0;this.children.length>e;e++)this.children[e].render(t)},this.addChild=function(e,i){var n=e;i&&(n=t.CreateElement(e)),n.parent=this,this.children.push(n)},null!=e&&1==e.nodeType){for(var i=0;e.childNodes.length>i;i++){var n=e.childNodes[i];if(1==n.nodeType&&this.addChild(n,!0),this.captureTextNodes&&3==n.nodeType){var r=n.nodeValue||n.text||"";""!=t.trim(t.compressSpaces(r))&&this.addChild(new t.Element.tspan(n),!1)}}for(var i=0;e.attributes.length>i;i++){var a=e.attributes[i];this.attributes[a.nodeName]=new t.Property(a.nodeName,a.nodeValue)}var s=t.Styles[e.nodeName];if(null!=s)for(var o in s)this.styles[o]=s[o];if(this.attribute("class").hasValue())for(var l=t.compressSpaces(this.attribute("class").value).split(" "),c=0;l.length>c;c++){if(s=t.Styles["."+l[c]],null!=s)for(var o in s)this.styles[o]=s[o];if(s=t.Styles[e.nodeName+"."+l[c]],null!=s)for(var o in s)this.styles[o]=s[o]}if(this.attribute("id").hasValue()){var s=t.Styles["#"+this.attribute("id").value];if(null!=s)for(var o in s)this.styles[o]=s[o]}if(this.attribute("style").hasValue())for(var s=this.attribute("style").value.split(";"),i=0;s.length>i;i++)if(""!=t.trim(s[i])){var h=s[i].split(":"),o=t.trim(h[0]),u=t.trim(h[1]);this.styles[o]=new t.Property(o,u)}this.attribute("id").hasValue()&&null==t.Definitions[this.attribute("id").value]&&(t.Definitions[this.attribute("id").value]=this)}},t.Element.RenderedElementBase=function(e){this.base=t.Element.ElementBase,this.base(e),this.setContext=function(e){if(this.style("fill").isUrlDefinition()){var i=this.style("fill").getFillStyleDefinition(this,this.style("fill-opacity"));null!=i&&(e.fillStyle=i)}else if(this.style("fill").hasValue()){var n=this.style("fill");"currentColor"==n.value&&(n.value=this.style("color").value),e.fillStyle="none"==n.value?"rgba(0,0,0,0)":n.value
+}if(this.style("fill-opacity").hasValue()){var n=new t.Property("fill",e.fillStyle);n=n.addOpacity(this.style("fill-opacity").value),e.fillStyle=n.value}if(this.style("stroke").isUrlDefinition()){var i=this.style("stroke").getFillStyleDefinition(this,this.style("stroke-opacity"));null!=i&&(e.strokeStyle=i)}else if(this.style("stroke").hasValue()){var r=this.style("stroke");"currentColor"==r.value&&(r.value=this.style("color").value),e.strokeStyle="none"==r.value?"rgba(0,0,0,0)":r.value}if(this.style("stroke-opacity").hasValue()){var r=new t.Property("stroke",e.strokeStyle);r=r.addOpacity(this.style("stroke-opacity").value),e.strokeStyle=r.value}if(this.style("stroke-width").hasValue()){var a=this.style("stroke-width").toPixels();e.lineWidth=0==a?.001:a}if(this.style("stroke-linecap").hasValue()&&(e.lineCap=this.style("stroke-linecap").value),this.style("stroke-linejoin").hasValue()&&(e.lineJoin=this.style("stroke-linejoin").value),this.style("stroke-miterlimit").hasValue()&&(e.miterLimit=this.style("stroke-miterlimit").value),this.style("stroke-dasharray").hasValue()){var s=t.ToNumberArray(this.style("stroke-dasharray").value);e.setLineDash!==void 0?e.setLineDash(s):e.webkitLineDash!==void 0?e.webkitLineDash=s:e.mozDash!==void 0&&(e.mozDash=s);var o=this.style("stroke-dashoffset").numValueOrDefault(1);e.lineDashOffset!==void 0?e.lineDashOffset=o:e.webkitLineDashOffset!==void 0?e.webkitLineDashOffset=o:e.mozDashOffset!==void 0&&(e.mozDashOffset=o)}if(e.font!==void 0&&(e.font=""+t.Font.CreateFont(this.style("font-style").value,this.style("font-variant").value,this.style("font-weight").value,this.style("font-size").hasValue()?this.style("font-size").toPixels()+"px":"",this.style("font-family").value)),this.attribute("transform").hasValue()){var l=new t.Transform(this.attribute("transform").value);l.apply(e)}if(this.style("clip-path").hasValue()){var c=this.style("clip-path").getDefinition();null!=c&&c.apply(e)}this.style("opacity").hasValue()&&(e.globalAlpha=this.style("opacity").numValue())}},t.Element.RenderedElementBase.prototype=new t.Element.ElementBase,t.Element.PathElementBase=function(e){this.base=t.Element.RenderedElementBase,this.base(e),this.path=function(e){return null!=e&&e.beginPath(),new t.BoundingBox},this.renderChildren=function(e){this.path(e),t.Mouse.checkPath(this,e),""!=e.fillStyle&&(this.attribute("fill-rule").hasValue()?e.fill(this.attribute("fill-rule").value):e.fill()),""!=e.strokeStyle&&e.stroke();var i=this.getMarkers();if(null!=i){if(this.style("marker-start").isUrlDefinition()){var n=this.style("marker-start").getDefinition();n.render(e,i[0][0],i[0][1])}if(this.style("marker-mid").isUrlDefinition())for(var n=this.style("marker-mid").getDefinition(),r=1;i.length-1>r;r++)n.render(e,i[r][0],i[r][1]);if(this.style("marker-end").isUrlDefinition()){var n=this.style("marker-end").getDefinition();n.render(e,i[i.length-1][0],i[i.length-1][1])}}},this.getBoundingBox=function(){return this.path()},this.getMarkers=function(){return null}},t.Element.PathElementBase.prototype=new t.Element.RenderedElementBase,t.Element.svg=function(e){this.base=t.Element.RenderedElementBase,this.base(e),this.baseClearContext=this.clearContext,this.clearContext=function(e){this.baseClearContext(e),t.ViewPort.RemoveCurrent()},this.baseSetContext=this.setContext,this.setContext=function(e){e.strokeStyle="rgba(0,0,0,0)",e.lineCap="butt",e.lineJoin="miter",e.miterLimit=4,this.baseSetContext(e),this.attribute("x").hasValue()||(this.attribute("x",!0).value=0),this.attribute("y").hasValue()||(this.attribute("y",!0).value=0),e.translate(this.attribute("x").toPixels("x"),this.attribute("y").toPixels("y"));var i=t.ViewPort.width(),n=t.ViewPort.height();if(this.attribute("width").hasValue()||(this.attribute("width",!0).value="100%"),this.attribute("height").hasValue()||(this.attribute("height",!0).value="100%"),this.root===void 0){i=this.attribute("width").toPixels("x"),n=this.attribute("height").toPixels("y");var r=0,a=0;this.attribute("refX").hasValue()&&this.attribute("refY").hasValue()&&(r=-this.attribute("refX").toPixels("x"),a=-this.attribute("refY").toPixels("y")),e.beginPath(),e.moveTo(r,a),e.lineTo(i,a),e.lineTo(i,n),e.lineTo(r,n),e.closePath(),e.clip()}if(t.ViewPort.SetCurrent(i,n),this.attribute("viewBox").hasValue()){var s=t.ToNumberArray(this.attribute("viewBox").value),o=s[0],l=s[1];i=s[2],n=s[3],t.AspectRatio(e,this.attribute("preserveAspectRatio").value,t.ViewPort.width(),i,t.ViewPort.height(),n,o,l,this.attribute("refX").value,this.attribute("refY").value),t.ViewPort.RemoveCurrent(),t.ViewPort.SetCurrent(s[2],s[3])}}},t.Element.svg.prototype=new t.Element.RenderedElementBase,t.Element.rect=function(e){this.base=t.Element.PathElementBase,this.base(e),this.path=function(e){var i=this.attribute("x").toPixels("x"),n=this.attribute("y").toPixels("y"),r=this.attribute("width").toPixels("x"),a=this.attribute("height").toPixels("y"),s=this.attribute("rx").toPixels("x"),o=this.attribute("ry").toPixels("y");return this.attribute("rx").hasValue()&&!this.attribute("ry").hasValue()&&(o=s),this.attribute("ry").hasValue()&&!this.attribute("rx").hasValue()&&(s=o),s=Math.min(s,r/2),o=Math.min(o,a/2),null!=e&&(e.beginPath(),e.moveTo(i+s,n),e.lineTo(i+r-s,n),e.quadraticCurveTo(i+r,n,i+r,n+o),e.lineTo(i+r,n+a-o),e.quadraticCurveTo(i+r,n+a,i+r-s,n+a),e.lineTo(i+s,n+a),e.quadraticCurveTo(i,n+a,i,n+a-o),e.lineTo(i,n+o),e.quadraticCurveTo(i,n,i+s,n),e.closePath()),new t.BoundingBox(i,n,i+r,n+a)}},t.Element.rect.prototype=new t.Element.PathElementBase,t.Element.circle=function(e){this.base=t.Element.PathElementBase,this.base(e),this.path=function(e){var i=this.attribute("cx").toPixels("x"),n=this.attribute("cy").toPixels("y"),r=this.attribute("r").toPixels();return null!=e&&(e.beginPath(),e.arc(i,n,r,0,2*Math.PI,!0),e.closePath()),new t.BoundingBox(i-r,n-r,i+r,n+r)}},t.Element.circle.prototype=new t.Element.PathElementBase,t.Element.ellipse=function(e){this.base=t.Element.PathElementBase,this.base(e),this.path=function(e){var i=4*((Math.sqrt(2)-1)/3),n=this.attribute("rx").toPixels("x"),r=this.attribute("ry").toPixels("y"),a=this.attribute("cx").toPixels("x"),s=this.attribute("cy").toPixels("y");return null!=e&&(e.beginPath(),e.moveTo(a,s-r),e.bezierCurveTo(a+i*n,s-r,a+n,s-i*r,a+n,s),e.bezierCurveTo(a+n,s+i*r,a+i*n,s+r,a,s+r),e.bezierCurveTo(a-i*n,s+r,a-n,s+i*r,a-n,s),e.bezierCurveTo(a-n,s-i*r,a-i*n,s-r,a,s-r),e.closePath()),new t.BoundingBox(a-n,s-r,a+n,s+r)}},t.Element.ellipse.prototype=new t.Element.PathElementBase,t.Element.line=function(e){this.base=t.Element.PathElementBase,this.base(e),this.getPoints=function(){return[new t.Point(this.attribute("x1").toPixels("x"),this.attribute("y1").toPixels("y")),new t.Point(this.attribute("x2").toPixels("x"),this.attribute("y2").toPixels("y"))]},this.path=function(e){var i=this.getPoints();return null!=e&&(e.beginPath(),e.moveTo(i[0].x,i[0].y),e.lineTo(i[1].x,i[1].y)),new t.BoundingBox(i[0].x,i[0].y,i[1].x,i[1].y)},this.getMarkers=function(){var t=this.getPoints(),e=t[0].angleTo(t[1]);return[[t[0],e],[t[1],e]]}},t.Element.line.prototype=new t.Element.PathElementBase,t.Element.polyline=function(e){this.base=t.Element.PathElementBase,this.base(e),this.points=t.CreatePath(this.attribute("points").value),this.path=function(e){var i=new t.BoundingBox(this.points[0].x,this.points[0].y);null!=e&&(e.beginPath(),e.moveTo(this.points[0].x,this.points[0].y));for(var n=1;this.points.length>n;n++)i.addPoint(this.points[n].x,this.points[n].y),null!=e&&e.lineTo(this.points[n].x,this.points[n].y);return i},this.getMarkers=function(){for(var t=[],e=0;this.points.length-1>e;e++)t.push([this.points[e],this.points[e].angleTo(this.points[e+1])]);return t.push([this.points[this.points.length-1],t[t.length-1][1]]),t}},t.Element.polyline.prototype=new t.Element.PathElementBase,t.Element.polygon=function(e){this.base=t.Element.polyline,this.base(e),this.basePath=this.path,this.path=function(t){var e=this.basePath(t);return null!=t&&(t.lineTo(this.points[0].x,this.points[0].y),t.closePath()),e}},t.Element.polygon.prototype=new t.Element.polyline,t.Element.path=function(e){this.base=t.Element.PathElementBase,this.base(e);var i=this.attribute("d").value;i=i.replace(/,/gm," "),i=i.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,"$1 $2"),i=i.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,"$1 $2"),i=i.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,"$1 $2"),i=i.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,"$1 $2"),i=i.replace(/([0-9])([+\-])/gm,"$1 $2"),i=i.replace(/(\.[0-9]*)(\.)/gm,"$1 $2"),i=i.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,"$1 $3 $4 "),i=t.compressSpaces(i),i=t.trim(i),this.PathParser=new function(e){this.tokens=e.split(" "),this.reset=function(){this.i=-1,this.command="",this.previousCommand="",this.start=new t.Point(0,0),this.control=new t.Point(0,0),this.current=new t.Point(0,0),this.points=[],this.angles=[]},this.isEnd=function(){return this.i>=this.tokens.length-1},this.isCommandOrEnd=function(){return this.isEnd()?!0:null!=this.tokens[this.i+1].match(/^[A-Za-z]$/)},this.isRelativeCommand=function(){switch(this.command){case"m":case"l":case"h":case"v":case"c":case"s":case"q":case"t":case"a":case"z":return!0}return!1},this.getToken=function(){return this.i++,this.tokens[this.i]},this.getScalar=function(){return parseFloat(this.getToken())},this.nextCommand=function(){this.previousCommand=this.command,this.command=this.getToken()},this.getPoint=function(){var e=new t.Point(this.getScalar(),this.getScalar());return this.makeAbsolute(e)},this.getAsControlPoint=function(){var t=this.getPoint();return this.control=t,t},this.getAsCurrentPoint=function(){var t=this.getPoint();return this.current=t,t},this.getReflectedControlPoint=function(){if("c"!=this.previousCommand.toLowerCase()&&"s"!=this.previousCommand.toLowerCase()&&"q"!=this.previousCommand.toLowerCase()&&"t"!=this.previousCommand.toLowerCase())return this.current;var e=new t.Point(2*this.current.x-this.control.x,2*this.current.y-this.control.y);return e},this.makeAbsolute=function(t){return this.isRelativeCommand()&&(t.x+=this.current.x,t.y+=this.current.y),t},this.addMarker=function(t,e,i){null!=i&&this.angles.length>0&&null==this.angles[this.angles.length-1]&&(this.angles[this.angles.length-1]=this.points[this.points.length-1].angleTo(i)),this.addMarkerAngle(t,null==e?null:e.angleTo(t))},this.addMarkerAngle=function(t,e){this.points.push(t),this.angles.push(e)},this.getMarkerPoints=function(){return this.points},this.getMarkerAngles=function(){for(var t=0;this.angles.length>t;t++)if(null==this.angles[t])for(var e=t+1;this.angles.length>e;e++)if(null!=this.angles[e]){this.angles[t]=this.angles[e];break}return this.angles}}(i),this.path=function(e){var i=this.PathParser;i.reset();var n=new t.BoundingBox;for(null!=e&&e.beginPath();!i.isEnd();)switch(i.nextCommand(),i.command){case"M":case"m":var r=i.getAsCurrentPoint();for(i.addMarker(r),n.addPoint(r.x,r.y),null!=e&&e.moveTo(r.x,r.y),i.start=i.current;!i.isCommandOrEnd();){var r=i.getAsCurrentPoint();i.addMarker(r,i.start),n.addPoint(r.x,r.y),null!=e&&e.lineTo(r.x,r.y)}break;case"L":case"l":for(;!i.isCommandOrEnd();){var a=i.current,r=i.getAsCurrentPoint();i.addMarker(r,a),n.addPoint(r.x,r.y),null!=e&&e.lineTo(r.x,r.y)}break;case"H":case"h":for(;!i.isCommandOrEnd();){var s=new t.Point((i.isRelativeCommand()?i.current.x:0)+i.getScalar(),i.current.y);i.addMarker(s,i.current),i.current=s,n.addPoint(i.current.x,i.current.y),null!=e&&e.lineTo(i.current.x,i.current.y)}break;case"V":case"v":for(;!i.isCommandOrEnd();){var s=new t.Point(i.current.x,(i.isRelativeCommand()?i.current.y:0)+i.getScalar());i.addMarker(s,i.current),i.current=s,n.addPoint(i.current.x,i.current.y),null!=e&&e.lineTo(i.current.x,i.current.y)}break;case"C":case"c":for(;!i.isCommandOrEnd();){var o=i.current,l=i.getPoint(),c=i.getAsControlPoint(),h=i.getAsCurrentPoint();i.addMarker(h,c,l),n.addBezierCurve(o.x,o.y,l.x,l.y,c.x,c.y,h.x,h.y),null!=e&&e.bezierCurveTo(l.x,l.y,c.x,c.y,h.x,h.y)}break;case"S":case"s":for(;!i.isCommandOrEnd();){var o=i.current,l=i.getReflectedControlPoint(),c=i.getAsControlPoint(),h=i.getAsCurrentPoint();i.addMarker(h,c,l),n.addBezierCurve(o.x,o.y,l.x,l.y,c.x,c.y,h.x,h.y),null!=e&&e.bezierCurveTo(l.x,l.y,c.x,c.y,h.x,h.y)}break;case"Q":case"q":for(;!i.isCommandOrEnd();){var o=i.current,c=i.getAsControlPoint(),h=i.getAsCurrentPoint();i.addMarker(h,c,c),n.addQuadraticCurve(o.x,o.y,c.x,c.y,h.x,h.y),null!=e&&e.quadraticCurveTo(c.x,c.y,h.x,h.y)}break;case"T":case"t":for(;!i.isCommandOrEnd();){var o=i.current,c=i.getReflectedControlPoint();i.control=c;var h=i.getAsCurrentPoint();i.addMarker(h,c,c),n.addQuadraticCurve(o.x,o.y,c.x,c.y,h.x,h.y),null!=e&&e.quadraticCurveTo(c.x,c.y,h.x,h.y)}break;case"A":case"a":for(;!i.isCommandOrEnd();){var o=i.current,u=i.getScalar(),p=i.getScalar(),g=i.getScalar()*(Math.PI/180),d=i.getScalar(),f=i.getScalar(),h=i.getAsCurrentPoint(),m=new t.Point(Math.cos(g)*(o.x-h.x)/2+Math.sin(g)*(o.y-h.y)/2,-Math.sin(g)*(o.x-h.x)/2+Math.cos(g)*(o.y-h.y)/2),I=Math.pow(m.x,2)/Math.pow(u,2)+Math.pow(m.y,2)/Math.pow(p,2);I>1&&(u*=Math.sqrt(I),p*=Math.sqrt(I));var y=(d==f?-1:1)*Math.sqrt((Math.pow(u,2)*Math.pow(p,2)-Math.pow(u,2)*Math.pow(m.y,2)-Math.pow(p,2)*Math.pow(m.x,2))/(Math.pow(u,2)*Math.pow(m.y,2)+Math.pow(p,2)*Math.pow(m.x,2)));isNaN(y)&&(y=0);var v=new t.Point(y*u*m.y/p,y*-p*m.x/u),C=new t.Point((o.x+h.x)/2+Math.cos(g)*v.x-Math.sin(g)*v.y,(o.y+h.y)/2+Math.sin(g)*v.x+Math.cos(g)*v.y),b=function(t){return Math.sqrt(Math.pow(t[0],2)+Math.pow(t[1],2))},A=function(t,e){return(t[0]*e[0]+t[1]*e[1])/(b(t)*b(e))},w=function(t,e){return(t[0]*e[1]<t[1]*e[0]?-1:1)*Math.acos(A(t,e))},x=w([1,0],[(m.x-v.x)/u,(m.y-v.y)/p]),M=[(m.x-v.x)/u,(m.y-v.y)/p],j=[(-m.x-v.x)/u,(-m.y-v.y)/p],N=w(M,j);-1>=A(M,j)&&(N=Math.PI),A(M,j)>=1&&(N=0);var k=1-f?1:-1,D=x+k*(N/2),z=new t.Point(C.x+u*Math.cos(D),C.y+p*Math.sin(D));if(i.addMarkerAngle(z,D-k*Math.PI/2),i.addMarkerAngle(h,D-k*Math.PI),n.addPoint(h.x,h.y),null!=e){var A=u>p?u:p,S=u>p?1:u/p,T=u>p?p/u:1;e.translate(C.x,C.y),e.rotate(g),e.scale(S,T),e.arc(0,0,A,x,x+N,1-f),e.scale(1/S,1/T),e.rotate(-g),e.translate(-C.x,-C.y)}}break;case"Z":case"z":null!=e&&e.closePath(),i.current=i.start}return n},this.getMarkers=function(){for(var t=this.PathParser.getMarkerPoints(),e=this.PathParser.getMarkerAngles(),i=[],n=0;t.length>n;n++)i.push([t[n],e[n]]);return i}},t.Element.path.prototype=new t.Element.PathElementBase,t.Element.pattern=function(e){this.base=t.Element.ElementBase,this.base(e),this.createPattern=function(e){var i=this.attribute("width").toPixels("x",!0),n=this.attribute("height").toPixels("y",!0),r=new t.Element.svg;r.attributes.viewBox=new t.Property("viewBox",this.attribute("viewBox").value),r.attributes.width=new t.Property("width",i+"px"),r.attributes.height=new t.Property("height",n+"px"),r.attributes.transform=new t.Property("transform",this.attribute("patternTransform").value),r.children=this.children;var a=document.createElement("canvas");a.width=i,a.height=n;var s=a.getContext("2d");this.attribute("x").hasValue()&&this.attribute("y").hasValue()&&s.translate(this.attribute("x").toPixels("x",!0),this.attribute("y").toPixels("y",!0));for(var o=-1;1>=o;o++)for(var l=-1;1>=l;l++)s.save(),s.translate(o*a.width,l*a.height),r.render(s),s.restore();var c=e.createPattern(a,"repeat");return c}},t.Element.pattern.prototype=new t.Element.ElementBase,t.Element.marker=function(e){this.base=t.Element.ElementBase,this.base(e),this.baseRender=this.render,this.render=function(e,i,n){e.translate(i.x,i.y),"auto"==this.attribute("orient").valueOrDefault("auto")&&e.rotate(n),"strokeWidth"==this.attribute("markerUnits").valueOrDefault("strokeWidth")&&e.scale(e.lineWidth,e.lineWidth),e.save();var r=new t.Element.svg;r.attributes.viewBox=new t.Property("viewBox",this.attribute("viewBox").value),r.attributes.refX=new t.Property("refX",this.attribute("refX").value),r.attributes.refY=new t.Property("refY",this.attribute("refY").value),r.attributes.width=new t.Property("width",this.attribute("markerWidth").value),r.attributes.height=new t.Property("height",this.attribute("markerHeight").value),r.attributes.fill=new t.Property("fill",this.attribute("fill").valueOrDefault("black")),r.attributes.stroke=new t.Property("stroke",this.attribute("stroke").valueOrDefault("none")),r.children=this.children,r.render(e),e.restore(),"strokeWidth"==this.attribute("markerUnits").valueOrDefault("strokeWidth")&&e.scale(1/e.lineWidth,1/e.lineWidth),"auto"==this.attribute("orient").valueOrDefault("auto")&&e.rotate(-n),e.translate(-i.x,-i.y)}},t.Element.marker.prototype=new t.Element.ElementBase,t.Element.defs=function(e){this.base=t.Element.ElementBase,this.base(e),this.render=function(){}},t.Element.defs.prototype=new t.Element.ElementBase,t.Element.GradientBase=function(e){this.base=t.Element.ElementBase,this.base(e),this.gradientUnits=this.attribute("gradientUnits").valueOrDefault("objectBoundingBox"),this.stops=[];for(var i=0;this.children.length>i;i++){var n=this.children[i];"stop"==n.type&&this.stops.push(n)}this.getGradient=function(){},this.createGradient=function(e,i,n){var r=this;this.getHrefAttribute().hasValue()&&(r=this.getHrefAttribute().getDefinition());var a=function(e){if(n.hasValue()){var i=new t.Property("color",e);return i.addOpacity(n.value).value}return e},s=this.getGradient(e,i);if(null==s)return a(r.stops[r.stops.length-1].color);for(var o=0;r.stops.length>o;o++)s.addColorStop(r.stops[o].offset,a(r.stops[o].color));if(this.attribute("gradientTransform").hasValue()){var l=t.ViewPort.viewPorts[0],c=new t.Element.rect;c.attributes.x=new t.Property("x",-t.MAX_VIRTUAL_PIXELS/3),c.attributes.y=new t.Property("y",-t.MAX_VIRTUAL_PIXELS/3),c.attributes.width=new t.Property("width",t.MAX_VIRTUAL_PIXELS),c.attributes.height=new t.Property("height",t.MAX_VIRTUAL_PIXELS);var h=new t.Element.g;h.attributes.transform=new t.Property("transform",this.attribute("gradientTransform").value),h.children=[c];var u=new t.Element.svg;u.attributes.x=new t.Property("x",0),u.attributes.y=new t.Property("y",0),u.attributes.width=new t.Property("width",l.width),u.attributes.height=new t.Property("height",l.height),u.children=[h];var p=document.createElement("canvas");p.width=l.width,p.height=l.height;var g=p.getContext("2d");return g.fillStyle=s,u.render(g),g.createPattern(p,"no-repeat")}return s}},t.Element.GradientBase.prototype=new t.Element.ElementBase,t.Element.linearGradient=function(e){this.base=t.Element.GradientBase,this.base(e),this.getGradient=function(t,e){var i=e.getBoundingBox();this.attribute("x1").hasValue()||this.attribute("y1").hasValue()||this.attribute("x2").hasValue()||this.attribute("y2").hasValue()||(this.attribute("x1",!0).value=0,this.attribute("y1",!0).value=0,this.attribute("x2",!0).value=1,this.attribute("y2",!0).value=0);var n="objectBoundingBox"==this.gradientUnits?i.x()+i.width()*this.attribute("x1").numValue():this.attribute("x1").toPixels("x"),r="objectBoundingBox"==this.gradientUnits?i.y()+i.height()*this.attribute("y1").numValue():this.attribute("y1").toPixels("y"),a="objectBoundingBox"==this.gradientUnits?i.x()+i.width()*this.attribute("x2").numValue():this.attribute("x2").toPixels("x"),s="objectBoundingBox"==this.gradientUnits?i.y()+i.height()*this.attribute("y2").numValue():this.attribute("y2").toPixels("y");return n==a&&r==s?null:t.createLinearGradient(n,r,a,s)}},t.Element.linearGradient.prototype=new t.Element.GradientBase,t.Element.radialGradient=function(e){this.base=t.Element.GradientBase,this.base(e),this.getGradient=function(t,e){var i=e.getBoundingBox();this.attribute("cx").hasValue()||(this.attribute("cx",!0).value="50%"),this.attribute("cy").hasValue()||(this.attribute("cy",!0).value="50%"),this.attribute("r").hasValue()||(this.attribute("r",!0).value="50%");var n="objectBoundingBox"==this.gradientUnits?i.x()+i.width()*this.attribute("cx").numValue():this.attribute("cx").toPixels("x"),r="objectBoundingBox"==this.gradientUnits?i.y()+i.height()*this.attribute("cy").numValue():this.attribute("cy").toPixels("y"),a=n,s=r;this.attribute("fx").hasValue()&&(a="objectBoundingBox"==this.gradientUnits?i.x()+i.width()*this.attribute("fx").numValue():this.attribute("fx").toPixels("x")),this.attribute("fy").hasValue()&&(s="objectBoundingBox"==this.gradientUnits?i.y()+i.height()*this.attribute("fy").numValue():this.attribute("fy").toPixels("y"));var o="objectBoundingBox"==this.gradientUnits?(i.width()+i.height())/2*this.attribute("r").numValue():this.attribute("r").toPixels();return t.createRadialGradient(a,s,0,n,r,o)}},t.Element.radialGradient.prototype=new t.Element.GradientBase,t.Element.stop=function(e){this.base=t.Element.ElementBase,this.base(e),this.offset=this.attribute("offset").numValue(),0>this.offset&&(this.offset=0),this.offset>1&&(this.offset=1);var i=this.style("stop-color");this.style("stop-opacity").hasValue()&&(i=i.addOpacity(this.style("stop-opacity").value)),this.color=i.value},t.Element.stop.prototype=new t.Element.ElementBase,t.Element.AnimateBase=function(e){this.base=t.Element.ElementBase,this.base(e),t.Animations.push(this),this.duration=0,this.begin=this.attribute("begin").toMilliseconds(),this.maxDuration=this.begin+this.attribute("dur").toMilliseconds(),this.getProperty=function(){var t=this.attribute("attributeType").value,e=this.attribute("attributeName").value;return"CSS"==t?this.parent.style(e,!0):this.parent.attribute(e,!0)},this.initialValue=null,this.initialUnits="",this.removed=!1,this.calcValue=function(){return""},this.update=function(t){if(null==this.initialValue&&(this.initialValue=this.getProperty().value,this.initialUnits=this.getProperty().getUnits()),this.duration>this.maxDuration){if("indefinite"!=this.attribute("repeatCount").value&&"indefinite"!=this.attribute("repeatDur").value)return"remove"!=this.attribute("fill").valueOrDefault("remove")||this.removed?!1:(this.removed=!0,this.getProperty().value=this.initialValue,!0);this.duration=0}this.duration=this.duration+t;var e=!1;if(this.begin<this.duration){var i=this.calcValue();if(this.attribute("type").hasValue()){var n=this.attribute("type").value;i=n+"("+i+")"}this.getProperty().value=i,e=!0}return e},this.from=this.attribute("from"),this.to=this.attribute("to"),this.values=this.attribute("values"),this.values.hasValue()&&(this.values.value=this.values.value.split(";")),this.progress=function(){var e={progress:(this.duration-this.begin)/(this.maxDuration-this.begin)};if(this.values.hasValue()){var i=e.progress*(this.values.value.length-1),n=Math.floor(i),r=Math.ceil(i);e.from=new t.Property("from",parseFloat(this.values.value[n])),e.to=new t.Property("to",parseFloat(this.values.value[r])),e.progress=(i-n)/(r-n)}else e.from=this.from,e.to=this.to;return e}},t.Element.AnimateBase.prototype=new t.Element.ElementBase,t.Element.animate=function(e){this.base=t.Element.AnimateBase,this.base(e),this.calcValue=function(){var t=this.progress(),e=t.from.numValue()+(t.to.numValue()-t.from.numValue())*t.progress;return e+this.initialUnits}},t.Element.animate.prototype=new t.Element.AnimateBase,t.Element.animateColor=function(e){this.base=t.Element.AnimateBase,this.base(e),this.calcValue=function(){var t=this.progress(),e=new RGBColor(t.from.value),i=new RGBColor(t.to.value);if(e.ok&&i.ok){var n=e.r+(i.r-e.r)*t.progress,r=e.g+(i.g-e.g)*t.progress,a=e.b+(i.b-e.b)*t.progress;return"rgb("+parseInt(n,10)+","+parseInt(r,10)+","+parseInt(a,10)+")"}return this.attribute("from").value}},t.Element.animateColor.prototype=new t.Element.AnimateBase,t.Element.animateTransform=function(e){this.base=t.Element.AnimateBase,this.base(e),this.calcValue=function(){for(var e=this.progress(),i=t.ToNumberArray(e.from.value),n=t.ToNumberArray(e.to.value),r="",a=0;i.length>a;a++)r+=i[a]+(n[a]-i[a])*e.progress+" ";return r}},t.Element.animateTransform.prototype=new t.Element.animate,t.Element.font=function(e){this.base=t.Element.ElementBase,this.base(e),this.horizAdvX=this.attribute("horiz-adv-x").numValue(),this.isRTL=!1,this.isArabic=!1,this.fontFace=null,this.missingGlyph=null,this.glyphs=[];for(var i=0;this.children.length>i;i++){var n=this.children[i];"font-face"==n.type?(this.fontFace=n,n.style("font-family").hasValue()&&(t.Definitions[n.style("font-family").value]=this)):"missing-glyph"==n.type?this.missingGlyph=n:"glyph"==n.type&&(""!=n.arabicForm?(this.isRTL=!0,this.isArabic=!0,this.glyphs[n.unicode]===void 0&&(this.glyphs[n.unicode]=[]),this.glyphs[n.unicode][n.arabicForm]=n):this.glyphs[n.unicode]=n)}},t.Element.font.prototype=new t.Element.ElementBase,t.Element.fontface=function(e){this.base=t.Element.ElementBase,this.base(e),this.ascent=this.attribute("ascent").value,this.descent=this.attribute("descent").value,this.unitsPerEm=this.attribute("units-per-em").numValue()},t.Element.fontface.prototype=new t.Element.ElementBase,t.Element.missingglyph=function(e){this.base=t.Element.path,this.base(e),this.horizAdvX=0},t.Element.missingglyph.prototype=new t.Element.path,t.Element.glyph=function(e){this.base=t.Element.path,this.base(e),this.horizAdvX=this.attribute("horiz-adv-x").numValue(),this.unicode=this.attribute("unicode").value,this.arabicForm=this.attribute("arabic-form").value},t.Element.glyph.prototype=new t.Element.path,t.Element.text=function(e){this.captureTextNodes=!0,this.base=t.Element.RenderedElementBase,this.base(e),this.baseSetContext=this.setContext,this.setContext=function(t){this.baseSetContext(t),this.style("dominant-baseline").hasValue()&&(t.textBaseline=this.style("dominant-baseline").value),this.style("alignment-baseline").hasValue()&&(t.textBaseline=this.style("alignment-baseline").value)},this.getBoundingBox=function(){return new t.BoundingBox(this.attribute("x").toPixels("x"),this.attribute("y").toPixels("y"),0,0)},this.renderChildren=function(t){this.x=this.attribute("x").toPixels("x"),this.y=this.attribute("y").toPixels("y"),this.x+=this.getAnchorDelta(t,this,0);for(var e=0;this.children.length>e;e++)this.renderChild(t,this,e)},this.getAnchorDelta=function(t,e,i){var n=this.style("text-anchor").valueOrDefault("start");if("start"!=n){for(var r=0,a=i;e.children.length>a;a++){var s=e.children[a];if(a>i&&s.attribute("x").hasValue())break;r+=s.measureTextRecursive(t)}return-1*("end"==n?r:r/2)}return 0},this.renderChild=function(t,e,i){var n=e.children[i];n.attribute("x").hasValue()?n.x=n.attribute("x").toPixels("x")+this.getAnchorDelta(t,e,i):(this.attribute("dx").hasValue()&&(this.x+=this.attribute("dx").toPixels("x")),n.attribute("dx").hasValue()&&(this.x+=n.attribute("dx").toPixels("x")),n.x=this.x),this.x=n.x+n.measureText(t),n.attribute("y").hasValue()?n.y=n.attribute("y").toPixels("y"):(this.attribute("dy").hasValue()&&(this.y+=this.attribute("dy").toPixels("y")),n.attribute("dy").hasValue()&&(this.y+=n.attribute("dy").toPixels("y")),n.y=this.y),this.y=n.y,n.render(t);for(var i=0;n.children.length>i;i++)this.renderChild(t,n,i)}},t.Element.text.prototype=new t.Element.RenderedElementBase,t.Element.TextElementBase=function(e){this.base=t.Element.RenderedElementBase,this.base(e),this.getGlyph=function(t,e,i){var n=e[i],r=null;if(t.isArabic){var a="isolated";(0==i||" "==e[i-1])&&e.length-2>i&&" "!=e[i+1]&&(a="terminal"),i>0&&" "!=e[i-1]&&e.length-2>i&&" "!=e[i+1]&&(a="medial"),i>0&&" "!=e[i-1]&&(i==e.length-1||" "==e[i+1])&&(a="initial"),t.glyphs[n]!==void 0&&(r=t.glyphs[n][a],null==r&&"glyph"==t.glyphs[n].type&&(r=t.glyphs[n]))}else r=t.glyphs[n];return null==r&&(r=t.missingGlyph),r},this.renderChildren=function(e){var i=this.parent.style("font-family").getDefinition();if(null==i)""!=e.fillStyle&&e.fillText(t.compressSpaces(this.getText()),this.x,this.y),""!=e.strokeStyle&&e.strokeText(t.compressSpaces(this.getText()),this.x,this.y);else{var n=this.parent.style("font-size").numValueOrDefault(t.Font.Parse(t.ctx.font).fontSize),r=this.parent.style("font-style").valueOrDefault(t.Font.Parse(t.ctx.font).fontStyle),a=this.getText();i.isRTL&&(a=a.split("").reverse().join(""));for(var s=t.ToNumberArray(this.parent.attribute("dx").value),o=0;a.length>o;o++){var l=this.getGlyph(i,a,o),c=n/i.fontFace.unitsPerEm;e.translate(this.x,this.y),e.scale(c,-c);var h=e.lineWidth;e.lineWidth=e.lineWidth*i.fontFace.unitsPerEm/n,"italic"==r&&e.transform(1,0,.4,1,0,0),l.render(e),"italic"==r&&e.transform(1,0,-.4,1,0,0),e.lineWidth=h,e.scale(1/c,-1/c),e.translate(-this.x,-this.y),this.x+=n*(l.horizAdvX||i.horizAdvX)/i.fontFace.unitsPerEm,void 0===s[o]||isNaN(s[o])||(this.x+=s[o])}}},this.getText=function(){},this.measureTextRecursive=function(t){for(var e=this.measureText(t),i=0;this.children.length>i;i++)e+=this.children[i].measureTextRecursive(t);return e},this.measureText=function(e){var i=this.parent.style("font-family").getDefinition();if(null!=i){var n=this.parent.style("font-size").numValueOrDefault(t.Font.Parse(t.ctx.font).fontSize),r=0,a=this.getText();i.isRTL&&(a=a.split("").reverse().join(""));for(var s=t.ToNumberArray(this.parent.attribute("dx").value),o=0;a.length>o;o++){var l=this.getGlyph(i,a,o);r+=(l.horizAdvX||i.horizAdvX)*n/i.fontFace.unitsPerEm,void 0===s[o]||isNaN(s[o])||(r+=s[o])}return r}var c=t.compressSpaces(this.getText());if(!e.measureText)return 10*c.length;e.save(),this.setContext(e);var h=e.measureText(c).width;return e.restore(),h}},t.Element.TextElementBase.prototype=new t.Element.RenderedElementBase,t.Element.tspan=function(e){this.captureTextNodes=!0,this.base=t.Element.TextElementBase,this.base(e),this.text=e.nodeValue||e.text||"",this.getText=function(){return this.text}},t.Element.tspan.prototype=new t.Element.TextElementBase,t.Element.tref=function(e){this.base=t.Element.TextElementBase,this.base(e),this.getText=function(){var t=this.getHrefAttribute().getDefinition();return null!=t?t.children[0].getText():void 0}},t.Element.tref.prototype=new t.Element.TextElementBase,t.Element.a=function(e){this.base=t.Element.TextElementBase,this.base(e),this.hasText=!0;for(var i=0;e.childNodes.length>i;i++)3!=e.childNodes[i].nodeType&&(this.hasText=!1);this.text=this.hasText?e.childNodes[0].nodeValue:"",this.getText=function(){return this.text},this.baseRenderChildren=this.renderChildren,this.renderChildren=function(e){if(this.hasText){this.baseRenderChildren(e);var i=new t.Property("fontSize",t.Font.Parse(t.ctx.font).fontSize);t.Mouse.checkBoundingBox(this,new t.BoundingBox(this.x,this.y-i.toPixels("y"),this.x+this.measureText(e),this.y))}else{var n=new t.Element.g;n.children=this.children,n.parent=this,n.render(e)}},this.onclick=function(){window.open(this.getHrefAttribute().value)},this.onmousemove=function(){t.ctx.canvas.style.cursor="pointer"}},t.Element.a.prototype=new t.Element.TextElementBase,t.Element.image=function(e){this.base=t.Element.RenderedElementBase,this.base(e);var i=this.getHrefAttribute().value,n=i.match(/\.svg$/);if(t.Images.push(this),this.loaded=!1,n)this.img=t.ajax(i),this.loaded=!0;else{this.img=document.createElement("img");var r=this;this.img.onload=function(){r.loaded=!0},this.img.onerror=function(){"undefined"!=typeof console&&(console.log('ERROR: image "'+i+'" not found'),r.loaded=!0)},this.img.src=i}this.renderChildren=function(e){var i=this.attribute("x").toPixels("x"),r=this.attribute("y").toPixels("y"),a=this.attribute("width").toPixels("x"),s=this.attribute("height").toPixels("y");0!=a&&0!=s&&(e.save(),n?e.drawSvg(this.img,i,r,a,s):(e.translate(i,r),t.AspectRatio(e,this.attribute("preserveAspectRatio").value,a,this.img.width,s,this.img.height,0,0),e.drawImage(this.img,0,0)),e.restore())},this.getBoundingBox=function(){var e=this.attribute("x").toPixels("x"),i=this.attribute("y").toPixels("y"),n=this.attribute("width").toPixels("x"),r=this.attribute("height").toPixels("y");return new t.BoundingBox(e,i,e+n,i+r)}},t.Element.image.prototype=new t.Element.RenderedElementBase,t.Element.g=function(e){this.base=t.Element.RenderedElementBase,this.base(e),this.getBoundingBox=function(){for(var e=new t.BoundingBox,i=0;this.children.length>i;i++)e.addBoundingBox(this.children[i].getBoundingBox());return e}},t.Element.g.prototype=new t.Element.RenderedElementBase,t.Element.symbol=function(e){this.base=t.Element.RenderedElementBase,this.base(e),this.baseSetContext=this.setContext,this.setContext=function(e){if(this.baseSetContext(e),this.attribute("viewBox").hasValue()){var i=t.ToNumberArray(this.attribute("viewBox").value),n=i[0],r=i[1];
+width=i[2],height=i[3],t.AspectRatio(e,this.attribute("preserveAspectRatio").value,this.attribute("width").toPixels("x"),width,this.attribute("height").toPixels("y"),height,n,r),t.ViewPort.SetCurrent(i[2],i[3])}}},t.Element.symbol.prototype=new t.Element.RenderedElementBase,t.Element.style=function(e){this.base=t.Element.ElementBase,this.base(e);for(var i="",n=0;e.childNodes.length>n;n++)i+=e.childNodes[n].nodeValue;i=i.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm,""),i=t.compressSpaces(i);for(var r=i.split("}"),n=0;r.length>n;n++)if(""!=t.trim(r[n]))for(var a=r[n].split("{"),s=a[0].split(","),o=a[1].split(";"),l=0;s.length>l;l++){var c=t.trim(s[l]);if(""!=c){for(var h={},u=0;o.length>u;u++){var p=o[u].indexOf(":"),g=o[u].substr(0,p),d=o[u].substr(p+1,o[u].length-p);null!=g&&null!=d&&(h[t.trim(g)]=new t.Property(t.trim(g),t.trim(d)))}if(t.Styles[c]=h,"@font-face"==c)for(var f=h["font-family"].value.replace(/"/g,""),m=h.src.value.split(","),I=0;m.length>I;I++)if(m[I].indexOf('format("svg")')>0)for(var y=m[I].indexOf("url"),v=m[I].indexOf(")",y),C=m[I].substr(y+5,v-y-6),b=t.parseXml(t.ajax(C)),A=b.getElementsByTagName("font"),w=0;A.length>w;w++){var x=t.CreateElement(A[w]);t.Definitions[f]=x}}}},t.Element.style.prototype=new t.Element.ElementBase,t.Element.use=function(e){this.base=t.Element.RenderedElementBase,this.base(e),this.baseSetContext=this.setContext,this.setContext=function(t){this.baseSetContext(t),this.attribute("x").hasValue()&&t.translate(this.attribute("x").toPixels("x"),0),this.attribute("y").hasValue()&&t.translate(0,this.attribute("y").toPixels("y"))},this.getDefinition=function(){var t=this.getHrefAttribute().getDefinition();return this.attribute("width").hasValue()&&(t.attribute("width",!0).value=this.attribute("width").value),this.attribute("height").hasValue()&&(t.attribute("height",!0).value=this.attribute("height").value),t},this.path=function(t){var e=this.getDefinition();null!=e&&e.path(t)},this.getBoundingBox=function(){var t=this.getDefinition();return null!=t?t.getBoundingBox():void 0},this.renderChildren=function(t){var e=this.getDefinition();if(null!=e){var i=e.parent;e.parent=null,e.render(t),e.parent=i}}},t.Element.use.prototype=new t.Element.RenderedElementBase,t.Element.mask=function(e){this.base=t.Element.ElementBase,this.base(e),this.apply=function(e,i){var n=this.attribute("x").toPixels("x"),r=this.attribute("y").toPixels("y"),a=this.attribute("width").toPixels("x"),s=this.attribute("height").toPixels("y");if(0==a&&0==s){for(var o=new t.BoundingBox,l=0;this.children.length>l;l++)o.addBoundingBox(this.children[l].getBoundingBox());var n=Math.floor(o.x1),r=Math.floor(o.y1),a=Math.floor(o.width()),s=Math.floor(o.height())}var c=i.attribute("mask").value;i.attribute("mask").value="";var h=document.createElement("canvas");h.width=n+a,h.height=r+s;var u=h.getContext("2d");this.renderChildren(u);var p=document.createElement("canvas");p.width=n+a,p.height=r+s;var g=p.getContext("2d");i.render(g),g.globalCompositeOperation="destination-in",g.fillStyle=u.createPattern(h,"no-repeat"),g.fillRect(0,0,n+a,r+s),e.fillStyle=g.createPattern(p,"no-repeat"),e.fillRect(0,0,n+a,r+s),i.attribute("mask").value=c},this.render=function(){}},t.Element.mask.prototype=new t.Element.ElementBase,t.Element.clipPath=function(e){this.base=t.Element.ElementBase,this.base(e),this.apply=function(e){for(var i=0;this.children.length>i;i++){var n=this.children[i];if(n.path!==void 0){var r=null;n.attribute("transform").hasValue()&&(r=new t.Transform(n.attribute("transform").value),r.apply(e)),n.path(e),e.clip(),r&&r.unapply(e)}}},this.render=function(){}},t.Element.clipPath.prototype=new t.Element.ElementBase,t.Element.filter=function(e){this.base=t.Element.ElementBase,this.base(e),this.apply=function(t,e){var i=e.getBoundingBox(),n=Math.floor(i.x1),r=Math.floor(i.y1),a=Math.floor(i.width()),s=Math.floor(i.height()),o=e.style("filter").value;e.style("filter").value="";for(var l=0,c=0,h=0;this.children.length>h;h++){var u=this.children[h].extraFilterDistance||0;l=Math.max(l,u),c=Math.max(c,u)}var p=document.createElement("canvas");p.width=a+2*l,p.height=s+2*c;var g=p.getContext("2d");g.translate(-n+l,-r+c),e.render(g);for(var h=0;this.children.length>h;h++)this.children[h].apply(g,0,0,a+2*l,s+2*c);t.drawImage(p,0,0,a+2*l,s+2*c,n-l,r-c,a+2*l,s+2*c),e.style("filter",!0).value=o},this.render=function(){}},t.Element.filter.prototype=new t.Element.ElementBase,t.Element.feMorphology=function(e){this.base=t.Element.ElementBase,this.base(e),this.apply=function(){}},t.Element.feMorphology.prototype=new t.Element.ElementBase,t.Element.feColorMatrix=function(e){function i(t,e,i,n,r,a){return t[4*i*n+4*e+a]}function n(t,e,i,n,r,a,s){t[4*i*n+4*e+a]=s}this.base=t.Element.ElementBase,this.base(e),this.apply=function(t,e,r,a,s){for(var o=t.getImageData(0,0,a,s),r=0;s>r;r++)for(var e=0;a>e;e++){var l=i(o.data,e,r,a,s,0),c=i(o.data,e,r,a,s,1),h=i(o.data,e,r,a,s,2),u=(l+c+h)/3;n(o.data,e,r,a,s,0,u),n(o.data,e,r,a,s,1,u),n(o.data,e,r,a,s,2,u)}t.clearRect(0,0,a,s),t.putImageData(o,0,0)}},t.Element.feColorMatrix.prototype=new t.Element.ElementBase,t.Element.feGaussianBlur=function(e){this.base=t.Element.ElementBase,this.base(e),this.blurRadius=Math.floor(this.attribute("stdDeviation").numValue()),this.extraFilterDistance=this.blurRadius,this.apply=function(e,i,n,r,a){return stackBlurCanvasRGBA===void 0?("undefined"!=typeof console&&console.log("ERROR: StackBlur.js must be included for blur to work"),void 0):(e.canvas.id=t.UniqueId(),e.canvas.style.display="none",document.body.appendChild(e.canvas),stackBlurCanvasRGBA(e.canvas.id,i,n,r,a,this.blurRadius),document.body.removeChild(e.canvas),void 0)}},t.Element.feGaussianBlur.prototype=new t.Element.ElementBase,t.Element.title=function(){},t.Element.title.prototype=new t.Element.ElementBase,t.Element.desc=function(){},t.Element.desc.prototype=new t.Element.ElementBase,t.Element.MISSING=function(t){"undefined"!=typeof console&&console.log("ERROR: Element '"+t.nodeName+"' not yet implemented.")},t.Element.MISSING.prototype=new t.Element.ElementBase,t.CreateElement=function(e){var i=e.nodeName.replace(/^[^:]+:/,"");i=i.replace(/\-/g,"");var n=null;return n=t.Element[i]!==void 0?new t.Element[i](e):new t.Element.MISSING(e),n.type=e.nodeName,n},t.load=function(e,i){t.loadXml(e,t.ajax(i))},t.loadXml=function(e,i){t.loadXmlDoc(e,t.parseXml(i))},t.loadXmlDoc=function(e,i){t.init(e);var n=function(t){for(var i=e.canvas;i;)t.x-=i.offsetLeft,t.y-=i.offsetTop,i=i.offsetParent;return window.scrollX&&(t.x+=window.scrollX),window.scrollY&&(t.y+=window.scrollY),t};1!=t.opts.ignoreMouse&&(e.canvas.onclick=function(e){var i=n(new t.Point(null!=e?e.clientX:event.clientX,null!=e?e.clientY:event.clientY));t.Mouse.onclick(i.x,i.y)},e.canvas.onmousemove=function(e){var i=n(new t.Point(null!=e?e.clientX:event.clientX,null!=e?e.clientY:event.clientY));t.Mouse.onmousemove(i.x,i.y)});var r=t.CreateElement(i.documentElement);r.root=!0;var a=!0,s=function(){t.ViewPort.Clear(),e.canvas.parentNode&&t.ViewPort.SetCurrent(e.canvas.parentNode.clientWidth,e.canvas.parentNode.clientHeight),1!=t.opts.ignoreDimensions&&(r.style("width").hasValue()&&(e.canvas.width=r.style("width").toPixels("x"),e.canvas.style.width=e.canvas.width+"px"),r.style("height").hasValue()&&(e.canvas.height=r.style("height").toPixels("y"),e.canvas.style.height=e.canvas.height+"px"));var n=e.canvas.clientWidth||e.canvas.width,s=e.canvas.clientHeight||e.canvas.height;if(1==t.opts.ignoreDimensions&&r.style("width").hasValue()&&r.style("height").hasValue()&&(n=r.style("width").toPixels("x"),s=r.style("height").toPixels("y")),t.ViewPort.SetCurrent(n,s),null!=t.opts.offsetX&&(r.attribute("x",!0).value=t.opts.offsetX),null!=t.opts.offsetY&&(r.attribute("y",!0).value=t.opts.offsetY),null!=t.opts.scaleWidth&&null!=t.opts.scaleHeight){var o=1,l=1,c=t.ToNumberArray(r.attribute("viewBox").value);r.attribute("width").hasValue()?o=r.attribute("width").toPixels("x")/t.opts.scaleWidth:isNaN(c[2])||(o=c[2]/t.opts.scaleWidth),r.attribute("height").hasValue()?l=r.attribute("height").toPixels("y")/t.opts.scaleHeight:isNaN(c[3])||(l=c[3]/t.opts.scaleHeight),r.attribute("width",!0).value=t.opts.scaleWidth,r.attribute("height",!0).value=t.opts.scaleHeight,r.attribute("viewBox",!0).value="0 0 "+n*o+" "+s*l,r.attribute("preserveAspectRatio",!0).value="none"}1!=t.opts.ignoreClear&&e.clearRect(0,0,n,s),r.render(e),a&&(a=!1,"function"==typeof t.opts.renderCallback&&t.opts.renderCallback(i))},o=!0;t.ImagesLoaded()&&(o=!1,s()),t.intervalID=setInterval(function(){var e=!1;if(o&&t.ImagesLoaded()&&(o=!1,e=!0),1!=t.opts.ignoreMouse&&(e|=t.Mouse.hasEvents()),1!=t.opts.ignoreAnimation)for(var i=0;t.Animations.length>i;i++)e|=t.Animations[i].update(1e3/t.FRAMERATE);"function"==typeof t.opts.forceRedraw&&1==t.opts.forceRedraw()&&(e=!0),e&&(s(),t.Mouse.runEvents())},1e3/t.FRAMERATE)},t.stop=function(){t.intervalID&&clearInterval(t.intervalID)},t.Mouse=new function(){this.events=[],this.hasEvents=function(){return 0!=this.events.length},this.onclick=function(t,e){this.events.push({type:"onclick",x:t,y:e,run:function(t){t.onclick&&t.onclick()}})},this.onmousemove=function(t,e){this.events.push({type:"onmousemove",x:t,y:e,run:function(t){t.onmousemove&&t.onmousemove()}})},this.eventElements=[],this.checkPath=function(t,e){for(var i=0;this.events.length>i;i++){var n=this.events[i];e.isPointInPath&&e.isPointInPath(n.x,n.y)&&(this.eventElements[i]=t)}},this.checkBoundingBox=function(t,e){for(var i=0;this.events.length>i;i++){var n=this.events[i];e.isPointInBox(n.x,n.y)&&(this.eventElements[i]=t)}},this.runEvents=function(){t.ctx.canvas.style.cursor="";for(var e=0;this.events.length>e;e++)for(var i=this.events[e],n=this.eventElements[e];n;)i.run(n),n=n.parent;this.events=[],this.eventElements=[]}},t}this.canvg=function(e,i,n){if(null!=e||null!=i||null!=n){n=n||{},"string"==typeof e&&(e=document.getElementById(e)),null!=e.svg&&e.svg.stop();var r=t();(1!=e.childNodes.length||"OBJECT"!=e.childNodes[0].nodeName)&&(e.svg=r),r.opts=n;var a=e.getContext("2d");i.documentElement!==void 0?r.loadXmlDoc(a,i):"<"==i.substr(0,1)?r.loadXml(a,i):r.load(a,i)}else for(var s=document.getElementsByTagName("svg"),o=0;s.length>o;o++){var l=s[o],c=document.createElement("canvas");c.width=l.clientWidth,c.height=l.clientHeight,l.parentNode.insertBefore(c,l),l.parentNode.removeChild(l);var h=document.createElement("div");h.appendChild(l),canvg(c,h.innerHTML)}}}(),"undefined"!=typeof CanvasRenderingContext2D&&(CanvasRenderingContext2D.prototype.drawSvg=function(t,e,i,n,r){canvg(this.canvas,t,{ignoreMouse:!0,ignoreAnimation:!0,ignoreDimensions:!0,ignoreClear:!0,offsetX:e,offsetY:i,scaleWidth:n,scaleHeight:r})});var mul_table=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],shg_table=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];if(joint.dia.Paper.prototype.toDataURL=function(t,e){if("function"!=typeof this.toSVG)throw Error("The joint.format.svg.js plugin must be loaded.");e=e||{};var i,n,r,a,s=e.padding||0;if(e.width&&e.height)i=e.width,n=e.height,s=Math.min(s,i/2-1,n/2-1),a=i-2*s,r=n-2*s;else{var o=this.viewport.getBoundingClientRect();a=o.width||1,r=o.height||1,i=a+2*s,n=r+2*s}var l=new Image;l.onload=function(){function o(){p=document.createElement("canvas"),p.width=i,p.height=n,u=p.getContext("2d"),u.fillStyle=e.backgroundColor||"white",u.fillRect(0,0,i,n)}var h,u,p;o(),u.drawImage(l,s,s,a,r);try{h=p.toDataURL(e.type,e.quality)}catch(g){return"undefined"==typeof canvg?(console.error("Canvas tainted. Canvg library required."),void 0):(o(),canvg(p,c,{ignoreDimensions:!0,ignoreClear:!0,offsetX:s,offsetY:s,renderCallback:function(){h=p.toDataURL(e.type,e.quality),t(h)}}),void 0)}t(h)};var c=this.toSVG();c=c.replace('width="100%"','width="'+a+'"').replace('height="100%"','height="'+r+'"'),l.src="data:image/svg+xml;base64,"+btoa(c)},joint.dia.Paper.prototype.toPNG=function(t,e){e=e||{},e.type="image/png",this.toDataURL(t,e)},joint.dia.Paper.prototype.toJPEG=function(t,e){e=e||{},e.type="image/jpeg",this.toDataURL(t,e)},function(){function t(t,e){var i=V(this.svg),n=this.getContentBBox().moveAndExpand({x:-t.padding,y:-t.padding,width:2*t.padding,height:2*t.padding});e.attrs={width:i.attr("width"),height:i.attr("height"),viewBox:i.attr("viewBox")},e.scrollLeft=this.el.scrollLeft,e.scrollTop=this.el.scrollTop,i.attr({width:"100%",height:"100%",viewBox:[n.x,n.y,n.width,n.height].join(" ")}),this.$el.addClass("printarea").addClass(t.size),t.detachBody&&(e.$parent=this.$el.parent(),e.$content=$(document.body).children().detach(),this.$el.appendTo(document.body))}function e(t,e){var i=V(this.svg),n=!!window.chrome&&!window.opera,r=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;!n&&!r||e.attrs.viewBox||(i.node.removeAttributeNS(null,"viewBox"),delete e.attrs.viewBox),i.attr(e.attrs),this.$el.removeClass("printarea").removeClass(t.size),t.detachBody&&(this.$el.appendTo(e.$parent),e.$content.appendTo(document.body)),this.el.scrollLeft=e.scrollLeft,this.el.scrollTop=e.scrollTop}var i="onbeforeprint"in window;joint.dia.Paper.prototype.print=function(n){n=n||{},_.defaults(n,{size:"a4",padding:5,detachBody:!0});var r={},a=_.bind(t,this,n,r),s=_.bind(e,this,n,r);if(i?($(window).one("beforeprint",a),$(window).one("afterprint",s)):a(),window.print(),!i){var o=_.once(s);$(document).one("mouseover",o),_.delay(o,1e3)}}}(),"object"==typeof exports)var joint={com:{},util:require("../../../src/core").util},WebSocketServer=require("ws").Server,WebSocket=require("ws"),_=require("lodash"),url=require("url"),Backbone=require("backbone");joint.com=joint.com||{},joint.com.Channel=function(t){if(this.options=t,!this.options||!this.options.graph)throw Error("Channel: missing a graph.");this.options.ttl=this.options.ttl||60,this.options.healthCheckInterval=this.options.healthCheckInterval||36e5,this.options.reconnectInterval=this.options.reconnectInterval||1e4,this._isClient=!!this.options.url,this._clients=[],this.messageQueue=[],this.id=this.options.id||(this._isClient?"c_":"s_")+joint.util.uuid(),this.state={},this.state[this.id]=0,this.sites={},this.sites[this.id]={socket:void 0,outgoing:[],ttl:this.options.ttl},this.initialize()},_.extend(joint.com.Channel.prototype,Backbone.Events),joint.com.Channel.prototype.initialize=function(){this.options.graph.on("all",this.onGraphChange.bind(this)),this._isClient?this.connectClient():this.options.port&&(this.server=new WebSocketServer({port:this.options.port}),this.server.on("connection",this.onConnection.bind(this))),this._isClient||(this._healthCheckInterval=setInterval(this.healthCheck.bind(this),this.options.healthCheckInterval))},joint.com.Channel.prototype.connectClient=function(){var t=this.options.url+"/?channelId="+this.id+"&state="+JSON.stringify(this.state)+(this.options.query?"&query="+JSON.stringify(this.options.query):"");this.options.debugLevel>0&&this.log("connectClient",t);var e=new WebSocket(t);e.onopen=this.onConnection.bind(this,e),e.onclose=this.onClose.bind(this,e)},joint.com.Channel.prototype.close=function(){this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this._healthCheckInterval&&clearInterval(this._healthCheckInterval),this._closed=!0,_.each(this.sites,function(t){t.socket&&t.socket.close()}),this.server&&this.server.close()},joint.com.Channel.prototype.healthCheck=function(){this.options.debugLevel>0&&this.log("healthCheck",_.object(_.keys(this.sites),_.pluck(this.sites,"ttl"))),_.each(this.sites,function(t,e){e!==this.id&&(t.socket&&1===t.socket.readyState?t.ttl=this.options.ttl:t.ttl-=1,0>=t.ttl&&(delete this.sites[e],delete this.state[e]))},this)},joint.com.Channel.prototype.onConnection=function(t){if(this._clients.push(t),this._isClient)this.sites[this.id].socket=t,t.onmessage=function(e){this.onMessage(t,e.data)}.bind(this);else{var e=url.parse(t.upgradeReq.url,!0),i=e.query.channelId;if(this.sites[i])this.sites[i].socket=t;else{this.debugLevel>1&&this.log("new_site",i),this.sites[i]={socket:t,outgoing:[],ttl:this.options.ttl},this.state[i]=0;var n={channelId:this.id,state:JSON.parse(JSON.stringify(this.state)),action:"graph",graph:this.options.graph.toJSON()};this.messageQueue.push({type:"op",data:n,source:this.id,target:[i]}),this.send()}t.on("message",this.onMessage.bind(this,t)),t.on("close",this.onClose.bind(this,t))}},joint.com.Channel.prototype.onClose=function(t){var e=this._clients.indexOf(t);-1!==e&&this._clients.splice(e,1),this._isClient&&!this._closed&&(this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this._reconnectTimeout=setTimeout(this.connectClient.bind(this),this.options.reconnectInterval)),this.trigger("close",t)},joint.com.Channel.prototype.onMessage=function(t,e){this.trigger("message:received",e),this.options.debugLevel>1&&this.log("message",e);try{e=JSON.parse(e)}catch(i){return console.error("Channel: message parsing failed.",i)}if("notification"==e.type)return this.trigger(e.data.event,e.data.data),this.sendNotification(e);var n=e.data;if(this._isClient){var r=this.sites[this.id];n=this.receive(r,this.id,n)}else{var a=this.sites[n.channelId];n=this.receive(a,n.channelId,n);var r=this.sites[this.id];n=this.receive(r,this.id,n)}this.state[n.channelId]="graph"===n.action?n.state[n.channelId]:(this.state[n.channelId]||0)+1,this.options.debugLevel>1&&this.log("new state",this.state),this.execute(n),_.each(this.sites,function(t,e){e!==this.id&&e!==n.channelId&&this.receive(t,e,n)},this),this._isClient||(e.op=n,this.messageQueue.push(e),this.broadcast(e)),this.trigger("message:processed",e)},joint.com.Channel.prototype.receive=function(t,e,i){if(!t)return i;this.options.debugLevel>1&&this.log("receive",e,i),this.options.debugLevel>1&&this.log("outgoing",t.outgoing),t.outgoing=_.filter(t.outgoing,function(t){return t.state[t.channelId]>=(i.state[t.channelId]||0)}),this.options.debugLevel>1&&this.log("outgoing.length",t.outgoing.length);for(var n=0;t.outgoing.length>n;n++){var r=t.outgoing[n],a=this.transform(i,r);i=a[0],t.outgoing[n]=a[1]}return i},joint.com.Channel.prototype.transform=function(t,e){return this.options.debugLevel>1&&this.log("transform",t,e),"change:target"===t.action&&"remove"===e.action&&t.cell.target.id===e.cell.id&&(t.cell.target={x:0,y:0}),"change:source"===t.action&&"remove"===e.action&&t.cell.source.id===e.cell.id&&(t.cell.source={x:0,y:0}),[t,e]},joint.com.Channel.prototype.execute=function(t){var e;switch(t.action){case"add":this.options.graph.addCell(t.cell,{remote:!0});break;case"remove":e=this.options.graph.getCell(t.cell.id),e&&e.remove({remote:!0,disconnectLinks:!0});break;case"graph":this.options.graph.fromJSON(t.graph);break;default:var i=t.action.substr("change:".length);e=this.options.graph.getCell(t.cell.id),e&&e.set(i,t.cell[i],{remote:!0})}},joint.com.Channel.prototype.broadcast=function(t){t.target=this._isClient?_.keys(this.sites):_.keys(_.omit(this.sites,this.id,t.source)),this.send()},joint.com.Channel.prototype.send=function(){if(!this._paused){for(var t=[],e=0;this.messageQueue.length>e;e++){var i=this.messageQueue[e];this.sendMessage(i)&&t.push(e)}t.forEach(_.bind(function(t){this.messageQueue.splice(t,1)},this))}},joint.com.Channel.prototype.sendMessage=function(t){this.debugLevel>1&&this.log("sendMessage",t);var e=[];return t.target.forEach(function(i,n){var r=this.sites[i];return r?(r.socket&&1===r.socket.readyState&&(this.debugLevel>1&&this.log("sendMessage",i,t),r.socket.send(JSON.stringify(t)),e.push(n)),void 0):e.push(n)},this),e.forEach(function(e){t.target.splice(e,1)}),t.target.length?!1:!0},joint.com.Channel.prototype.log=function(t){var e="Channel ["+this.id+"] "+t.toUpperCase()+": ";console.log.apply(console,[e].concat(_.rest(_.toArray(arguments))))},joint.com.Channel.prototype.pause=function(){this._paused=!0},joint.com.Channel.prototype.unpause=function(){this._paused=!1,this.send()},joint.com.Channel.prototype.notify=function(t,e){var i={type:"notification",source:this.id,data:{event:t,data:e}};this.sendNotification(i)},joint.com.Channel.prototype.sendNotification=function(t){t.target=this._isClient?_.keys(this.sites):_.keys(_.omit(this.sites,this.id,t.source)),this.sendMessage(t)},joint.com.Channel.prototype.onGraphChange=function(t,e,i,n){if(!n||!n.remote){var r="add"===t||"remove"===t||"change:"===t.substr(0,"change:".length);if(r){var a={channelId:this.id,state:JSON.parse(JSON.stringify(this.state)),action:t,cell:e.toJSON()},s={type:"op",data:a,source:this.id};this.options.debugLevel>1&&this.log("generate",s),this.messageQueue.push(s),this.broadcast(s),this.sites[this.id].outgoing.push(a),this.state[this.id]++}}},joint.com.ChannelHub=function(t){if(this.options=t,!this.options.port)throw Error("ChannelHub: missing a port.");this.initialize()},_.extend(joint.com.ChannelHub.prototype,Backbone.Events),joint.com.ChannelHub.prototype.initialize=function(){this.server=new WebSocketServer({port:this.options.port}),this.server.on("connection",this.onConnection.bind(this))},joint.com.ChannelHub.prototype.onConnection=function(t){var e=url.parse(t.upgradeReq.url,!0),i={query:e.query};if(!this.router)throw Error("ChannelHub: missing a router.");var n=this.router(i);n.onConnection(t)},joint.com.ChannelHub.prototype.route=function(t){this.router=t},joint.com.ChannelHub.prototype.close=function(){this.server.close()},"object"==typeof exports&&(module.exports.Channel=joint.com.Channel,module.exports.ChannelHub=joint.com.ChannelHub);
diff --git a/js/joint.js b/js/joint.js
new file mode 100644 (file)
index 0000000..f62a8e3
--- /dev/null
@@ -0,0 +1,23470 @@
+/*! JointJS v0.9.0 - JavaScript diagramming library  2014-05-13 
+
+
+This Source Code Form is subject to the terms of the Mozilla Public
+License, v. 2.0. If a copy of the MPL was not distributed with this
+file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+/*!
+ * jQuery JavaScript Library v2.0.3
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2013-07-03T13:30Z
+ */
+(function( window, undefined ) {
+
+// Can't do this because several apps including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+// Support: Firefox 18+
+//"use strict";
+var
+       // A central reference to the root jQuery(document)
+       rootjQuery,
+
+       // The deferred used on DOM ready
+       readyList,
+
+       // Support: IE9
+       // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
+       core_strundefined = typeof undefined,
+
+       // Use the correct document accordingly with window argument (sandbox)
+       location = window.location,
+       document = window.document,
+       docElem = document.documentElement,
+
+       // Map over jQuery in case of overwrite
+       _jQuery = window.jQuery,
+
+       // Map over the $ in case of overwrite
+       _$ = window.$,
+
+       // [[Class]] -> type pairs
+       class2type = {},
+
+       // List of deleted data cache ids, so we can reuse them
+       core_deletedIds = [],
+
+       core_version = "2.0.3",
+
+       // Save a reference to some core methods
+       core_concat = core_deletedIds.concat,
+       core_push = core_deletedIds.push,
+       core_slice = core_deletedIds.slice,
+       core_indexOf = core_deletedIds.indexOf,
+       core_toString = class2type.toString,
+       core_hasOwn = class2type.hasOwnProperty,
+       core_trim = core_version.trim,
+
+       // Define a local copy of jQuery
+       jQuery = function( selector, context ) {
+               // The jQuery object is actually just the init constructor 'enhanced'
+               return new jQuery.fn.init( selector, context, rootjQuery );
+       },
+
+       // Used for matching numbers
+       core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
+
+       // Used for splitting on whitespace
+       core_rnotwhite = /\S+/g,
+
+       // 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-]*))$/,
+
+       // Match a standalone tag
+       rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
+
+       // 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();
+       },
+
+       // The ready event handler and self cleanup method
+       completed = function() {
+               document.removeEventListener( "DOMContentLoaded", completed, false );
+               window.removeEventListener( "load", completed, false );
+               jQuery.ready();
+       };
+
+jQuery.fn = jQuery.prototype = {
+       // The current version of jQuery being used
+       jquery: core_version,
+
+       constructor: jQuery,
+       init: function( selector, context, rootjQuery ) {
+               var match, elem;
+
+               // HANDLE: $(""), $(null), $(undefined), $(false)
+               if ( !selector ) {
+                       return this;
+               }
+
+               // 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
+                                       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 ) {
+                                               // 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 || rootjQuery ).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 rootjQuery.ready( selector );
+               }
+
+               if ( selector.selector !== undefined ) {
+                       this.selector = selector.selector;
+                       this.context = selector.context;
+               }
+
+               return jQuery.makeArray( selector, this );
+       },
+
+       // Start with an empty selector
+       selector: "",
+
+       // The default length of a jQuery object is 0
+       length: 0,
+
+       toArray: function() {
+               return core_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 a 'clean' array
+                       this.toArray() :
+
+                       // Return just the object
+                       ( num < 0 ? this[ this.length + num ] : this[ num ] );
+       },
+
+       // 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.
+       // (You can seed the arguments with an array of args, but this is
+       // only used internally.)
+       each: function( callback, args ) {
+               return jQuery.each( this, callback, args );
+       },
+
+       ready: function( fn ) {
+               // Add the callback
+               jQuery.ready.promise().done( fn );
+
+               return this;
+       },
+
+       slice: function() {
+               return this.pushStack( core_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] ] : [] );
+       },
+
+       map: function( callback ) {
+               return this.pushStack( jQuery.map(this, function( elem, i ) {
+                       return callback.call( elem, i, elem );
+               }));
+       },
+
+       end: function() {
+               return this.prevObject || this.constructor(null);
+       },
+
+       // For internal use only.
+       // Behaves like an Array's method, not like a jQuery method.
+       push: core_push,
+       sort: [].sort,
+       splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+       var options, name, src, copy, copyIsArray, clone,
+               target = arguments[0] || {},
+               i = 1,
+               length = arguments.length,
+               deep = false;
+
+       // Handle a deep copy situation
+       if ( typeof target === "boolean" ) {
+               deep = target;
+               target = arguments[1] || {};
+               // skip the boolean and the target
+               i = 2;
+       }
+
+       // 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 ( length === i ) {
+               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" + ( core_version + Math.random() ).replace( /\D/g, "" ),
+
+       noConflict: function( deep ) {
+               if ( window.$ === jQuery ) {
+                       window.$ = _$;
+               }
+
+               if ( deep && window.jQuery === jQuery ) {
+                       window.jQuery = _jQuery;
+               }
+
+               return jQuery;
+       },
+
+       // 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.trigger ) {
+                       jQuery( document ).trigger("ready").off("ready");
+               }
+       },
+
+       // 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,
+
+       isWindow: function( obj ) {
+               return obj != null && obj === obj.window;
+       },
+
+       isNumeric: function( obj ) {
+               return !isNaN( parseFloat(obj) ) && isFinite( obj );
+       },
+
+       type: function( obj ) {
+               if ( obj == null ) {
+                       return String( obj );
+               }
+               // Support: Safari <= 5.1 (functionish RegExp)
+               return typeof obj === "object" || typeof obj === "function" ?
+                       class2type[ core_toString.call(obj) ] || "object" :
+                       typeof obj;
+       },
+
+       isPlainObject: function( obj ) {
+               // Not plain objects:
+               // - Any object or value whose internal [[Class]] property is not "[object Object]"
+               // - DOM nodes
+               // - window
+               if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+                       return false;
+               }
+
+               // Support: Firefox <20
+               // The try/catch suppresses exceptions thrown when attempting to access
+               // the "constructor" property of certain host objects, ie. |window.location|
+               // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
+               try {
+                       if ( obj.constructor &&
+                                       !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
+                               return false;
+                       }
+               } catch ( e ) {
+                       return false;
+               }
+
+               // If the function hasn't returned already, we're confident that
+               // |obj| is a plain object, created by {} or constructed with new Object
+               return true;
+       },
+
+       isEmptyObject: function( obj ) {
+               var name;
+               for ( name in obj ) {
+                       return false;
+               }
+               return true;
+       },
+
+       error: function( msg ) {
+               throw new Error( msg );
+       },
+
+       // 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
+       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 = jQuery.buildFragment( [ data ], context, scripts );
+
+               if ( scripts ) {
+                       jQuery( scripts ).remove();
+               }
+
+               return jQuery.merge( [], parsed.childNodes );
+       },
+
+       parseJSON: JSON.parse,
+
+       // Cross-browser xml parsing
+       parseXML: function( data ) {
+               var xml, tmp;
+               if ( !data || typeof data !== "string" ) {
+                       return null;
+               }
+
+               // Support: IE9
+               try {
+                       tmp = new DOMParser();
+                       xml = tmp.parseFromString( data , "text/xml" );
+               } catch ( e ) {
+                       xml = undefined;
+               }
+
+               if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
+                       jQuery.error( "Invalid XML: " + data );
+               }
+               return xml;
+       },
+
+       noop: function() {},
+
+       // Evaluates a script in a global context
+       globalEval: function( code ) {
+               var script,
+                               indirect = eval;
+
+               code = jQuery.trim( code );
+
+               if ( code ) {
+                       // If the code includes a valid, prologue position
+                       // strict mode pragma, execute code by injecting a
+                       // script tag into the document.
+                       if ( code.indexOf("use strict") === 1 ) {
+                               script = document.createElement("script");
+                               script.text = code;
+                               document.head.appendChild( script ).parentNode.removeChild( script );
+                       } else {
+                       // Otherwise, avoid the DOM node creation, insertion
+                       // and removal by using an indirect global eval
+                               indirect( code );
+                       }
+               }
+       },
+
+       // 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();
+       },
+
+       // args is for internal usage only
+       each: function( obj, callback, args ) {
+               var value,
+                       i = 0,
+                       length = obj.length,
+                       isArray = isArraylike( obj );
+
+               if ( args ) {
+                       if ( isArray ) {
+                               for ( ; i < length; i++ ) {
+                                       value = callback.apply( obj[ i ], args );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       } else {
+                               for ( i in obj ) {
+                                       value = callback.apply( obj[ i ], args );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       }
+
+               // A special, fast, case for the most common use of each
+               } else {
+                       if ( isArray ) {
+                               for ( ; i < length; i++ ) {
+                                       value = callback.call( obj[ i ], i, obj[ i ] );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       } else {
+                               for ( i in obj ) {
+                                       value = callback.call( obj[ i ], i, obj[ i ] );
+
+                                       if ( value === false ) {
+                                               break;
+                                       }
+                               }
+                       }
+               }
+
+               return obj;
+       },
+
+       trim: function( text ) {
+               return text == null ? "" : core_trim.call( text );
+       },
+
+       // 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 {
+                               core_push.call( ret, arr );
+                       }
+               }
+
+               return ret;
+       },
+
+       inArray: function( elem, arr, i ) {
+               return arr == null ? -1 : core_indexOf.call( arr, elem, i );
+       },
+
+       merge: function( first, second ) {
+               var l = second.length,
+                       i = first.length,
+                       j = 0;
+
+               if ( typeof l === "number" ) {
+                       for ( ; j < l; j++ ) {
+                               first[ i++ ] = second[ j ];
+                       }
+               } else {
+                       while ( second[j] !== undefined ) {
+                               first[ i++ ] = second[ j++ ];
+                       }
+               }
+
+               first.length = i;
+
+               return first;
+       },
+
+       grep: function( elems, callback, inv ) {
+               var retVal,
+                       ret = [],
+                       i = 0,
+                       length = elems.length;
+               inv = !!inv;
+
+               // Go through the array, only saving the items
+               // that pass the validator function
+               for ( ; i < length; i++ ) {
+                       retVal = !!callback( elems[ i ], i );
+                       if ( inv !== retVal ) {
+                               ret.push( elems[ i ] );
+                       }
+               }
+
+               return ret;
+       },
+
+       // arg is for internal usage only
+       map: function( elems, callback, arg ) {
+               var value,
+                       i = 0,
+                       length = elems.length,
+                       isArray = isArraylike( elems ),
+                       ret = [];
+
+               // Go through the array, translating each of the items to their
+               if ( isArray ) {
+                       for ( ; i < length; i++ ) {
+                               value = callback( elems[ i ], i, arg );
+
+                               if ( value != null ) {
+                                       ret[ ret.length ] = value;
+                               }
+                       }
+
+               // Go through every key on the object,
+               } else {
+                       for ( i in elems ) {
+                               value = callback( elems[ i ], i, arg );
+
+                               if ( value != null ) {
+                                       ret[ ret.length ] = value;
+                               }
+                       }
+               }
+
+               // Flatten any nested arrays
+               return core_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 tmp, args, proxy;
+
+               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 = core_slice.call( arguments, 2 );
+               proxy = function() {
+                       return fn.apply( context || this, args.concat( core_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;
+       },
+
+       // Multifunctional method to get and set values of a collection
+       // The value/s can optionally be executed if it's a function
+       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 ) {
+                               jQuery.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;
+       },
+
+       now: Date.now,
+
+       // A method for quickly swapping in/out CSS properties to get correct calculations.
+       // Note: this method belongs to the css module but it's needed here for the support module.
+       // If support gets modularized, this method should be moved back to the css module.
+       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;
+       }
+});
+
+jQuery.ready.promise = function( obj ) {
+       if ( !readyList ) {
+
+               readyList = jQuery.Deferred();
+
+               // Catch cases where $(document).ready() is called after the browser event has already occurred.
+               // we once tried to use readyState "interactive" here, but it caused issues like the one
+               // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
+               if ( document.readyState === "complete" ) {
+                       // Handle it asynchronously to allow scripts the opportunity to delay ready
+                       setTimeout( jQuery.ready );
+
+               } else {
+
+                       // Use the handy event callback
+                       document.addEventListener( "DOMContentLoaded", completed, false );
+
+                       // A fallback to window.onload, that will always work
+                       window.addEventListener( "load", completed, false );
+               }
+       }
+       return readyList.promise( obj );
+};
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
+       class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+function isArraylike( obj ) {
+       var length = obj.length,
+               type = jQuery.type( obj );
+
+       if ( jQuery.isWindow( obj ) ) {
+               return false;
+       }
+
+       if ( obj.nodeType === 1 && length ) {
+               return true;
+       }
+
+       return type === "array" || type !== "function" &&
+               ( length === 0 ||
+               typeof length === "number" && length > 0 && ( length - 1 ) in obj );
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+/*!
+ * Sizzle CSS Selector Engine v1.9.4-pre
+ * http://sizzlejs.com/
+ *
+ * Copyright 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2013-06-03
+ */
+(function( window, undefined ) {
+
+var i,
+       support,
+       cachedruns,
+       Expr,
+       getText,
+       isXML,
+       compile,
+       outermostContext,
+       sortInput,
+
+       // Local document vars
+       setDocument,
+       document,
+       docElem,
+       documentIsHTML,
+       rbuggyQSA,
+       rbuggyMatches,
+       matches,
+       contains,
+
+       // Instance-specific data
+       expando = "sizzle" + -(new Date()),
+       preferredDoc = window.document,
+       dirruns = 0,
+       done = 0,
+       classCache = createCache(),
+       tokenCache = createCache(),
+       compilerCache = createCache(),
+       hasDuplicate = false,
+       sortOrder = function( a, b ) {
+               if ( a === b ) {
+                       hasDuplicate = true;
+                       return 0;
+               }
+               return 0;
+       },
+
+       // General-purpose constants
+       strundefined = typeof undefined,
+       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 if we can't use a native one
+       indexOf = arr.indexOf || function( elem ) {
+               var i = 0,
+                       len = this.length;
+               for ( ; i < len; i++ ) {
+                       if ( this[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
+
+       // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
+       whitespace = "[\\x20\\t\\r\\n\\f]",
+       // http://www.w3.org/TR/css3-syntax/#characters
+       characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
+
+       // Loosely modeled on CSS identifier characters
+       // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
+       // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
+       identifier = characterEncoding.replace( "w", "w#" ),
+
+       // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
+       attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
+               "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
+
+       // Prefer arguments quoted,
+       //   then not containing pseudos/brackets,
+       //   then attribute selectors/non-parenthetical expressions,
+       //   then anything else
+       // These preferences are here to reduce the number of selectors
+       //   needing tokenize in the PSEUDO preFilter
+       pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
+
+       // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
+       rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
+
+       rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
+       rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
+
+       rsibling = new RegExp( whitespace + "*[+~]" ),
+       rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
+
+       rpseudo = new RegExp( pseudos ),
+       ridentifier = new RegExp( "^" + identifier + "$" ),
+
+       matchExpr = {
+               "ID": new RegExp( "^#(" + characterEncoding + ")" ),
+               "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
+               "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
+               "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" )
+       },
+
+       rnative = /^[^{]+\{\s*\[native \w/,
+
+       // Easily-parseable/retrievable ID or TAG or CLASS selectors
+       rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
+
+       rinputs = /^(?:input|select|textarea|button)$/i,
+       rheader = /^h\d$/i,
+
+       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
+               // Workaround erroneous numeric interpretation of +"0x"
+               return high !== high || escapedWhitespace ?
+                       escaped :
+                       // BMP codepoint
+                       high < 0 ?
+                               String.fromCharCode( high + 0x10000 ) :
+                               // Supplemental Plane codepoint (surrogate pair)
+                               String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
+       };
+
+// 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 match, elem, m, nodeType,
+               // QSA vars
+               i, groups, old, nid, newContext, newSelector;
+
+       if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
+               setDocument( context );
+       }
+
+       context = context || document;
+       results = results || [];
+
+       if ( !selector || typeof selector !== "string" ) {
+               return results;
+       }
+
+       if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
+               return [];
+       }
+
+       if ( documentIsHTML && !seed ) {
+
+               // Shortcuts
+               if ( (match = rquickExpr.exec( selector )) ) {
+                       // Speed-up: Sizzle("#ID")
+                       if ( (m = match[1]) ) {
+                               if ( nodeType === 9 ) {
+                                       elem = context.getElementById( m );
+                                       // 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, Opera, and Webkit return items
+                                               // by name instead of ID
+                                               if ( elem.id === m ) {
+                                                       results.push( elem );
+                                                       return results;
+                                               }
+                                       } else {
+                                               return results;
+                                       }
+                               } else {
+                                       // Context is not a document
+                                       if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
+                                               contains( context, elem ) && elem.id === m ) {
+                                               results.push( elem );
+                                               return results;
+                                       }
+                               }
+
+                       // Speed-up: Sizzle("TAG")
+                       } else if ( match[2] ) {
+                               push.apply( results, context.getElementsByTagName( selector ) );
+                               return results;
+
+                       // Speed-up: Sizzle(".CLASS")
+                       } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
+                               push.apply( results, context.getElementsByClassName( m ) );
+                               return results;
+                       }
+               }
+
+               // QSA path
+               if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
+                       nid = old = expando;
+                       newContext = context;
+                       newSelector = nodeType === 9 && selector;
+
+                       // qSA works strangely on Element-rooted queries
+                       // We can work around this by specifying an extra ID on the root
+                       // and working up from there (Thanks to Andrew Dupont for the technique)
+                       // IE 8 doesn't work on object elements
+                       if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+                               groups = tokenize( selector );
+
+                               if ( (old = context.getAttribute("id")) ) {
+                                       nid = old.replace( rescape, "\\$&" );
+                               } else {
+                                       context.setAttribute( "id", nid );
+                               }
+                               nid = "[id='" + nid + "'] ";
+
+                               i = groups.length;
+                               while ( i-- ) {
+                                       groups[i] = nid + toSelector( groups[i] );
+                               }
+                               newContext = rsibling.test( selector ) && context.parentNode || context;
+                               newSelector = groups.join(",");
+                       }
+
+                       if ( newSelector ) {
+                               try {
+                                       push.apply( results,
+                                               newContext.querySelectorAll( newSelector )
+                                       );
+                                       return results;
+                               } catch(qsaError) {
+                               } finally {
+                                       if ( !old ) {
+                                               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 = attrs.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]);
+                               }
+                       }
+               });
+       });
+}
+
+/**
+ * Detect xml
+ * @param {Element|Object} elem An element or a document
+ */
+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;
+};
+
+// Expose support vars for convenience
+support = Sizzle.support = {};
+
+/**
+ * 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 doc = node ? node.ownerDocument || node : preferredDoc,
+               parent = doc.defaultView;
+
+       // If no document and documentElement is available, return
+       if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
+               return document;
+       }
+
+       // Set our document
+       document = doc;
+       docElem = doc.documentElement;
+
+       // Support tests
+       documentIsHTML = !isXML( doc );
+
+       // Support: IE>8
+       // If iframe document is assigned to "document" variable and if iframe has been reloaded,
+       // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
+       // IE6-8 do not support the defaultView property so parent will be undefined
+       if ( parent && parent.attachEvent && parent !== parent.top ) {
+               parent.attachEvent( "onbeforeunload", function() {
+                       setDocument();
+               });
+       }
+
+       /* 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( doc.createComment("") );
+               return !div.getElementsByTagName("*").length;
+       });
+
+       // Check if getElementsByClassName can be trusted
+       support.getElementsByClassName = assert(function( div ) {
+               div.innerHTML = "<div class='a'></div><div class='a i'></div>";
+
+               // Support: Safari<4
+               // Catch class over-caching
+               div.firstChild.className = "i";
+               // Support: Opera<10
+               // Catch gEBCN failure to find non-leading classes
+               return div.getElementsByClassName("i").length === 2;
+       });
+
+       // 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 !doc.getElementsByName || !doc.getElementsByName( expando ).length;
+       });
+
+       // ID find and filter
+       if ( support.getById ) {
+               Expr.find["ID"] = function( id, context ) {
+                       if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
+                               var m = context.getElementById( id );
+                               // Check parentNode to catch when Blackberry 4.6 returns
+                               // nodes that are no longer in the document #6963
+                               return m && m.parentNode ? [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 !== strundefined && elem.getAttributeNode("id");
+                               return node && node.value === attrId;
+                       };
+               };
+       }
+
+       // Tag
+       Expr.find["TAG"] = support.getElementsByTagName ?
+               function( tag, context ) {
+                       if ( typeof context.getElementsByTagName !== strundefined ) {
+                               return context.getElementsByTagName( tag );
+                       }
+               } :
+               function( tag, context ) {
+                       var elem,
+                               tmp = [],
+                               i = 0,
+                               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 !== strundefined && 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( doc.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
+                       div.innerHTML = "<select><option selected=''></option></select>";
+
+                       // Support: IE8
+                       // Boolean attributes and "value" are not treated correctly
+                       if ( !div.querySelectorAll("[selected]").length ) {
+                               rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
+                       }
+
+                       // 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");
+                       }
+               });
+
+               assert(function( div ) {
+
+                       // Support: Opera 10-12/IE8
+                       // ^= $= *= and empty values
+                       // Should not select anything
+                       // Support: Windows 8 Native Apps
+                       // The type attribute is restricted during .innerHTML assignment
+                       var input = doc.createElement("input");
+                       input.setAttribute( "type", "hidden" );
+                       div.appendChild( input ).setAttribute( "t", "" );
+
+                       if ( div.querySelectorAll("[t^='']").length ) {
+                               rbuggyQSA.push( "[*^$]=" + 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.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
+       ---------------------------------------------------------------------- */
+
+       // Element contains another
+       // Purposefully does not implement inclusive descendent
+       // As in, an element does not contain itself
+       contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
+               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 = docElem.compareDocumentPosition ?
+       function( a, b ) {
+
+               // Flag for duplicate removal
+               if ( a === b ) {
+                       hasDuplicate = true;
+                       return 0;
+               }
+
+               var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
+
+               if ( compare ) {
+                       // Disconnected nodes
+                       if ( compare & 1 ||
+                               (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
+
+                               // Choose the first element that is related to our preferred document
+                               if ( a === doc || contains(preferredDoc, a) ) {
+                                       return -1;
+                               }
+                               if ( b === doc || contains(preferredDoc, b) ) {
+                                       return 1;
+                               }
+
+                               // Maintain original order
+                               return sortInput ?
+                                       ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
+                                       0;
+                       }
+
+                       return compare & 4 ? -1 : 1;
+               }
+
+               // Not directly comparable, sort on existence of method
+               return a.compareDocumentPosition ? -1 : 1;
+       } :
+       function( a, b ) {
+               var cur,
+                       i = 0,
+                       aup = a.parentNode,
+                       bup = b.parentNode,
+                       ap = [ a ],
+                       bp = [ b ];
+
+               // Exit early if the nodes are identical
+               if ( a === b ) {
+                       hasDuplicate = true;
+                       return 0;
+
+               // Parentless nodes are either documents or disconnected
+               } else if ( !aup || !bup ) {
+                       return a === doc ? -1 :
+                               b === doc ? 1 :
+                               aup ? -1 :
+                               bup ? 1 :
+                               sortInput ?
+                               ( indexOf.call( sortInput, a ) - indexOf.call( 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 doc;
+};
+
+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 &&
+               ( !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 ?
+               support.attributes || !documentIsHTML ?
+                       elem.getAttribute( name ) :
+                       (val = elem.getAttributeNode(name)) && val.specified ?
+                               val.value :
+                               null :
+               val;
+};
+
+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 );
+               }
+       }
+
+       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
+               for ( ; (node = elem[i]); 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 (see #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[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[5] && match[2];
+
+                       if ( matchExpr["CHILD"].test( match[0] ) ) {
+                               return null;
+                       }
+
+                       // Accept quoted arguments as-is
+                       if ( match[3] && match[4] !== undefined ) {
+                               match[2] = match[4];
+
+                       // 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 !== strundefined && 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 + " " ).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, outerCache, node, diff, nodeIndex, start,
+                                               dir = simple !== forward ? "nextSibling" : "previousSibling",
+                                               parent = elem.parentNode,
+                                               name = ofType && elem.nodeName.toLowerCase(),
+                                               useCache = !xml && !ofType;
+
+                                       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
+                                                       outerCache = parent[ expando ] || (parent[ expando ] = {});
+                                                       cache = outerCache[ type ] || [];
+                                                       nodeIndex = cache[0] === dirruns && cache[1];
+                                                       diff = cache[0] === dirruns && 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 ) {
+                                                                       outerCache[ type ] = [ dirruns, nodeIndex, diff ];
+                                                                       break;
+                                                               }
+                                                       }
+
+                                               // Use previously-cached element index if available
+                                               } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
+                                                       diff = cache[1];
+
+                                               // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
+                                               } else {
+                                                       // 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 ) {
+                                                                               (node[ expando ] || (node[ expando ] = {}))[ 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.call( 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 );
+                                       return !results.pop();
+                               };
+               }),
+
+               "has": markFunction(function( selector ) {
+                       return function( elem ) {
+                               return Sizzle( selector, elem ).length > 0;
+                       };
+               }),
+
+               "contains": markFunction(function( text ) {
+                       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 only affected by element nodes and content nodes(including text(3), cdata(4)),
+                       //   not comment, processing instructions, or others
+                       // Thanks to Diego Perini for the nodeName shortcut
+                       //   Greater than "@" means alpha characters (specifically not starting with "#" or "?")
+                       for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+                               if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
+                                       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;
+                       // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
+                       // use getAttribute instead to test this case
+                       return elem.nodeName.toLowerCase() === "input" &&
+                               elem.type === "text" &&
+                               ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
+               },
+
+               // 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();
+
+function tokenize( 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 data, cache, outerCache,
+                               dirkey = dirruns + " " + doneName;
+
+                       // We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
+                                               if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
+                                                       if ( (data = cache[1]) === true || data === cachedruns ) {
+                                                               return data === true;
+                                                       }
+                                               } else {
+                                                       cache = outerCache[ dir ] = [ dirkey ];
+                                                       cache[1] = matcher( elem, context, xml ) || cachedruns;
+                                                       if ( cache[1] === true ) {
+                                                               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 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.call( 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.call( checkContext, elem ) > -1;
+               }, implicitRelative, true ),
+               matchers = [ function( elem, context, xml ) {
+                       return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
+                               (checkContext = context).nodeType ?
+                                       matchContext( elem, context, xml ) :
+                                       matchAnyContext( elem, context, xml ) );
+               } ];
+
+       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 ) {
+       // A counter to specify which element is currently being matched
+       var matcherCachedRuns = 0,
+               bySet = setMatchers.length > 0,
+               byElement = elementMatchers.length > 0,
+               superMatcher = function( seed, context, xml, results, expandContext ) {
+                       var elem, j, matcher,
+                               setMatched = [],
+                               matchedCount = 0,
+                               i = "0",
+                               unmatched = seed && [],
+                               outermost = expandContext != null,
+                               contextBackup = outermostContext,
+                               // We must always have either seed elements or context
+                               elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
+                               // Use integer dirruns iff this is the outermost matcher
+                               dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
+
+                       if ( outermost ) {
+                               outermostContext = context !== document && context;
+                               cachedruns = matcherCachedRuns;
+                       }
+
+                       // Add elements passing elementMatchers directly to results
+                       // Keep `i` a string if there are no elements so `matchedCount` will be "00" below
+                       for ( ; (elem = elems[i]) != null; i++ ) {
+                               if ( byElement && elem ) {
+                                       j = 0;
+                                       while ( (matcher = elementMatchers[j++]) ) {
+                                               if ( matcher( elem, context, xml ) ) {
+                                                       results.push( elem );
+                                                       break;
+                                               }
+                                       }
+                                       if ( outermost ) {
+                                               dirruns = dirrunsUnique;
+                                               cachedruns = ++matcherCachedRuns;
+                                       }
+                               }
+
+                               // 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 );
+                                       }
+                               }
+                       }
+
+                       // Apply set filters to unmatched elements
+                       matchedCount += i;
+                       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, group /* 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 ( !group ) {
+                       group = tokenize( selector );
+               }
+               i = group.length;
+               while ( i-- ) {
+                       cached = matcherFromTokens( group[i] );
+                       if ( cached[ expando ] ) {
+                               setMatchers.push( cached );
+                       } else {
+                               elementMatchers.push( cached );
+                       }
+               }
+
+               // Cache the compiled function
+               cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
+       }
+       return cached;
+};
+
+function multipleContexts( selector, contexts, results ) {
+       var i = 0,
+               len = contexts.length;
+       for ( ; i < len; i++ ) {
+               Sizzle( selector, contexts[i], results );
+       }
+       return results;
+}
+
+function select( selector, context, results, seed ) {
+       var i, tokens, token, type, find,
+               match = tokenize( selector );
+
+       if ( !seed ) {
+               // Try to minimize operations if there is only one group
+               if ( match.length === 1 ) {
+
+                       // Take a shortcut and set the context if the root 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;
+                               }
+                               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 ) && 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
+       // Provide `match` to avoid retokenization if we modified the selector above
+       compile( selector, match )(
+               seed,
+               context,
+               !documentIsHTML,
+               results,
+               rsibling.test( selector )
+       );
+       return results;
+}
+
+// One-time assignments
+
+// Sort stability
+support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
+
+// Support: Chrome<14
+// 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 (val = elem.getAttributeNode( name )) && val.specified ?
+                               val.value :
+                               elem[ name ] === true ? name.toLowerCase() : null;
+               }
+       });
+}
+
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.pseudos;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+})( window );
+// String to Object options format cache
+var optionsCache = {};
+
+// Convert String-formatted options into Object-formatted ones and store in cache
+function createOptions( options ) {
+       var object = optionsCache[ options ] = {};
+       jQuery.each( options.match( core_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" ?
+               ( optionsCache[ options ] || createOptions( options ) ) :
+               jQuery.extend( {}, options );
+
+       var // Last fire value (for non-forgettable lists)
+               memory,
+               // Flag to know if list was already fired
+               fired,
+               // Flag to know if list is currently firing
+               firing,
+               // First callback to fire (used internally by add and fireWith)
+               firingStart,
+               // End of the loop when firing
+               firingLength,
+               // Index of currently firing callback (modified by remove if needed)
+               firingIndex,
+               // Actual callback list
+               list = [],
+               // Stack of fire calls for repeatable lists
+               stack = !options.once && [],
+               // Fire callbacks
+               fire = function( data ) {
+                       memory = options.memory && data;
+                       fired = true;
+                       firingIndex = firingStart || 0;
+                       firingStart = 0;
+                       firingLength = list.length;
+                       firing = true;
+                       for ( ; list && firingIndex < firingLength; firingIndex++ ) {
+                               if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
+                                       memory = false; // To prevent further calls using add
+                                       break;
+                               }
+                       }
+                       firing = false;
+                       if ( list ) {
+                               if ( stack ) {
+                                       if ( stack.length ) {
+                                               fire( stack.shift() );
+                                       }
+                               } else if ( memory ) {
+                                       list = [];
+                               } else {
+                                       self.disable();
+                               }
+                       }
+               },
+               // Actual Callbacks object
+               self = {
+                       // Add a callback or a collection of callbacks to the list
+                       add: function() {
+                               if ( list ) {
+                                       // First, we save the current length
+                                       var start = list.length;
+                                       (function add( args ) {
+                                               jQuery.each( args, function( _, arg ) {
+                                                       var type = jQuery.type( arg );
+                                                       if ( type === "function" ) {
+                                                               if ( !options.unique || !self.has( arg ) ) {
+                                                                       list.push( arg );
+                                                               }
+                                                       } else if ( arg && arg.length && type !== "string" ) {
+                                                               // Inspect recursively
+                                                               add( arg );
+                                                       }
+                                               });
+                                       })( arguments );
+                                       // Do we need to add the callbacks to the
+                                       // current firing batch?
+                                       if ( firing ) {
+                                               firingLength = list.length;
+                                       // With memory, if we're not firing then
+                                       // we should call right away
+                                       } else if ( memory ) {
+                                               firingStart = start;
+                                               fire( memory );
+                                       }
+                               }
+                               return this;
+                       },
+                       // Remove a callback from the list
+                       remove: function() {
+                               if ( list ) {
+                                       jQuery.each( arguments, function( _, arg ) {
+                                               var index;
+                                               while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
+                                                       list.splice( index, 1 );
+                                                       // Handle firing indexes
+                                                       if ( firing ) {
+                                                               if ( index <= firingLength ) {
+                                                                       firingLength--;
+                                                               }
+                                                               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 && list.length );
+                       },
+                       // Remove all callbacks from the list
+                       empty: function() {
+                               list = [];
+                               firingLength = 0;
+                               return this;
+                       },
+                       // Have the list do nothing anymore
+                       disable: function() {
+                               list = stack = memory = undefined;
+                               return this;
+                       },
+                       // Is it disabled?
+                       disabled: function() {
+                               return !list;
+                       },
+                       // Lock the list in its current state
+                       lock: function() {
+                               stack = undefined;
+                               if ( !memory ) {
+                                       self.disable();
+                               }
+                               return this;
+                       },
+                       // Is it locked?
+                       locked: function() {
+                               return !stack;
+                       },
+                       // Call all callbacks with the given context and arguments
+                       fireWith: function( context, args ) {
+                               if ( list && ( !fired || stack ) ) {
+                                       args = args || [];
+                                       args = [ context, args.slice ? args.slice() : args ];
+                                       if ( firing ) {
+                                               stack.push( args );
+                                       } else {
+                                               fire( args );
+                                       }
+                               }
+                               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 action = tuple[ 0 ],
+                                                               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()
+                                                                               .done( newDefer.resolve )
+                                                                               .fail( newDefer.reject )
+                                                                               .progress( newDefer.notify );
+                                                               } else {
+                                                                       newDefer[ action + "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 = core_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 ? core_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()
+                                               .done( updateFunc( i, resolveContexts, resolveValues ) )
+                                               .fail( deferred.reject )
+                                               .progress( updateFunc( i, progressContexts, progressValues ) );
+                               } else {
+                                       --remaining;
+                               }
+                       }
+               }
+
+               // if we're not waiting on anything, resolve the master
+               if ( !remaining ) {
+                       deferred.resolveWith( resolveContexts, resolveValues );
+               }
+
+               return deferred.promise();
+       }
+});
+jQuery.support = (function( support ) {
+       var input = document.createElement("input"),
+               fragment = document.createDocumentFragment(),
+               div = document.createElement("div"),
+               select = document.createElement("select"),
+               opt = select.appendChild( document.createElement("option") );
+
+       // Finish early in limited environments
+       if ( !input.type ) {
+               return support;
+       }
+
+       input.type = "checkbox";
+
+       // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
+       // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
+       support.checkOn = input.value !== "";
+
+       // Must access the parent to make an option select properly
+       // Support: IE9, IE10
+       support.optSelected = opt.selected;
+
+       // Will be defined later
+       support.reliableMarginRight = true;
+       support.boxSizingReliable = true;
+       support.pixelPosition = false;
+
+       // Make sure checked status is properly cloned
+       // Support: IE9, IE10
+       input.checked = true;
+       support.noCloneChecked = input.cloneNode( true ).checked;
+
+       // 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;
+
+       // Check if an input maintains its value after becoming a radio
+       // Support: IE9, IE10
+       input = document.createElement("input");
+       input.value = "t";
+       input.type = "radio";
+       support.radioValue = input.value === "t";
+
+       // #11217 - WebKit loses check when the name is after the checked attribute
+       input.setAttribute( "checked", "t" );
+       input.setAttribute( "name", "t" );
+
+       fragment.appendChild( input );
+
+       // Support: Safari 5.1, Android 4.x, Android 2.3
+       // old WebKit doesn't clone checked state correctly in fragments
+       support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+       // Support: Firefox, Chrome, Safari
+       // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
+       support.focusinBubbles = "onfocusin" in window;
+
+       div.style.backgroundClip = "content-box";
+       div.cloneNode( true ).style.backgroundClip = "";
+       support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+       // Run tests that need a body at doc ready
+       jQuery(function() {
+               var container, marginDiv,
+                       // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
+                       divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",
+                       body = document.getElementsByTagName("body")[ 0 ];
+
+               if ( !body ) {
+                       // Return for frameset docs that don't have a body
+                       return;
+               }
+
+               container = document.createElement("div");
+               container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
+
+               // Check box-sizing and margin behavior.
+               body.appendChild( container ).appendChild( div );
+               div.innerHTML = "";
+               // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
+               div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%";
+
+               // Workaround failing boxSizing test due to offsetWidth returning wrong value
+               // with some non-1 values of body zoom, ticket #13543
+               jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
+                       support.boxSizing = div.offsetWidth === 4;
+               });
+
+               // Use window.getComputedStyle because jsdom on node.js will break without it.
+               if ( window.getComputedStyle ) {
+                       support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
+                       support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
+
+                       // Support: Android 2.3
+                       // Check if 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
+                       marginDiv = div.appendChild( document.createElement("div") );
+                       marginDiv.style.cssText = div.style.cssText = divReset;
+                       marginDiv.style.marginRight = marginDiv.style.width = "0";
+                       div.style.width = "1px";
+
+                       support.reliableMarginRight =
+                               !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
+               }
+
+               body.removeChild( container );
+       });
+
+       return support;
+})( {} );
+
+/*
+       Implementation Summary
+
+       1. Enforce API surface and semantic compatibility with 1.9.x branch
+       2. Improve the module's maintainability by reducing the storage
+               paths to a single mechanism.
+       3. Use the same single mechanism to support "private" and "user" data.
+       4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
+       5. Avoid exposing implementation details on user objects (eg. expando properties)
+       6. Provide a clear path for implementation upgrade to WeakMap in 2014
+*/
+var data_user, data_priv,
+       rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
+       rmultiDash = /([A-Z])/g;
+
+function Data() {
+       // Support: Android < 4,
+       // Old WebKit does not have Object.preventExtensions/freeze method,
+       // return new empty object instead with no [[set]] accessor
+       Object.defineProperty( this.cache = {}, 0, {
+               get: function() {
+                       return {};
+               }
+       });
+
+       this.expando = jQuery.expando + Math.random();
+}
+
+Data.uid = 1;
+
+Data.accepts = function( owner ) {
+       // Accepts only:
+       //  - Node
+       //    - Node.ELEMENT_NODE
+       //    - Node.DOCUMENT_NODE
+       //  - Object
+       //    - Any
+       return owner.nodeType ?
+               owner.nodeType === 1 || owner.nodeType === 9 : true;
+};
+
+Data.prototype = {
+       key: function( owner ) {
+               // We can accept data for non-element nodes in modern browsers,
+               // but we should not, see #8335.
+               // Always return the key for a frozen object.
+               if ( !Data.accepts( owner ) ) {
+                       return 0;
+               }
+
+               var descriptor = {},
+                       // Check if the owner object already has a cache key
+                       unlock = owner[ this.expando ];
+
+               // If not, create one
+               if ( !unlock ) {
+                       unlock = Data.uid++;
+
+                       // Secure it in a non-enumerable, non-writable property
+                       try {
+                               descriptor[ this.expando ] = { value: unlock };
+                               Object.defineProperties( owner, descriptor );
+
+                       // Support: Android < 4
+                       // Fallback to a less secure definition
+                       } catch ( e ) {
+                               descriptor[ this.expando ] = unlock;
+                               jQuery.extend( owner, descriptor );
+                       }
+               }
+
+               // Ensure the cache object
+               if ( !this.cache[ unlock ] ) {
+                       this.cache[ unlock ] = {};
+               }
+
+               return unlock;
+       },
+       set: function( owner, data, value ) {
+               var prop,
+                       // There may be an unlock assigned to this node,
+                       // if there is no entry for this "owner", create one inline
+                       // and set the unlock as though an owner entry had always existed
+                       unlock = this.key( owner ),
+                       cache = this.cache[ unlock ];
+
+               // Handle: [ owner, key, value ] args
+               if ( typeof data === "string" ) {
+                       cache[ data ] = value;
+
+               // Handle: [ owner, { properties } ] args
+               } else {
+                       // Fresh assignments by object are shallow copied
+                       if ( jQuery.isEmptyObject( cache ) ) {
+                               jQuery.extend( this.cache[ unlock ], data );
+                       // Otherwise, copy the properties one-by-one to the cache object
+                       } else {
+                               for ( prop in data ) {
+                                       cache[ prop ] = data[ prop ];
+                               }
+                       }
+               }
+               return cache;
+       },
+       get: function( owner, key ) {
+               // Either a valid cache is found, or will be created.
+               // New caches will be created and the unlock returned,
+               // allowing direct access to the newly created
+               // empty data object. A valid owner object must be provided.
+               var cache = this.cache[ this.key( owner ) ];
+
+               return key === undefined ?
+                       cache : cache[ key ];
+       },
+       access: function( owner, key, value ) {
+               var stored;
+               // In cases where either:
+               //
+               //   1. No key was specified
+               //   2. A string key was specified, but no value provided
+               //
+               // Take the "read" path and allow the get method to determine
+               // which value to return, respectively either:
+               //
+               //   1. The entire cache object
+               //   2. The data stored at the key
+               //
+               if ( key === undefined ||
+                               ((key && typeof key === "string") && value === undefined) ) {
+
+                       stored = this.get( owner, key );
+
+                       return stored !== undefined ?
+                               stored : this.get( owner, jQuery.camelCase(key) );
+               }
+
+               // [*]When the key is not a string, or both a key and value
+               // are specified, set or extend (existing objects) with either:
+               //
+               //   1. An object of properties
+               //   2. A key and value
+               //
+               this.set( owner, key, value );
+
+               // Since the "set" path can have two possible entry points
+               // return the expected data based on which path was taken[*]
+               return value !== undefined ? value : key;
+       },
+       remove: function( owner, key ) {
+               var i, name, camel,
+                       unlock = this.key( owner ),
+                       cache = this.cache[ unlock ];
+
+               if ( key === undefined ) {
+                       this.cache[ unlock ] = {};
+
+               } else {
+                       // Support array or space separated string of keys
+                       if ( jQuery.isArray( key ) ) {
+                               // 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 = key.concat( key.map( jQuery.camelCase ) );
+                       } else {
+                               camel = jQuery.camelCase( key );
+                               // Try the string as a key before any manipulation
+                               if ( key in cache ) {
+                                       name = [ key, camel ];
+                               } else {
+                                       // If a key with the spaces exists, use it.
+                                       // Otherwise, create an array by matching non-whitespace
+                                       name = camel;
+                                       name = name in cache ?
+                                               [ name ] : ( name.match( core_rnotwhite ) || [] );
+                               }
+                       }
+
+                       i = name.length;
+                       while ( i-- ) {
+                               delete cache[ name[ i ] ];
+                       }
+               }
+       },
+       hasData: function( owner ) {
+               return !jQuery.isEmptyObject(
+                       this.cache[ owner[ this.expando ] ] || {}
+               );
+       },
+       discard: function( owner ) {
+               if ( owner[ this.expando ] ) {
+                       delete this.cache[ owner[ this.expando ] ];
+               }
+       }
+};
+
+// These may be used throughout the jQuery core codebase
+data_user = new Data();
+data_priv = new Data();
+
+
+jQuery.extend({
+       acceptData: Data.accepts,
+
+       hasData: function( elem ) {
+               return data_user.hasData( elem ) || data_priv.hasData( elem );
+       },
+
+       data: function( elem, name, data ) {
+               return data_user.access( elem, name, data );
+       },
+
+       removeData: function( elem, name ) {
+               data_user.remove( elem, name );
+       },
+
+       // TODO: Now that all calls to _data and _removeData have been replaced
+       // with direct calls to data_priv methods, these can be deprecated.
+       _data: function( elem, name, data ) {
+               return data_priv.access( elem, name, data );
+       },
+
+       _removeData: function( elem, name ) {
+               data_priv.remove( elem, name );
+       }
+});
+
+jQuery.fn.extend({
+       data: function( key, value ) {
+               var attrs, name,
+                       elem = this[ 0 ],
+                       i = 0,
+                       data = null;
+
+               // Gets all values
+               if ( key === undefined ) {
+                       if ( this.length ) {
+                               data = data_user.get( elem );
+
+                               if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
+                                       attrs = elem.attributes;
+                                       for ( ; i < attrs.length; i++ ) {
+                                               name = attrs[ i ].name;
+
+                                               if ( name.indexOf( "data-" ) === 0 ) {
+                                                       name = jQuery.camelCase( name.slice(5) );
+                                                       dataAttr( elem, name, data[ name ] );
+                                               }
+                                       }
+                                       data_priv.set( elem, "hasDataAttrs", true );
+                               }
+                       }
+
+                       return data;
+               }
+
+               // Sets multiple values
+               if ( typeof key === "object" ) {
+                       return this.each(function() {
+                               data_user.set( this, key );
+                       });
+               }
+
+               return jQuery.access( this, function( value ) {
+                       var data,
+                               camelKey = jQuery.camelCase( key );
+
+                       // The calling jQuery object (element matches) is not empty
+                       // (and therefore has an element appears at this[ 0 ]) and the
+                       // `value` parameter was not undefined. An empty jQuery object
+                       // will result in `undefined` for elem = this[ 0 ] which will
+                       // throw an exception if an attempt to read a data cache is made.
+                       if ( elem && value === undefined ) {
+                               // Attempt to get data from the cache
+                               // with the key as-is
+                               data = data_user.get( elem, key );
+                               if ( data !== undefined ) {
+                                       return data;
+                               }
+
+                               // Attempt to get data from the cache
+                               // with the key camelized
+                               data = data_user.get( elem, camelKey );
+                               if ( data !== undefined ) {
+                                       return data;
+                               }
+
+                               // Attempt to "discover" the data in
+                               // HTML5 custom data-* attrs
+                               data = dataAttr( elem, camelKey, undefined );
+                               if ( data !== undefined ) {
+                                       return data;
+                               }
+
+                               // We tried really hard, but the data doesn't exist.
+                               return;
+                       }
+
+                       // Set the data...
+                       this.each(function() {
+                               // First, attempt to store a copy or reference of any
+                               // data that might've been store with a camelCased key.
+                               var data = data_user.get( this, camelKey );
+
+                               // For HTML5 data-* attribute interop, we have to
+                               // store property names with dashes in a camelCase form.
+                               // This might not apply to all properties...*
+                               data_user.set( this, camelKey, value );
+
+                               // *... In the case of properties that might _actually_
+                               // have dashes, we need to also store a copy of that
+                               // unchanged property.
+                               if ( key.indexOf("-") !== -1 && data !== undefined ) {
+                                       data_user.set( this, key, value );
+                               }
+                       });
+               }, null, value, arguments.length > 1, null, true );
+       },
+
+       removeData: function( key ) {
+               return this.each(function() {
+                       data_user.remove( this, key );
+               });
+       }
+});
+
+function dataAttr( elem, key, data ) {
+       var name;
+
+       // If nothing was found internally, try to fetch any
+       // data from the HTML5 data-* attribute
+       if ( data === undefined && elem.nodeType === 1 ) {
+               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 ) ? JSON.parse( data ) :
+                                       data;
+                       } catch( e ) {}
+
+                       // Make sure we set the data so it isn't changed later
+                       data_user.set( elem, key, data );
+               } else {
+                       data = undefined;
+               }
+       }
+       return data;
+}
+jQuery.extend({
+       queue: function( elem, type, data ) {
+               var queue;
+
+               if ( elem ) {
+                       type = ( type || "fx" ) + "queue";
+                       queue = data_priv.get( elem, type );
+
+                       // Speed up dequeue by getting out quickly if this is just a lookup
+                       if ( data ) {
+                               if ( !queue || jQuery.isArray( data ) ) {
+                                       queue = data_priv.access( 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 data_priv.get( elem, key ) || data_priv.access( elem, key, {
+                       empty: jQuery.Callbacks("once memory").add(function() {
+                               data_priv.remove( elem, [ type + "queue", 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 );
+               });
+       },
+       // Based off of the plugin by Clint Helfers, with permission.
+       // http://blindsignals.com/index.php/2009/07/jquery-delay/
+       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 = setTimeout( next, time );
+                       hooks.stop = function() {
+                               clearTimeout( timeout );
+                       };
+               });
+       },
+       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 = data_priv.get( elements[ i ], type + "queueHooks" );
+                       if ( tmp && tmp.empty ) {
+                               count++;
+                               tmp.empty.add( resolve );
+                       }
+               }
+               resolve();
+               return defer.promise( obj );
+       }
+});
+var nodeHook, boolHook,
+       rclass = /[\t\r\n\f]/g,
+       rreturn = /\r/g,
+       rfocusable = /^(?:input|select|textarea|button)$/i;
+
+jQuery.fn.extend({
+       attr: function( name, value ) {
+               return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
+       },
+
+       removeAttr: function( name ) {
+               return this.each(function() {
+                       jQuery.removeAttr( this, name );
+               });
+       },
+
+       prop: function( name, value ) {
+               return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
+       },
+
+       removeProp: function( name ) {
+               return this.each(function() {
+                       delete this[ jQuery.propFix[ name ] || name ];
+               });
+       },
+
+       addClass: function( value ) {
+               var classes, elem, cur, clazz, j,
+                       i = 0,
+                       len = this.length,
+                       proceed = typeof value === "string" && value;
+
+               if ( jQuery.isFunction( value ) ) {
+                       return this.each(function( j ) {
+                               jQuery( this ).addClass( value.call( this, j, this.className ) );
+                       });
+               }
+
+               if ( proceed ) {
+                       // The disjunction here is for better compressibility (see removeClass)
+                       classes = ( value || "" ).match( core_rnotwhite ) || [];
+
+                       for ( ; i < len; i++ ) {
+                               elem = this[ i ];
+                               cur = elem.nodeType === 1 && ( elem.className ?
+                                       ( " " + elem.className + " " ).replace( rclass, " " ) :
+                                       " "
+                               );
+
+                               if ( cur ) {
+                                       j = 0;
+                                       while ( (clazz = classes[j++]) ) {
+                                               if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
+                                                       cur += clazz + " ";
+                                               }
+                                       }
+                                       elem.className = jQuery.trim( cur );
+
+                               }
+                       }
+               }
+
+               return this;
+       },
+
+       removeClass: function( value ) {
+               var classes, elem, cur, clazz, j,
+                       i = 0,
+                       len = this.length,
+                       proceed = arguments.length === 0 || typeof value === "string" && value;
+
+               if ( jQuery.isFunction( value ) ) {
+                       return this.each(function( j ) {
+                               jQuery( this ).removeClass( value.call( this, j, this.className ) );
+                       });
+               }
+               if ( proceed ) {
+                       classes = ( value || "" ).match( core_rnotwhite ) || [];
+
+                       for ( ; i < len; i++ ) {
+                               elem = this[ i ];
+                               // This expression is here for better compressibility (see addClass)
+                               cur = elem.nodeType === 1 && ( elem.className ?
+                                       ( " " + elem.className + " " ).replace( rclass, " " ) :
+                                       ""
+                               );
+
+                               if ( cur ) {
+                                       j = 0;
+                                       while ( (clazz = classes[j++]) ) {
+                                               // Remove *all* instances
+                                               while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
+                                                       cur = cur.replace( " " + clazz + " ", " " );
+                                               }
+                                       }
+                                       elem.className = value ? jQuery.trim( cur ) : "";
+                               }
+                       }
+               }
+
+               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, this.className, stateVal), stateVal );
+                       });
+               }
+
+               return this.each(function() {
+                       if ( type === "string" ) {
+                               // toggle individual class names
+                               var className,
+                                       i = 0,
+                                       self = jQuery( this ),
+                                       classNames = value.match( core_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 ( type === core_strundefined || type === "boolean" ) {
+                               if ( this.className ) {
+                                       // store className if set
+                                       data_priv.set( this, "__className__", this.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.
+                               this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
+                       }
+               });
+       },
+
+       hasClass: function( selector ) {
+               var className = " " + selector + " ",
+                       i = 0,
+                       l = this.length;
+               for ( ; i < l; i++ ) {
+                       if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
+                               return true;
+                       }
+               }
+
+               return false;
+       },
+
+       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 ) {
+                               // attributes.value is undefined in Blackberry 4.7 but
+                               // uses .value. See #6932
+                               var val = elem.attributes.value;
+                               return !val || val.specified ? elem.value : elem.text;
+                       }
+               },
+               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 ];
+
+                                       // IE6-9 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
+                                                       ( jQuery.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 ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
+                                               optionSet = true;
+                                       }
+                               }
+
+                               // force browsers to behave consistently when non-matching value is set
+                               if ( !optionSet ) {
+                                       elem.selectedIndex = -1;
+                               }
+                               return values;
+                       }
+               }
+       },
+
+       attr: function( elem, name, value ) {
+               var hooks, ret,
+                       nType = elem.nodeType;
+
+               // don't get/set attributes on text, comment and attribute nodes
+               if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+                       return;
+               }
+
+               // Fallback to prop when attributes are not supported
+               if ( typeof elem.getAttribute === core_strundefined ) {
+                       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 );
+
+                       } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+                               return ret;
+
+                       } else {
+                               elem.setAttribute( name, value + "" );
+                               return value;
+                       }
+
+               } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+                       return ret;
+
+               } else {
+                       ret = jQuery.find.attr( elem, name );
+
+                       // Non-existent attributes return null, we normalize to undefined
+                       return ret == null ?
+                               undefined :
+                               ret;
+               }
+       },
+
+       removeAttr: function( elem, value ) {
+               var name, propName,
+                       i = 0,
+                       attrNames = value && value.match( core_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
+                                       elem[ propName ] = false;
+                               }
+
+                               elem.removeAttribute( name );
+                       }
+               }
+       },
+
+       attrHooks: {
+               type: {
+                       set: function( elem, value ) {
+                               if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
+                                       // Setting the type on a radio button after the value resets the value in IE6-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;
+                               }
+                       }
+               }
+       },
+
+       propFix: {
+               "for": "htmlFor",
+               "class": "className"
+       },
+
+       prop: function( elem, name, value ) {
+               var ret, hooks, notxml,
+                       nType = elem.nodeType;
+
+               // don't get/set properties on text, comment and attribute nodes
+               if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+                       return;
+               }
+
+               notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+               if ( notxml ) {
+                       // Fix name and attach hooks
+                       name = jQuery.propFix[ name ] || name;
+                       hooks = jQuery.propHooks[ name ];
+               }
+
+               if ( value !== undefined ) {
+                       return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
+                               ret :
+                               ( elem[ name ] = value );
+
+               } else {
+                       return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
+                               ret :
+                               elem[ name ];
+               }
+       },
+
+       propHooks: {
+               tabIndex: {
+                       get: function( elem ) {
+                               return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
+                                       elem.tabIndex :
+                                       -1;
+                       }
+               }
+       }
+});
+
+// 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 {
+                       elem.setAttribute( name, name );
+               }
+               return name;
+       }
+};
+jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
+       var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
+
+       jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) {
+               var fn = jQuery.expr.attrHandle[ name ],
+                       ret = isXML ?
+                               undefined :
+                               /* jshint eqeqeq: false */
+                               // Temporarily disable this handler to check existence
+                               (jQuery.expr.attrHandle[ name ] = undefined) !=
+                                       getter( elem, name, isXML ) ?
+
+                                       name.toLowerCase() :
+                                       null;
+
+               // Restore handler
+               jQuery.expr.attrHandle[ name ] = fn;
+
+               return ret;
+       };
+});
+
+// Support: IE9+
+// Selectedness for an option in an optgroup can be inaccurate
+if ( !jQuery.support.optSelected ) {
+       jQuery.propHooks.selected = {
+               get: function( elem ) {
+                       var parent = elem.parentNode;
+                       if ( parent && parent.parentNode ) {
+                               parent.parentNode.selectedIndex;
+                       }
+                       return null;
+               }
+       };
+}
+
+jQuery.each([
+       "tabIndex",
+       "readOnly",
+       "maxLength",
+       "cellSpacing",
+       "cellPadding",
+       "rowSpan",
+       "colSpan",
+       "useMap",
+       "frameBorder",
+       "contentEditable"
+], function() {
+       jQuery.propFix[ this.toLowerCase() ] = this;
+});
+
+// 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 ) >= 0 );
+                       }
+               }
+       };
+       if ( !jQuery.support.checkOn ) {
+               jQuery.valHooks[ this ].get = function( elem ) {
+                       // Support: Webkit
+                       // "" is returned instead of "on" if a value isn't specified
+                       return elem.getAttribute("value") === null ? "on" : elem.value;
+               };
+       }
+});
+var rkeyEvent = /^key/,
+       rmouseEvent = /^(?:mouse|contextmenu)|click/,
+       rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+       rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
+
+function returnTrue() {
+       return true;
+}
+
+function returnFalse() {
+       return false;
+}
+
+function safeActiveElement() {
+       try {
+               return document.activeElement;
+       } catch ( err ) { }
+}
+
+/*
+ * 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 handleObjIn, eventHandle, tmp,
+                       events, t, handleObj,
+                       special, handlers, type, namespaces, origType,
+                       elemData = data_priv.get( 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 !== core_strundefined && (!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( core_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 if the special events handler returns false
+                               if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+                                       if ( elem.addEventListener ) {
+                                               elem.addEventListener( type, eventHandle, false );
+                                       }
+                               }
+                       }
+
+                       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, origCount, tmp,
+                       events, t, handleObj,
+                       special, handlers, type, namespaces, origType,
+                       elemData = data_priv.hasData( elem ) && data_priv.get( elem );
+
+               if ( !elemData || !(events = elemData.events) ) {
+                       return;
+               }
+
+               // Once for each type.namespace in types; type may be omitted
+               types = ( types || "" ).match( core_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;
+                       data_priv.remove( elem, "events" );
+               }
+       },
+
+       trigger: function( event, data, elem, onlyHandlers ) {
+
+               var i, cur, tmp, bubbleType, ontype, handle, special,
+                       eventPath = [ elem || document ],
+                       type = core_hasOwn.call( event, "type" ) ? event.type : event,
+                       namespaces = core_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(".") >= 0 ) {
+                       // 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.namespace_re = 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
+                       if ( handle ) {
+                               handle.apply( cur, data );
+                       }
+
+                       // Native handler
+                       handle = ontype && cur[ ontype ];
+                       if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === 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) &&
+                               jQuery.acceptData( elem ) ) {
+
+                               // Call a native DOM method on the target with the same name name as the event.
+                               // Don't do default actions on window, that's where global variables be (#6170)
+                               if ( ontype && jQuery.isFunction( 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;
+                                       elem[ type ]();
+                                       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 = core_slice.call( arguments ),
+                       handlers = ( data_priv.get( 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.namespace_re || event.namespace_re.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;
+
+               // Find delegate handlers
+               // Black-hole SVG <use> instance trees (#13180)
+               // Avoid non-left-click bubbling in Firefox (#3861)
+               if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
+
+                       for ( ; cur !== this; cur = cur.parentNode || this ) {
+
+                               // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
+                               if ( 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 ) >= 0 :
+                                                               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;
+       },
+
+       // Includes some event props shared by KeyEvent and MouseEvent
+       props: "altKey bubbles cancelable ctrlKey currentTarget 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
+               filter: function( event, original ) {
+                       var eventDoc, doc, body,
+                               button = original.button;
+
+                       // 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 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;
+               }
+       },
+
+       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: Cordova 2.5 (WebKit) (#13255)
+               // All events should have a target; Cordova deviceready doesn't
+               if ( !event.target ) {
+                       event.target = document;
+               }
+
+               // Support: Safari 6.0+, Chrome < 28
+               // Target should not be a text node (#504, #13143)
+               if ( event.target.nodeType === 3 ) {
+                       event.target = event.target.parentNode;
+               }
+
+               return fixHook.filter? fixHook.filter( event, originalEvent ) : 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 ) {
+                                       this.focus();
+                                       return false;
+                               }
+                       },
+                       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 ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
+                                       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.returnValue = event.result;
+                               }
+                       }
+               }
+       },
+
+       simulate: function( type, elem, event, bubble ) {
+               // Piggyback on a donor event to simulate a different one.
+               // Fake originalEvent to avoid donor's stopPropagation, but if the
+               // simulated event prevents default then we do the same on the donor.
+               var e = jQuery.extend(
+                       new jQuery.Event(),
+                       event,
+                       {
+                               type: type,
+                               isSimulated: true,
+                               originalEvent: {}
+                       }
+               );
+               if ( bubble ) {
+                       jQuery.event.trigger( e, null, elem );
+               } else {
+                       jQuery.event.dispatch.call( elem, e );
+               }
+               if ( e.isDefaultPrevented() ) {
+                       event.preventDefault();
+               }
+       }
+};
+
+jQuery.removeEvent = function( elem, type, handle ) {
+       if ( elem.removeEventListener ) {
+               elem.removeEventListener( type, handle, false );
+       }
+};
+
+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.getPreventDefault && src.getPreventDefault() ) ? 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 = {
+       isDefaultPrevented: returnFalse,
+       isPropagationStopped: returnFalse,
+       isImmediatePropagationStopped: returnFalse,
+
+       preventDefault: function() {
+               var e = this.originalEvent;
+
+               this.isDefaultPrevented = returnTrue;
+
+               if ( e && e.preventDefault ) {
+                       e.preventDefault();
+               }
+       },
+       stopPropagation: function() {
+               var e = this.originalEvent;
+
+               this.isPropagationStopped = returnTrue;
+
+               if ( e && e.stopPropagation ) {
+                       e.stopPropagation();
+               }
+       },
+       stopImmediatePropagation: function() {
+               this.isImmediatePropagationStopped = returnTrue;
+               this.stopPropagation();
+       }
+};
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+// Support: Chrome 15+
+jQuery.each({
+       mouseenter: "mouseover",
+       mouseleave: "mouseout"
+}, 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 mousenter/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;
+               }
+       };
+});
+
+// Create "bubbling" focus and blur events
+// Support: Firefox, Chrome, Safari
+if ( !jQuery.support.focusinBubbles ) {
+       jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+               // Attach a single capturing handler while someone wants focusin/focusout
+               var attaches = 0,
+                       handler = function( event ) {
+                               jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
+                       };
+
+               jQuery.event.special[ fix ] = {
+                       setup: function() {
+                               if ( attaches++ === 0 ) {
+                                       document.addEventListener( orig, handler, true );
+                               }
+                       },
+                       teardown: function() {
+                               if ( --attaches === 0 ) {
+                                       document.removeEventListener( orig, handler, true );
+                               }
+                       }
+               };
+       });
+}
+
+jQuery.fn.extend({
+
+       on: function( types, selector, data, fn, /*INTERNAL*/ 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 ) {
+                               this.on( type, selector, data, types[ type ], one );
+                       }
+                       return this;
+               }
+
+               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 this;
+               }
+
+               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 this.each( function() {
+                       jQuery.event.add( this, types, fn, data, selector );
+               });
+       },
+       one: function( types, selector, data, fn ) {
+               return this.on( 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 isSimple = /^.[^:#\[\.,]*$/,
+       rparentsprev = /^(?:parents|prev(?:Until|All))/,
+       rneedsContext = jQuery.expr.match.needsContext,
+       // 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({
+       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;
+       },
+
+       has: function( target ) {
+               var targets = jQuery( target, this ),
+                       l = targets.length;
+
+               return this.filter(function() {
+                       var i = 0;
+                       for ( ; i < l; i++ ) {
+                               if ( jQuery.contains( this, targets[i] ) ) {
+                                       return true;
+                               }
+                       }
+               });
+       },
+
+       not: function( selector ) {
+               return this.pushStack( winnow(this, selector || [], true) );
+       },
+
+       filter: function( selector ) {
+               return this.pushStack( winnow(this, selector || [], false) );
+       },
+
+       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;
+       },
+
+       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)) ) {
+
+                                       cur = matched.push( cur );
+                                       break;
+                               }
+                       }
+               }
+
+               return this.pushStack( matched.length > 1 ? jQuery.unique( 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 core_indexOf.call( jQuery( elem ), this[ 0 ] );
+               }
+
+               // Locate the position of the desired element
+               return core_indexOf.call( this,
+
+                       // If it receives a jQuery object, the first element is used
+                       elem.jquery ? elem[ 0 ] : elem
+               );
+       },
+
+       add: function( selector, context ) {
+               var set = typeof selector === "string" ?
+                               jQuery( selector, context ) :
+                               jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
+                       all = jQuery.merge( this.get(), set );
+
+               return this.pushStack( jQuery.unique(all) );
+       },
+
+       addBack: function( selector ) {
+               return this.add( selector == null ?
+                       this.prevObject : this.prevObject.filter(selector)
+               );
+       }
+});
+
+function sibling( cur, dir ) {
+       while ( (cur = cur[dir]) && 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 jQuery.dir( elem, "parentNode" );
+       },
+       parentsUntil: function( elem, i, until ) {
+               return jQuery.dir( elem, "parentNode", until );
+       },
+       next: function( elem ) {
+               return sibling( elem, "nextSibling" );
+       },
+       prev: function( elem ) {
+               return sibling( elem, "previousSibling" );
+       },
+       nextAll: function( elem ) {
+               return jQuery.dir( elem, "nextSibling" );
+       },
+       prevAll: function( elem ) {
+               return jQuery.dir( elem, "previousSibling" );
+       },
+       nextUntil: function( elem, i, until ) {
+               return jQuery.dir( elem, "nextSibling", until );
+       },
+       prevUntil: function( elem, i, until ) {
+               return jQuery.dir( elem, "previousSibling", until );
+       },
+       siblings: function( elem ) {
+               return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
+       },
+       children: function( elem ) {
+               return jQuery.sibling( elem.firstChild );
+       },
+       contents: function( elem ) {
+               return elem.contentDocument || jQuery.merge( [], elem.childNodes );
+       }
+}, function( name, fn ) {
+       jQuery.fn[ name ] = function( until, selector ) {
+               var matched = jQuery.map( this, fn, until );
+
+               if ( name.slice( -5 ) !== "Until" ) {
+                       selector = until;
+               }
+
+               if ( selector && typeof selector === "string" ) {
+                       matched = jQuery.filter( selector, matched );
+               }
+
+               if ( this.length > 1 ) {
+                       // Remove duplicates
+                       if ( !guaranteedUnique[ name ] ) {
+                               jQuery.unique( matched );
+                       }
+
+                       // Reverse order for parents* and prev-derivatives
+                       if ( rparentsprev.test( name ) ) {
+                               matched.reverse();
+                       }
+               }
+
+               return this.pushStack( matched );
+       };
+});
+
+jQuery.extend({
+       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;
+                       }));
+       },
+
+       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;
+       },
+
+       sibling: function( n, elem ) {
+               var matched = [];
+
+               for ( ; n; n = n.nextSibling ) {
+                       if ( n.nodeType === 1 && n !== elem ) {
+                               matched.push( n );
+                       }
+               }
+
+               return matched;
+       }
+});
+
+// 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 ( isSimple.test( qualifier ) ) {
+                       return jQuery.filter( qualifier, elements, not );
+               }
+
+               qualifier = jQuery.filter( qualifier, elements );
+       }
+
+       return jQuery.grep( elements, function( elem ) {
+               return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
+       });
+}
+var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
+       rtagName = /<([\w:]+)/,
+       rhtml = /<|&#?\w+;/,
+       rnoInnerhtml = /<(?:script|style|link)/i,
+       manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
+       // checked="checked" or checked
+       rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+       rscriptType = /^$|\/(?:java|ecma)script/i,
+       rscriptTypeMasked = /^true\/(.*)/,
+       rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
+
+       // We have to close these tags to support XHTML (#13200)
+       wrapMap = {
+
+               // Support: IE 9
+               option: [ 1, "<select multiple='multiple'>", "</select>" ],
+
+               thead: [ 1, "<table>", "</table>" ],
+               col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
+               tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+               td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+
+               _default: [ 0, "", "" ]
+       };
+
+// Support: IE 9
+wrapMap.optgroup = wrapMap.option;
+
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+jQuery.fn.extend({
+       text: function( value ) {
+               return jQuery.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 this.domManip( arguments, function( elem ) {
+                       if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+                               var target = manipulationTarget( this, elem );
+                               target.appendChild( elem );
+                       }
+               });
+       },
+
+       prepend: function() {
+               return this.domManip( 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 this.domManip( arguments, function( elem ) {
+                       if ( this.parentNode ) {
+                               this.parentNode.insertBefore( elem, this );
+                       }
+               });
+       },
+
+       after: function() {
+               return this.domManip( arguments, function( elem ) {
+                       if ( this.parentNode ) {
+                               this.parentNode.insertBefore( elem, this.nextSibling );
+                       }
+               });
+       },
+
+       // keepData is for internal use only--do not document
+       remove: function( selector, keepData ) {
+               var elem,
+                       elems = selector ? jQuery.filter( selector, this ) : this,
+                       i = 0;
+
+               for ( ; (elem = elems[i]) != null; i++ ) {
+                       if ( !keepData && elem.nodeType === 1 ) {
+                               jQuery.cleanData( getAll( elem ) );
+                       }
+
+                       if ( elem.parentNode ) {
+                               if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
+                                       setGlobalEval( getAll( elem, "script" ) );
+                               }
+                               elem.parentNode.removeChild( elem );
+                       }
+               }
+
+               return this;
+       },
+
+       empty: function() {
+               var elem,
+                       i = 0;
+
+               for ( ; (elem = this[i]) != null; i++ ) {
+                       if ( elem.nodeType === 1 ) {
+
+                               // Prevent memory leaks
+                               jQuery.cleanData( getAll( elem, false ) );
+
+                               // Remove any remaining nodes
+                               elem.textContent = "";
+                       }
+               }
+
+               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 jQuery.access( this, function( value ) {
+                       var elem = this[ 0 ] || {},
+                               i = 0,
+                               l = this.length;
+
+                       if ( value === undefined && elem.nodeType === 1 ) {
+                               return elem.innerHTML;
+                       }
+
+                       // See if we can take a shortcut and just use innerHTML
+                       if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
+                               !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
+
+                               value = value.replace( rxhtmlTag, "<$1></$2>" );
+
+                               try {
+                                       for ( ; i < l; i++ ) {
+                                               elem = this[ i ] || {};
+
+                                               // Remove element nodes and prevent memory leaks
+                                               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
+                       // Snapshot the DOM in case .domManip sweeps something relevant into its fragment
+                       args = jQuery.map( this, function( elem ) {
+                               return [ elem.nextSibling, elem.parentNode ];
+                       }),
+                       i = 0;
+
+               // Make the changes, replacing each context element with the new content
+               this.domManip( arguments, function( elem ) {
+                       var next = args[ i++ ],
+                               parent = args[ i++ ];
+
+                       if ( parent ) {
+                               // Don't use the snapshot next if it has moved (#13810)
+                               if ( next && next.parentNode !== parent ) {
+                                       next = this.nextSibling;
+                               }
+                               jQuery( this ).remove();
+                               parent.insertBefore( elem, next );
+                       }
+               // Allow new content to include elements from the context set
+               }, true );
+
+               // Force removal if there was no new content (e.g., from empty arguments)
+               return i ? this : this.remove();
+       },
+
+       detach: function( selector ) {
+               return this.remove( selector, true );
+       },
+
+       domManip: function( args, callback, allowIntersection ) {
+
+               // Flatten any nested arrays
+               args = core_concat.apply( [], args );
+
+               var fragment, first, scripts, hasScripts, node, doc,
+                       i = 0,
+                       l = this.length,
+                       set = this,
+                       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" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
+                       return this.each(function( index ) {
+                               var self = set.eq( index );
+                               if ( isFunction ) {
+                                       args[ 0 ] = value.call( this, index, self.html() );
+                               }
+                               self.domManip( args, callback, allowIntersection );
+                       });
+               }
+
+               if ( l ) {
+                       fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
+                       first = fragment.firstChild;
+
+                       if ( fragment.childNodes.length === 1 ) {
+                               fragment = first;
+                       }
+
+                       if ( first ) {
+                               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: QtWebKit
+                                                       // jQuery.merge because core_push.apply(_, arraylike) throws
+                                                       jQuery.merge( scripts, getAll( node, "script" ) );
+                                               }
+                                       }
+
+                                       callback.call( this[ 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 || "" ) &&
+                                                       !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
+
+                                                       if ( node.src ) {
+                                                               // Hope ajax is available...
+                                                               jQuery._evalUrl( node.src );
+                                                       } else {
+                                                               jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               return this;
+       }
+});
+
+jQuery.each({
+       appendTo: "append",
+       prependTo: "prepend",
+       insertBefore: "before",
+       insertAfter: "after",
+       replaceAll: "replaceWith"
+}, function( name, original ) {
+       jQuery.fn[ name ] = function( selector ) {
+               var elems,
+                       ret = [],
+                       insert = jQuery( selector ),
+                       last = insert.length - 1,
+                       i = 0;
+
+               for ( ; i <= last; i++ ) {
+                       elems = i === last ? this : this.clone( true );
+                       jQuery( insert[ i ] )[ original ]( elems );
+
+                       // Support: QtWebKit
+                       // .get() because core_push.apply(_, arraylike) throws
+                       core_push.apply( ret, elems.get() );
+               }
+
+               return this.pushStack( ret );
+       };
+});
+
+jQuery.extend({
+       clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+               var i, l, srcElements, destElements,
+                       clone = elem.cloneNode( true ),
+                       inPage = jQuery.contains( elem.ownerDocument, elem );
+
+               // Support: IE >= 9
+               // Fix Cloning issues
+               if ( !jQuery.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 );
+
+                       for ( i = 0, l = srcElements.length; i < l; i++ ) {
+                               fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) {
+                                       cloneCopyEvent( srcElements[ i ], destElements[ i ] );
+                               }
+                       } else {
+                               cloneCopyEvent( elem, clone );
+                       }
+               }
+
+               // Preserve script evaluation history
+               destElements = getAll( clone, "script" );
+               if ( destElements.length > 0 ) {
+                       setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
+               }
+
+               // Return the cloned set
+               return clone;
+       },
+
+       buildFragment: function( elems, context, scripts, selection ) {
+               var elem, tmp, tag, wrap, contains, j,
+                       i = 0,
+                       l = elems.length,
+                       fragment = context.createDocumentFragment(),
+                       nodes = [];
+
+               for ( ; i < l; i++ ) {
+                       elem = elems[ i ];
+
+                       if ( elem || elem === 0 ) {
+
+                               // Add nodes directly
+                               if ( jQuery.type( elem ) === "object" ) {
+                                       // Support: QtWebKit
+                                       // jQuery.merge because core_push.apply(_, arraylike) throws
+                                       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 || fragment.appendChild( context.createElement("div") );
+
+                                       // Deserialize a standard representation
+                                       tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase();
+                                       wrap = wrapMap[ tag ] || wrapMap._default;
+                                       tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
+
+                                       // Descend through wrappers to the right content
+                                       j = wrap[ 0 ];
+                                       while ( j-- ) {
+                                               tmp = tmp.lastChild;
+                                       }
+
+                                       // Support: QtWebKit
+                                       // jQuery.merge because core_push.apply(_, arraylike) throws
+                                       jQuery.merge( nodes, tmp.childNodes );
+
+                                       // Remember the top-level container
+                                       tmp = fragment.firstChild;
+
+                                       // Fixes #12346
+                                       // Support: Webkit, IE
+                                       tmp.textContent = "";
+                               }
+                       }
+               }
+
+               // Remove wrapper from fragment
+               fragment.textContent = "";
+
+               i = 0;
+               while ( (elem = nodes[ i++ ]) ) {
+
+                       // #4087 - If origin and destination elements are the same, and this is
+                       // that element, do not do anything
+                       if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
+                               continue;
+                       }
+
+                       contains = jQuery.contains( elem.ownerDocument, elem );
+
+                       // Append to fragment
+                       tmp = getAll( fragment.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 );
+                                       }
+                               }
+                       }
+               }
+
+               return fragment;
+       },
+
+       cleanData: function( elems ) {
+               var data, elem, events, type, key, j,
+                       special = jQuery.event.special,
+                       i = 0;
+
+               for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
+                       if ( Data.accepts( elem ) ) {
+                               key = elem[ data_priv.expando ];
+
+                               if ( key && (data = data_priv.cache[ key ]) ) {
+                                       events = Object.keys( data.events || {} );
+                                       if ( events.length ) {
+                                               for ( j = 0; (type = events[j]) !== undefined; j++ ) {
+                                                       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 );
+                                                       }
+                                               }
+                                       }
+                                       if ( data_priv.cache[ key ] ) {
+                                               // Discard any remaining `private` data
+                                               delete data_priv.cache[ key ];
+                                       }
+                               }
+                       }
+                       // Discard any remaining `user` data
+                       delete data_user.cache[ elem[ data_user.expando ] ];
+               }
+       },
+
+       _evalUrl: function( url ) {
+               return jQuery.ajax({
+                       url: url,
+                       type: "GET",
+                       dataType: "script",
+                       async: false,
+                       global: false,
+                       "throws": true
+               });
+       }
+});
+
+// Support: 1.x compatibility
+// Manipulating tables requires a tbody
+function manipulationTarget( elem, content ) {
+       return jQuery.nodeName( elem, "table" ) &&
+               jQuery.nodeName( content.nodeType === 1 ? 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 = (elem.getAttribute("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;
+}
+
+// Mark scripts as having already been evaluated
+function setGlobalEval( elems, refElements ) {
+       var l = elems.length,
+               i = 0;
+
+       for ( ; i < l; i++ ) {
+               data_priv.set(
+                       elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
+               );
+       }
+}
+
+function cloneCopyEvent( src, dest ) {
+       var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
+
+       if ( dest.nodeType !== 1 ) {
+               return;
+       }
+
+       // 1. Copy private data: events, handlers, etc.
+       if ( data_priv.hasData( src ) ) {
+               pdataOld = data_priv.access( src );
+               pdataCur = data_priv.set( dest, pdataOld );
+               events = pdataOld.events;
+
+               if ( events ) {
+                       delete pdataCur.handle;
+                       pdataCur.events = {};
+
+                       for ( type in events ) {
+                               for ( i = 0, l = events[ type ].length; i < l; i++ ) {
+                                       jQuery.event.add( dest, type, events[ type ][ i ] );
+                               }
+                       }
+               }
+       }
+
+       // 2. Copy user data
+       if ( data_user.hasData( src ) ) {
+               udataOld = data_user.access( src );
+               udataCur = jQuery.extend( {}, udataOld );
+
+               data_user.set( dest, udataCur );
+       }
+}
+
+
+function getAll( context, tag ) {
+       var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
+                       context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
+                       [];
+
+       return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
+               jQuery.merge( [ context ], ret ) :
+               ret;
+}
+
+// Support: IE >= 9
+function fixInput( src, dest ) {
+       var nodeName = dest.nodeName.toLowerCase();
+
+       // Fails to persist the checked state of a cloned checkbox or radio button.
+       if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
+               dest.checked = src.checked;
+
+       // Fails to return the selected option to the default selected state when cloning options
+       } else if ( nodeName === "input" || nodeName === "textarea" ) {
+               dest.defaultValue = src.defaultValue;
+       }
+}
+jQuery.fn.extend({
+       wrapAll: function( html ) {
+               var wrap;
+
+               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
+                       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.firstElementChild ) {
+                                       elem = elem.firstElementChild;
+                               }
+
+                               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();
+       }
+});
+var curCSS, iframe,
+       // 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]).+)/,
+       rmargin = /^margin/,
+       rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
+       rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
+       rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
+       elemdisplay = { BODY: "block" },
+
+       cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+       cssNormalTransform = {
+               letterSpacing: 0,
+               fontWeight: 400
+       },
+
+       cssExpand = [ "Top", "Right", "Bottom", "Left" ],
+       cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
+
+// return a css property mapped to a potentially vendor prefixed property
+function vendorPropName( style, name ) {
+
+       // shortcut for names that are not vendor prefixed
+       if ( name in style ) {
+               return name;
+       }
+
+       // check for vendor prefixed names
+       var capName = name.charAt(0).toUpperCase() + name.slice(1),
+               origName = name,
+               i = cssPrefixes.length;
+
+       while ( i-- ) {
+               name = cssPrefixes[ i ] + capName;
+               if ( name in style ) {
+                       return name;
+               }
+       }
+
+       return origName;
+}
+
+function isHidden( 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 );
+}
+
+// NOTE: we've included the "window" in window.getComputedStyle
+// because jsdom on node.js will break without it.
+function getStyles( elem ) {
+       return window.getComputedStyle( elem, null );
+}
+
+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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
+                       }
+               } else {
+
+                       if ( !values[ index ] ) {
+                               hidden = isHidden( elem );
+
+                               if ( display && display !== "none" || !hidden ) {
+                                       data_priv.set( 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;
+}
+
+jQuery.fn.extend({
+       css: function( name, value ) {
+               return jQuery.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();
+                       }
+               });
+       }
+});
+
+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: {
+               "columnCount": true,
+               "fillOpacity": 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": "cssFloat"
+       },
+
+       // 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( style, 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 relative number strings (+= or -=) to relative numbers. #7345
+                       if ( type === "string" && (ret = rrelNum.exec( value )) ) {
+                               value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
+                               // Fixes bug #9237
+                               type = "number";
+                       }
+
+                       // Make sure that NaN and null values aren't set. See: #7116
+                       if ( value == null || type === "number" && isNaN( value ) ) {
+                               return;
+                       }
+
+                       // If a number was passed in, add 'px' to the (except for certain CSS properties)
+                       if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+                               value += "px";
+                       }
+
+                       // Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
+                       // but it would mean to define eight (for every problematic property) identical functions
+                       if ( !jQuery.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 ) {
+                               style[ name ] = value;
+                       }
+
+               } 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 val, num, hooks,
+                       origName = jQuery.camelCase( name );
+
+               // Make sure that we're working with the right name
+               name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, 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 || jQuery.isNumeric( num ) ? num || 0 : val;
+               }
+               return val;
+       }
+});
+
+curCSS = function( elem, name, _computed ) {
+       var width, minWidth, maxWidth,
+               computed = _computed || getStyles( elem ),
+
+               // Support: IE9
+               // getPropertyValue is only needed for .css('filter') in IE9, see #12537
+               ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
+               style = elem.style;
+
+       if ( computed ) {
+
+               if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
+                       ret = jQuery.style( elem, name );
+               }
+
+               // Support: Safari 5.1
+               // A tribute to the "awesome hack by Dean Edwards"
+               // 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 ( 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;
+               }
+       }
+
+       return ret;
+};
+
+
+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 = jQuery.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 && ( jQuery.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";
+}
+
+// Try to determine the default display value of an element
+function css_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'/>")
+                               .css( "cssText", "display:block !important" )
+                       ).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;
+                       doc.write("<!doctype html><html><body>");
+                       doc.close();
+
+                       display = actualDisplay( nodeName, doc );
+                       iframe.detach();
+               }
+
+               // Store the correct default display
+               elemdisplay[ nodeName ] = display;
+       }
+
+       return display;
+}
+
+// Called ONLY from within css_defaultDisplay
+function actualDisplay( name, doc ) {
+       var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
+               display = jQuery.css( elem[0], "display" );
+       elem.remove();
+       return display;
+}
+
+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 elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
+                                       jQuery.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,
+                                       jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
+                                       styles
+                               ) : 0
+                       );
+               }
+       };
+});
+
+// These hooks cannot be added until DOM ready because the support test
+// for it is not run until after DOM ready
+jQuery(function() {
+       // Support: Android 2.3
+       if ( !jQuery.support.reliableMarginRight ) {
+               jQuery.cssHooks.marginRight = {
+                       get: function( elem, computed ) {
+                               if ( computed ) {
+                                       // Support: Android 2.3
+                                       // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+                                       // Work around by temporarily setting element display to inline-block
+                                       return jQuery.swap( elem, { "display": "inline-block" },
+                                               curCSS, [ elem, "marginRight" ] );
+                               }
+                       }
+               };
+       }
+
+       // 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
+       if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
+               jQuery.each( [ "top", "left" ], function( i, prop ) {
+                       jQuery.cssHooks[ prop ] = {
+                               get: 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;
+                                       }
+                               }
+                       };
+               });
+       }
+
+});
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+       jQuery.expr.filters.hidden = function( elem ) {
+               // Support: Opera <= 12.12
+               // Opera reports offsetWidths and offsetHeights less than zero on some elements
+               return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
+       };
+
+       jQuery.expr.filters.visible = function( elem ) {
+               return !jQuery.expr.filters.hidden( elem );
+       };
+}
+
+// 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;
+       }
+});
+var r20 = /%20/g,
+       rbracket = /\[\]$/,
+       rCRLF = /\r?\n/g,
+       rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+       rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+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 || !manipulation_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();
+       }
+});
+
+//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, "+" );
+};
+
+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" ? 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 );
+       }
+}
+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 );
+       },
+
+       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 );
+       }
+});
+var
+       // Document location
+       ajaxLocParts,
+       ajaxLocation,
+
+       ajax_nonce = jQuery.now(),
+
+       ajax_rquery = /\?/,
+       rhash = /#.*$/,
+       rts = /([?&])_=[^&]*/,
+       rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
+       // #7653, #8125, #8152: local protocol detection
+       rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
+       rnoContent = /^(?:GET|HEAD)$/,
+       rprotocol = /^\/\//,
+       rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
+
+       // Keep a copy of the old load method
+       _load = jQuery.fn.load,
+
+       /* 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("*");
+
+// #8138, IE may throw an exception when accessing
+// a field from window.location if document.domain has been set
+try {
+       ajaxLocation = location.href;
+} catch( e ) {
+       // Use the href attribute of an A element
+       // since IE will modify it given document.location
+       ajaxLocation = document.createElement( "a" );
+       ajaxLocation.href = "";
+       ajaxLocation = ajaxLocation.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( core_rnotwhite ) || [];
+
+               if ( jQuery.isFunction( func ) ) {
+                       // For each dataType in the dataTypeExpression
+                       while ( (dataType = dataTypes[i++]) ) {
+                               // Prepend if requested
+                               if ( dataType[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 key, deep,
+               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;
+}
+
+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 >= 0 ) {
+               selector = url.slice( off );
+               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
+                       type: type,
+                       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 );
+
+               }).complete( callback && function( jqXHR, status ) {
+                       self.each( callback, 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.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: /xml/,
+                       html: /html/,
+                       json: /json/
+               },
+
+               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 transport,
+                       // URL without anti-cache param
+                       cacheURL,
+                       // Response headers
+                       responseHeadersString,
+                       responseHeaders,
+                       // timeout handle
+                       timeoutTimer,
+                       // Cross-domain detection vars
+                       parts,
+                       // To know if global events are to be dispatched
+                       fireGlobals,
+                       // Loop variable
+                       i,
+                       // 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 (prefilters might expect it)
+               // 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( core_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
+               fireGlobals = 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 += ( ajax_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_=" + ajax_nonce++ ) :
+
+                                       // Otherwise add one to the end
+                                       cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_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 ] );
+                       }
+                       // Timeout
+                       if ( s.async && s.timeout > 0 ) {
+                               timeoutTimer = 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 ) {
+                               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;
+               }
+
+               return jQuery.ajax({
+                       url: url,
+                       type: method,
+                       dataType: type,
+                       data: data,
+                       success: callback
+               });
+       };
+});
+
+/* 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 ct, type, finalDataType, firstDataType,
+               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" ] ) {
+                                               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 };
+}
+// Install script dataType
+jQuery.ajaxSetup({
+       accepts: {
+               script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+       },
+       contents: {
+               script: /(?:java|ecma)script/
+       },
+       converters: {
+               "text script": function( text ) {
+                       jQuery.globalEval( text );
+                       return text;
+               }
+       }
+});
+
+// Handle cache's special case and crossDomain
+jQuery.ajaxPrefilter( "script", function( s ) {
+       if ( s.cache === undefined ) {
+               s.cache = false;
+       }
+       if ( s.crossDomain ) {
+               s.type = "GET";
+       }
+});
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function( s ) {
+       // This transport only deals with cross domain requests
+       if ( s.crossDomain ) {
+               var script, callback;
+               return {
+                       send: function( _, complete ) {
+                               script = jQuery("<script>").prop({
+                                       async: true,
+                                       charset: s.scriptCharset,
+                                       src: s.url
+                               }).on(
+                                       "load error",
+                                       callback = function( evt ) {
+                                               script.remove();
+                                               callback = null;
+                                               if ( evt ) {
+                                                       complete( evt.type === "error" ? 404 : 200, evt.type );
+                                               }
+                                       }
+                               );
+                               document.head.appendChild( script[ 0 ] );
+                       },
+                       abort: function() {
+                               if ( callback ) {
+                                       callback();
+                               }
+                       }
+               };
+       }
+});
+var oldCallbacks = [],
+       rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+       jsonp: "callback",
+       jsonpCallback: function() {
+               var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_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") && 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 += ( ajax_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() {
+                       // Restore preexisting value
+                       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";
+       }
+});
+jQuery.ajaxSettings.xhr = function() {
+       try {
+               return new XMLHttpRequest();
+       } catch( e ) {}
+};
+
+var xhrSupported = jQuery.ajaxSettings.xhr(),
+       xhrSuccessStatus = {
+               // file protocol always yields status code 0, assume 200
+               0: 200,
+               // Support: IE9
+               // #1450: sometimes IE returns 1223 when it should be 204
+               1223: 204
+       },
+       // Support: IE9
+       // We need to keep track of outbound xhr and abort them manually
+       // because IE is not smart enough to do it all by itself
+       xhrId = 0,
+       xhrCallbacks = {};
+
+if ( window.ActiveXObject ) {
+       jQuery( window ).on( "unload", function() {
+               for( var key in xhrCallbacks ) {
+                       xhrCallbacks[ key ]();
+               }
+               xhrCallbacks = undefined;
+       });
+}
+
+jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+jQuery.support.ajax = xhrSupported = !!xhrSupported;
+
+jQuery.ajaxTransport(function( options ) {
+       var callback;
+       // Cross domain only allowed if supported through XMLHttpRequest
+       if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) {
+               return {
+                       send: function( headers, complete ) {
+                               var i, id,
+                                       xhr = options.xhr();
+                               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 ) {
+                                       xhr.setRequestHeader( i, headers[ i ] );
+                               }
+                               // Callback
+                               callback = function( type ) {
+                                       return function() {
+                                               if ( callback ) {
+                                                       delete xhrCallbacks[ id ];
+                                                       callback = xhr.onload = xhr.onerror = null;
+                                                       if ( type === "abort" ) {
+                                                               xhr.abort();
+                                                       } else if ( type === "error" ) {
+                                                               complete(
+                                                                       // file protocol always yields status 0, assume 404
+                                                                       xhr.status || 404,
+                                                                       xhr.statusText
+                                                               );
+                                                       } else {
+                                                               complete(
+                                                                       xhrSuccessStatus[ xhr.status ] || xhr.status,
+                                                                       xhr.statusText,
+                                                                       // Support: IE9
+                                                                       // #11426: When requesting binary data, IE9 will throw an exception
+                                                                       // on any attempt to access responseText
+                                                                       typeof xhr.responseText === "string" ? {
+                                                                               text: xhr.responseText
+                                                                       } : undefined,
+                                                                       xhr.getAllResponseHeaders()
+                                                               );
+                                                       }
+                                               }
+                                       };
+                               };
+                               // Listen to events
+                               xhr.onload = callback();
+                               xhr.onerror = callback("error");
+                               // Create the abort callback
+                               callback = xhrCallbacks[( id = xhrId++ )] = callback("abort");
+                               // 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 );
+                       },
+                       abort: function() {
+                               if ( callback ) {
+                                       callback();
+                               }
+                       }
+               };
+       }
+});
+var fxNow, timerId,
+       rfxtypes = /^(?:toggle|show|hide)$/,
+       rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
+       rrun = /queueHooks$/,
+       animationPrefilters = [ defaultPrefilter ],
+       tweeners = {
+               "*": [function( prop, value ) {
+                       var tween = this.createTween( prop, value ),
+                               target = tween.cur(),
+                               parts = rfxnum.exec( value ),
+                               unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
+
+                               // Starting value computation is required for potential unit mismatches
+                               start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
+                                       rfxnum.exec( jQuery.css( tween.elem, prop ) ),
+                               scale = 1,
+                               maxIterations = 20;
+
+                       if ( start && start[ 3 ] !== unit ) {
+                               // Trust units reported by jQuery.css
+                               unit = unit || start[ 3 ];
+
+                               // Make sure we update the tween properties later on
+                               parts = parts || [];
+
+                               // Iteratively approximate from a nonzero starting point
+                               start = +target || 1;
+
+                               do {
+                                       // If previous iteration zeroed out, double until we get *something*
+                                       // Use a string for doubling factor so we don't accidentally see scale as unchanged below
+                                       scale = scale || ".5";
+
+                                       // Adjust and apply
+                                       start = start / scale;
+                                       jQuery.style( tween.elem, prop, start + unit );
+
+                               // Update scale, tolerating zero or NaN from tween.cur()
+                               // And breaking the loop if scale is unchanged or perfect, or if we've just had enough
+                               } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
+                       }
+
+                       // Update tween properties
+                       if ( parts ) {
+                               start = tween.start = +start || +target || 0;
+                               tween.unit = unit;
+                               // If a +=/-= token was provided, we're doing a relative animation
+                               tween.end = parts[ 1 ] ?
+                                       start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+                                       +parts[ 2 ];
+                       }
+
+                       return tween;
+               }]
+       };
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+       setTimeout(function() {
+               fxNow = undefined;
+       });
+       return ( fxNow = jQuery.now() );
+}
+
+function createTween( value, prop, animation ) {
+       var tween,
+               collection = ( tweeners[ prop ] || [] ).concat( 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 Animation( elem, properties, options ) {
+       var result,
+               stopped,
+               index = 0,
+               length = animationPrefilters.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 ),
+                               // 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: {} }, 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.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 = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
+               if ( 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 );
+}
+
+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;
+               }
+       }
+}
+
+jQuery.Animation = jQuery.extend( Animation, {
+
+       tweener: function( props, callback ) {
+               if ( jQuery.isFunction( props ) ) {
+                       callback = props;
+                       props = [ "*" ];
+               } else {
+                       props = props.split(" ");
+               }
+
+               var prop,
+                       index = 0,
+                       length = props.length;
+
+               for ( ; index < length ; index++ ) {
+                       prop = props[ index ];
+                       tweeners[ prop ] = tweeners[ prop ] || [];
+                       tweeners[ prop ].unshift( callback );
+               }
+       },
+
+       prefilter: function( callback, prepend ) {
+               if ( prepend ) {
+                       animationPrefilters.unshift( callback );
+               } else {
+                       animationPrefilters.push( callback );
+               }
+       }
+});
+
+function defaultPrefilter( elem, props, opts ) {
+       /* jshint validthis: true */
+       var prop, value, toggle, tween, hooks, oldfire,
+               anim = this,
+               orig = {},
+               style = elem.style,
+               hidden = elem.nodeType && isHidden( elem ),
+               dataShow = data_priv.get( 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 IE9-10 do 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
+               if ( jQuery.css( elem, "display" ) === "inline" &&
+                               jQuery.css( elem, "float" ) === "none" ) {
+
+                       style.display = "inline-block";
+               }
+       }
+
+       if ( opts.overflow ) {
+               style.overflow = "hidden";
+               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 );
+               }
+       }
+
+       if ( !jQuery.isEmptyObject( orig ) ) {
+               if ( dataShow ) {
+                       if ( "hidden" in dataShow ) {
+                               hidden = dataShow.hidden;
+                       }
+               } else {
+                       dataShow = data_priv.access( 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;
+
+                       data_priv.remove( 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;
+                               }
+                       }
+               }
+       }
+}
+
+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 || "swing";
+               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;
+
+                       if ( tween.elem[ tween.prop ] != null &&
+                               (!tween.elem.style || 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.style && ( 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: IE9
+// 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.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 );
+       };
+});
+
+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 || data_priv.get( 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 = data_priv.get( 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 = data_priv.get( 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;
+               });
+       }
+});
+
+// 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;
+}
+
+// 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.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.easing = {
+       linear: function( p ) {
+               return p;
+       },
+       swing: function( p ) {
+               return 0.5 - Math.cos( p*Math.PI ) / 2;
+       }
+};
+
+jQuery.timers = [];
+jQuery.fx = Tween.prototype.init;
+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 ) {
+       if ( timer() && jQuery.timers.push( timer ) ) {
+               jQuery.fx.start();
+       }
+};
+
+jQuery.fx.interval = 13;
+
+jQuery.fx.start = function() {
+       if ( !timerId ) {
+               timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
+       }
+};
+
+jQuery.fx.stop = function() {
+       clearInterval( timerId );
+       timerId = null;
+};
+
+jQuery.fx.speeds = {
+       slow: 600,
+       fast: 200,
+       // Default speed
+       _default: 400
+};
+
+// Back Compat <1.8 extension point
+jQuery.fx.step = {};
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+       jQuery.expr.filters.animated = function( elem ) {
+               return jQuery.grep(jQuery.timers, function( fn ) {
+                       return elem === fn.elem;
+               }).length;
+       };
+}
+jQuery.fn.offset = function( options ) {
+       if ( arguments.length ) {
+               return options === undefined ?
+                       this :
+                       this.each(function( i ) {
+                               jQuery.offset.setOffset( this, options, i );
+                       });
+       }
+
+       var docElem, win,
+               elem = this[ 0 ],
+               box = { top: 0, left: 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 !== core_strundefined ) {
+               box = elem.getBoundingClientRect();
+       }
+       win = getWindow( doc );
+       return {
+               top: box.top + win.pageYOffset - docElem.clientTop,
+               left: box.left + win.pageXOffset - docElem.clientLeft
+       };
+};
+
+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" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -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 ) ) {
+                       options = options.call( elem, i, 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({
+
+       position: function() {
+               if ( !this[ 0 ] ) {
+                       return;
+               }
+
+               var offsetParent, offset,
+                       elem = this[ 0 ],
+                       parentOffset = { top: 0, left: 0 };
+
+               // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's 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
+               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 || docElem;
+
+                       while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
+                               offsetParent = offsetParent.offsetParent;
+                       }
+
+                       return offsetParent || docElem;
+               });
+       }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
+       var top = "pageYOffset" === prop;
+
+       jQuery.fn[ method ] = function( val ) {
+               return jQuery.access( this, function( elem, method, val ) {
+                       var win = getWindow( elem );
+
+                       if ( val === undefined ) {
+                               return win ? win[ prop ] : elem[ method ];
+                       }
+
+                       if ( win ) {
+                               win.scrollTo(
+                                       !top ? val : window.pageXOffset,
+                                       top ? val : window.pageYOffset
+                               );
+
+                       } else {
+                               elem[ method ] = val;
+                       }
+               }, method, val, arguments.length, null );
+       };
+});
+
+function getWindow( elem ) {
+       return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
+}
+// 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 jQuery.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
+                                       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 );
+               };
+       });
+});
+// Limit scope pollution from any deprecated API
+// (function() {
+
+// The number of elements contained in the matched element set
+jQuery.fn.size = function() {
+       return this.length;
+};
+
+jQuery.fn.andSelf = jQuery.fn.addBack;
+
+// })();
+if ( typeof module === "object" && module && typeof module.exports === "object" ) {
+       // Expose jQuery as module.exports in loaders that implement the Node
+       // module pattern (including browserify). Do not create the global, since
+       // the user will be storing it themselves locally, and globals are frowned
+       // upon in the Node module world.
+       module.exports = jQuery;
+} else {
+       // 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.
+       if ( typeof define === "function" && define.amd ) {
+               define( "jquery", [], function () { return jQuery; } );
+       }
+}
+
+// If there is a window object, that at least has a document property,
+// define jQuery and $ identifiers
+if ( typeof window === "object" && typeof window.document === "object" ) {
+       window.jQuery = window.$ = jQuery;
+}
+
+})( window );
+
+/**
+ * @license
+ * Lo-Dash 2.2.1 (Custom Build) <http://lodash.com/>
+ * Build: `lodash modern -o ./dist/lodash.js`
+ * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
+ * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license <http://lodash.com/license>
+ */
+;(function() {
+
+  /** Used as a safe reference for `undefined` in pre ES5 environments */
+  var undefined;
+
+  /** Used to pool arrays and objects used internally */
+  var arrayPool = [],
+      objectPool = [];
+
+  /** Used to generate unique IDs */
+  var idCounter = 0;
+
+  /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
+  var keyPrefix = +new Date + '';
+
+  /** Used as the size when optimizations are enabled for large arrays */
+  var largeArraySize = 75;
+
+  /** Used as the max size of the `arrayPool` and `objectPool` */
+  var maxPoolSize = 40;
+
+  /** Used to detect and test whitespace */
+  var whitespace = (
+    // whitespace
+    ' \t\x0B\f\xA0\ufeff' +
+
+    // line terminators
+    '\n\r\u2028\u2029' +
+
+    // unicode category "Zs" space separators
+    '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
+  );
+
+  /** Used to match empty string literals in compiled template source */
+  var reEmptyStringLeading = /\b__p \+= '';/g,
+      reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
+      reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
+
+  /**
+   * Used to match ES6 template delimiters
+   * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6
+   */
+  var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
+
+  /** Used to match regexp flags from their coerced string values */
+  var reFlags = /\w*$/;
+
+  /** Used to detected named functions */
+  var reFuncName = /^function[ \n\r\t]+\w/;
+
+  /** Used to match "interpolate" template delimiters */
+  var reInterpolate = /<%=([\s\S]+?)%>/g;
+
+  /** Used to match leading whitespace and zeros to be removed */
+  var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
+
+  /** Used to ensure capturing order of template delimiters */
+  var reNoMatch = /($^)/;
+
+  /** Used to detect functions containing a `this` reference */
+  var reThis = /\bthis\b/;
+
+  /** Used to match unescaped characters in compiled string literals */
+  var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
+
+  /** Used to assign default `context` object properties */
+  var contextProps = [
+    'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object',
+    'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
+    'parseInt', 'setImmediate', 'setTimeout'
+  ];
+
+  /** Used to make template sourceURLs easier to identify */
+  var templateCounter = 0;
+
+  /** `Object#toString` result shortcuts */
+  var argsClass = '[object Arguments]',
+      arrayClass = '[object Array]',
+      boolClass = '[object Boolean]',
+      dateClass = '[object Date]',
+      funcClass = '[object Function]',
+      numberClass = '[object Number]',
+      objectClass = '[object Object]',
+      regexpClass = '[object RegExp]',
+      stringClass = '[object String]';
+
+  /** Used to identify object classifications that `_.clone` supports */
+  var cloneableClasses = {};
+  cloneableClasses[funcClass] = false;
+  cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
+  cloneableClasses[boolClass] = cloneableClasses[dateClass] =
+  cloneableClasses[numberClass] = cloneableClasses[objectClass] =
+  cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
+
+  /** Used as an internal `_.debounce` options object */
+  var debounceOptions = {
+    'leading': false,
+    'maxWait': 0,
+    'trailing': false
+  };
+
+  /** Used as the property descriptor for `__bindData__` */
+  var descriptor = {
+    'configurable': false,
+    'enumerable': false,
+    'value': null,
+    'writable': false
+  };
+
+  /** Used to determine if values are of the language type Object */
+  var objectTypes = {
+    'boolean': false,
+    'function': true,
+    'object': true,
+    'number': false,
+    'string': false,
+    'undefined': false
+  };
+
+  /** Used to escape characters for inclusion in compiled string literals */
+  var stringEscapes = {
+    '\\': '\\',
+    "'": "'",
+    '\n': 'n',
+    '\r': 'r',
+    '\t': 't',
+    '\u2028': 'u2028',
+    '\u2029': 'u2029'
+  };
+
+  /** Used as a reference to the global object */
+  var root = (objectTypes[typeof window] && window) || this;
+
+  /** Detect free variable `exports` */
+  var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
+
+  /** Detect free variable `module` */
+  var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
+
+  /** Detect the popular CommonJS extension `module.exports` */
+  var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
+
+  /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
+  var freeGlobal = objectTypes[typeof global] && global;
+  if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
+    root = freeGlobal;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * The base implementation of `_.indexOf` without support for binary searches
+   * or `fromIndex` constraints.
+   *
+   * @private
+   * @param {Array} array The array to search.
+   * @param {*} value The value to search for.
+   * @param {number} [fromIndex=0] The index to search from.
+   * @returns {number} Returns the index of the matched value or `-1`.
+   */
+  function baseIndexOf(array, value, fromIndex) {
+    var index = (fromIndex || 0) - 1,
+        length = array ? array.length : 0;
+
+    while (++index < length) {
+      if (array[index] === value) {
+        return index;
+      }
+    }
+    return -1;
+  }
+
+  /**
+   * An implementation of `_.contains` for cache objects that mimics the return
+   * signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
+   *
+   * @private
+   * @param {Object} cache The cache object to inspect.
+   * @param {*} value The value to search for.
+   * @returns {number} Returns `0` if `value` is found, else `-1`.
+   */
+  function cacheIndexOf(cache, value) {
+    var type = typeof value;
+    cache = cache.cache;
+
+    if (type == 'boolean' || value == null) {
+      return cache[value] ? 0 : -1;
+    }
+    if (type != 'number' && type != 'string') {
+      type = 'object';
+    }
+    var key = type == 'number' ? value : keyPrefix + value;
+    cache = (cache = cache[type]) && cache[key];
+
+    return type == 'object'
+      ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
+      : (cache ? 0 : -1);
+  }
+
+  /**
+   * Adds a given value to the corresponding cache object.
+   *
+   * @private
+   * @param {*} value The value to add to the cache.
+   */
+  function cachePush(value) {
+    var cache = this.cache,
+        type = typeof value;
+
+    if (type == 'boolean' || value == null) {
+      cache[value] = true;
+    } else {
+      if (type != 'number' && type != 'string') {
+        type = 'object';
+      }
+      var key = type == 'number' ? value : keyPrefix + value,
+          typeCache = cache[type] || (cache[type] = {});
+
+      if (type == 'object') {
+        (typeCache[key] || (typeCache[key] = [])).push(value);
+      } else {
+        typeCache[key] = true;
+      }
+    }
+  }
+
+  /**
+   * Used by `_.max` and `_.min` as the default callback when a given
+   * collection is a string value.
+   *
+   * @private
+   * @param {string} value The character to inspect.
+   * @returns {number} Returns the code unit of given character.
+   */
+  function charAtCallback(value) {
+    return value.charCodeAt(0);
+  }
+
+  /**
+   * Used by `sortBy` to compare transformed `collection` elements, stable sorting
+   * them in ascending order.
+   *
+   * @private
+   * @param {Object} a The object to compare to `b`.
+   * @param {Object} b The object to compare to `a`.
+   * @returns {number} Returns the sort order indicator of `1` or `-1`.
+   */
+  function compareAscending(a, b) {
+    var ac = a.criteria,
+        bc = b.criteria;
+
+    // ensure a stable sort in V8 and other engines
+    // http://code.google.com/p/v8/issues/detail?id=90
+    if (ac !== bc) {
+      if (ac > bc || typeof ac == 'undefined') {
+        return 1;
+      }
+      if (ac < bc || typeof bc == 'undefined') {
+        return -1;
+      }
+    }
+    // The JS engine embedded in Adobe applications like InDesign has a buggy
+    // `Array#sort` implementation that causes it, under certain circumstances,
+    // to return the same value for `a` and `b`.
+    // See https://github.com/jashkenas/underscore/pull/1247
+    return a.index - b.index;
+  }
+
+  /**
+   * Creates a cache object to optimize linear searches of large arrays.
+   *
+   * @private
+   * @param {Array} [array=[]] The array to search.
+   * @returns {null|Object} Returns the cache object or `null` if caching should not be used.
+   */
+  function createCache(array) {
+    var index = -1,
+        length = array.length,
+        first = array[0],
+        mid = array[(length / 2) | 0],
+        last = array[length - 1];
+
+    if (first && typeof first == 'object' &&
+        mid && typeof mid == 'object' && last && typeof last == 'object') {
+      return false;
+    }
+    var cache = getObject();
+    cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
+
+    var result = getObject();
+    result.array = array;
+    result.cache = cache;
+    result.push = cachePush;
+
+    while (++index < length) {
+      result.push(array[index]);
+    }
+    return result;
+  }
+
+  /**
+   * Used by `template` to escape characters for inclusion in compiled
+   * string literals.
+   *
+   * @private
+   * @param {string} match The matched character to escape.
+   * @returns {string} Returns the escaped character.
+   */
+  function escapeStringChar(match) {
+    return '\\' + stringEscapes[match];
+  }
+
+  /**
+   * Gets an array from the array pool or creates a new one if the pool is empty.
+   *
+   * @private
+   * @returns {Array} The array from the pool.
+   */
+  function getArray() {
+    return arrayPool.pop() || [];
+  }
+
+  /**
+   * Gets an object from the object pool or creates a new one if the pool is empty.
+   *
+   * @private
+   * @returns {Object} The object from the pool.
+   */
+  function getObject() {
+    return objectPool.pop() || {
+      'array': null,
+      'cache': null,
+      'criteria': null,
+      'false': false,
+      'index': 0,
+      'null': false,
+      'number': null,
+      'object': null,
+      'push': null,
+      'string': null,
+      'true': false,
+      'undefined': false,
+      'value': null
+    };
+  }
+
+  /**
+   * A no-operation function.
+   *
+   * @private
+   */
+  function noop() {
+    // no operation performed
+  }
+
+  /**
+   * Releases the given array back to the array pool.
+   *
+   * @private
+   * @param {Array} [array] The array to release.
+   */
+  function releaseArray(array) {
+    array.length = 0;
+    if (arrayPool.length < maxPoolSize) {
+      arrayPool.push(array);
+    }
+  }
+
+  /**
+   * Releases the given object back to the object pool.
+   *
+   * @private
+   * @param {Object} [object] The object to release.
+   */
+  function releaseObject(object) {
+    var cache = object.cache;
+    if (cache) {
+      releaseObject(cache);
+    }
+    object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
+    if (objectPool.length < maxPoolSize) {
+      objectPool.push(object);
+    }
+  }
+
+  /**
+   * Slices the `collection` from the `start` index up to, but not including,
+   * the `end` index.
+   *
+   * Note: This function is used instead of `Array#slice` to support node lists
+   * in IE < 9 and to ensure dense arrays are returned.
+   *
+   * @private
+   * @param {Array|Object|string} collection The collection to slice.
+   * @param {number} start The start index.
+   * @param {number} end The end index.
+   * @returns {Array} Returns the new array.
+   */
+  function slice(array, start, end) {
+    start || (start = 0);
+    if (typeof end == 'undefined') {
+      end = array ? array.length : 0;
+    }
+    var index = -1,
+        length = end - start || 0,
+        result = Array(length < 0 ? 0 : length);
+
+    while (++index < length) {
+      result[index] = array[start + index];
+    }
+    return result;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  /**
+   * Create a new `lodash` function using the given context object.
+   *
+   * @static
+   * @memberOf _
+   * @category Utilities
+   * @param {Object} [context=root] The context object.
+   * @returns {Function} Returns the `lodash` function.
+   */
+  function runInContext(context) {
+    // Avoid issues with some ES3 environments that attempt to use values, named
+    // after built-in constructors like `Object`, for the creation of literals.
+    // ES5 clears this up by stating that literals must use built-in constructors.
+    // See http://es5.github.io/#x11.1.5.
+    context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
+
+    /** Native constructor references */
+    var Array = context.Array,
+        Boolean = context.Boolean,
+        Date = context.Date,
+        Function = context.Function,
+        Math = context.Math,
+        Number = context.Number,
+        Object = context.Object,
+        RegExp = context.RegExp,
+        String = context.String,
+        TypeError = context.TypeError;
+
+    /**
+     * Used for `Array` method references.
+     *
+     * Normally `Array.prototype` would suffice, however, using an array literal
+     * avoids issues in Narwhal.
+     */
+    var arrayRef = [];
+
+    /** Used for native method references */
+    var objectProto = Object.prototype;
+
+    /** Used to restore the original `_` reference in `noConflict` */
+    var oldDash = context._;
+
+    /** Used to detect if a method is native */
+    var reNative = RegExp('^' +
+      String(objectProto.valueOf)
+        .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+        .replace(/valueOf|for [^\]]+/g, '.+?') + '$'
+    );
+
+    /** Native method shortcuts */
+    var ceil = Math.ceil,
+        clearTimeout = context.clearTimeout,
+        floor = Math.floor,
+        fnToString = Function.prototype.toString,
+        getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
+        hasOwnProperty = objectProto.hasOwnProperty,
+        now = reNative.test(now = Date.now) && now || function() { return +new Date; },
+        push = arrayRef.push,
+        setImmediate = context.setImmediate,
+        setTimeout = context.setTimeout,
+        splice = arrayRef.splice,
+        toString = objectProto.toString,
+        unshift = arrayRef.unshift;
+
+    var defineProperty = (function() {
+      try {
+        var o = {},
+            func = reNative.test(func = Object.defineProperty) && func,
+            result = func(o, o, o) && func;
+      } catch(e) { }
+      return result;
+    }());
+
+    /* Native method shortcuts for methods with the same name as other `lodash` methods */
+    var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind,
+        nativeCreate = reNative.test(nativeCreate = Object.create) && nativeCreate,
+        nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
+        nativeIsFinite = context.isFinite,
+        nativeIsNaN = context.isNaN,
+        nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
+        nativeMax = Math.max,
+        nativeMin = Math.min,
+        nativeParseInt = context.parseInt,
+        nativeRandom = Math.random,
+        nativeSlice = arrayRef.slice;
+
+    /** Detect various environments */
+    var isIeOpera = reNative.test(context.attachEvent),
+        isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera);
+
+    /** Used to lookup a built-in constructor by [[Class]] */
+    var ctorByClass = {};
+    ctorByClass[arrayClass] = Array;
+    ctorByClass[boolClass] = Boolean;
+    ctorByClass[dateClass] = Date;
+    ctorByClass[funcClass] = Function;
+    ctorByClass[objectClass] = Object;
+    ctorByClass[numberClass] = Number;
+    ctorByClass[regexpClass] = RegExp;
+    ctorByClass[stringClass] = String;
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates a `lodash` object which wraps the given value to enable intuitive
+     * method chaining.
+     *
+     * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
+     * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
+     * and `unshift`
+     *
+     * Chaining is supported in custom builds as long as the `value` method is
+     * implicitly or explicitly included in the build.
+     *
+     * The chainable wrapper functions are:
+     * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
+     * `compose`, `concat`, `countBy`, `createCallback`, `curry`, `debounce`,
+     * `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`,
+     * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`,
+     * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`,
+     * `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, `once`, `pairs`,
+     * `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, `range`, `reject`,
+     * `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`,
+     * `tap`, `throttle`, `times`, `toArray`, `transform`, `union`, `uniq`, `unshift`,
+     * `unzip`, `values`, `where`, `without`, `wrap`, and `zip`
+     *
+     * The non-chainable wrapper functions are:
+     * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
+     * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
+     * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
+     * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
+     * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
+     * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
+     * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
+     * `template`, `unescape`, `uniqueId`, and `value`
+     *
+     * The wrapper functions `first` and `last` return wrapped values when `n` is
+     * provided, otherwise they return unwrapped values.
+     *
+     * Explicit chaining can be enabled by using the `_.chain` method.
+     *
+     * @name _
+     * @constructor
+     * @category Chaining
+     * @param {*} value The value to wrap in a `lodash` instance.
+     * @returns {Object} Returns a `lodash` instance.
+     * @example
+     *
+     * var wrapped = _([1, 2, 3]);
+     *
+     * // returns an unwrapped value
+     * wrapped.reduce(function(sum, num) {
+     *   return sum + num;
+     * });
+     * // => 6
+     *
+     * // returns a wrapped value
+     * var squares = wrapped.map(function(num) {
+     *   return num * num;
+     * });
+     *
+     * _.isArray(squares);
+     * // => false
+     *
+     * _.isArray(squares.value());
+     * // => true
+     */
+    function lodash(value) {
+      // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
+      return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
+       ? value
+       : new lodashWrapper(value);
+    }
+
+    /**
+     * A fast path for creating `lodash` wrapper objects.
+     *
+     * @private
+     * @param {*} value The value to wrap in a `lodash` instance.
+     * @param {boolean} chainAll A flag to enable chaining for all methods
+     * @returns {Object} Returns a `lodash` instance.
+     */
+    function lodashWrapper(value, chainAll) {
+      this.__chain__ = !!chainAll;
+      this.__wrapped__ = value;
+    }
+    // ensure `new lodashWrapper` is an instance of `lodash`
+    lodashWrapper.prototype = lodash.prototype;
+
+    /**
+     * An object used to flag environments features.
+     *
+     * @static
+     * @memberOf _
+     * @type Object
+     */
+    var support = lodash.support = {};
+
+    /**
+     * Detect if `Function#bind` exists and is inferred to be fast (all but V8).
+     *
+     * @memberOf _.support
+     * @type boolean
+     */
+    support.fastBind = nativeBind && !isV8;
+
+    /**
+     * Detect if functions can be decompiled by `Function#toString`
+     * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
+     *
+     * @memberOf _.support
+     * @type boolean
+     */
+    support.funcDecomp = !reNative.test(context.WinRTError) && reThis.test(runInContext);
+
+    /**
+     * Detect if `Function#name` is supported (all but IE).
+     *
+     * @memberOf _.support
+     * @type boolean
+     */
+    support.funcNames = typeof Function.name == 'string';
+
+    /**
+     * By default, the template delimiters used by Lo-Dash are similar to those in
+     * embedded Ruby (ERB). Change the following template settings to use alternative
+     * delimiters.
+     *
+     * @static
+     * @memberOf _
+     * @type Object
+     */
+    lodash.templateSettings = {
+
+      /**
+       * Used to detect `data` property values to be HTML-escaped.
+       *
+       * @memberOf _.templateSettings
+       * @type RegExp
+       */
+      'escape': /<%-([\s\S]+?)%>/g,
+
+      /**
+       * Used to detect code to be evaluated.
+       *
+       * @memberOf _.templateSettings
+       * @type RegExp
+       */
+      'evaluate': /<%([\s\S]+?)%>/g,
+
+      /**
+       * Used to detect `data` property values to inject.
+       *
+       * @memberOf _.templateSettings
+       * @type RegExp
+       */
+      'interpolate': reInterpolate,
+
+      /**
+       * Used to reference the data object in the template text.
+       *
+       * @memberOf _.templateSettings
+       * @type string
+       */
+      'variable': '',
+
+      /**
+       * Used to import variables into the compiled template.
+       *
+       * @memberOf _.templateSettings
+       * @type Object
+       */
+      'imports': {
+
+        /**
+         * A reference to the `lodash` function.
+         *
+         * @memberOf _.templateSettings.imports
+         * @type Function
+         */
+        '_': lodash
+      }
+    };
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * The base implementation of `_.clone` without argument juggling or support
+     * for `thisArg` binding.
+     *
+     * @private
+     * @param {*} value The value to clone.
+     * @param {boolean} [deep=false] Specify a deep clone.
+     * @param {Function} [callback] The function to customize cloning values.
+     * @param {Array} [stackA=[]] Tracks traversed source objects.
+     * @param {Array} [stackB=[]] Associates clones with source counterparts.
+     * @returns {*} Returns the cloned value.
+     */
+    function baseClone(value, deep, callback, stackA, stackB) {
+      if (callback) {
+        var result = callback(value);
+        if (typeof result != 'undefined') {
+          return result;
+        }
+      }
+      // inspect [[Class]]
+      var isObj = isObject(value);
+      if (isObj) {
+        var className = toString.call(value);
+        if (!cloneableClasses[className]) {
+          return value;
+        }
+        var ctor = ctorByClass[className];
+        switch (className) {
+          case boolClass:
+          case dateClass:
+            return new ctor(+value);
+
+          case numberClass:
+          case stringClass:
+            return new ctor(value);
+
+          case regexpClass:
+            result = ctor(value.source, reFlags.exec(value));
+            result.lastIndex = value.lastIndex;
+            return result;
+        }
+      } else {
+        return value;
+      }
+      var isArr = isArray(value);
+      if (deep) {
+        // check for circular references and return corresponding clone
+        var initedStack = !stackA;
+        stackA || (stackA = getArray());
+        stackB || (stackB = getArray());
+
+        var length = stackA.length;
+        while (length--) {
+          if (stackA[length] == value) {
+            return stackB[length];
+          }
+        }
+        result = isArr ? ctor(value.length) : {};
+      }
+      else {
+        result = isArr ? slice(value) : assign({}, value);
+      }
+      // add array properties assigned by `RegExp#exec`
+      if (isArr) {
+        if (hasOwnProperty.call(value, 'index')) {
+          result.index = value.index;
+        }
+        if (hasOwnProperty.call(value, 'input')) {
+          result.input = value.input;
+        }
+      }
+      // exit for shallow clone
+      if (!deep) {
+        return result;
+      }
+      // add the source value to the stack of traversed objects
+      // and associate it with its clone
+      stackA.push(value);
+      stackB.push(result);
+
+      // recursively populate clone (susceptible to call stack limits)
+      (isArr ? forEach : forOwn)(value, function(objValue, key) {
+        result[key] = baseClone(objValue, deep, callback, stackA, stackB);
+      });
+
+      if (initedStack) {
+        releaseArray(stackA);
+        releaseArray(stackB);
+      }
+      return result;
+    }
+
+    /**
+     * The base implementation of `_.createCallback` without support for creating
+     * "_.pluck" or "_.where" style callbacks.
+     *
+     * @private
+     * @param {*} [func=identity] The value to convert to a callback.
+     * @param {*} [thisArg] The `this` binding of the created callback.
+     * @param {number} [argCount] The number of arguments the callback accepts.
+     * @returns {Function} Returns a callback function.
+     */
+    function baseCreateCallback(func, thisArg, argCount) {
+      if (typeof func != 'function') {
+        return identity;
+      }
+      // exit early if there is no `thisArg`
+      if (typeof thisArg == 'undefined') {
+        return func;
+      }
+      var bindData = func.__bindData__ || (support.funcNames && !func.name);
+      if (typeof bindData == 'undefined') {
+        var source = reThis && fnToString.call(func);
+        if (!support.funcNames && source && !reFuncName.test(source)) {
+          bindData = true;
+        }
+        if (support.funcNames || !bindData) {
+          // checks if `func` references the `this` keyword and stores the result
+          bindData = !support.funcDecomp || reThis.test(source);
+          setBindData(func, bindData);
+        }
+      }
+      // exit early if there are no `this` references or `func` is bound
+      if (bindData !== true && (bindData && bindData[1] & 1)) {
+        return func;
+      }
+      switch (argCount) {
+        case 1: return function(value) {
+          return func.call(thisArg, value);
+        };
+        case 2: return function(a, b) {
+          return func.call(thisArg, a, b);
+        };
+        case 3: return function(value, index, collection) {
+          return func.call(thisArg, value, index, collection);
+        };
+        case 4: return function(accumulator, value, index, collection) {
+          return func.call(thisArg, accumulator, value, index, collection);
+        };
+      }
+      return bind(func, thisArg);
+    }
+
+    /**
+     * The base implementation of `_.flatten` without support for callback
+     * shorthands or `thisArg` binding.
+     *
+     * @private
+     * @param {Array} array The array to flatten.
+     * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
+     * @param {boolean} [isArgArrays=false] A flag to restrict flattening to arrays and `arguments` objects.
+     * @param {number} [fromIndex=0] The index to start from.
+     * @returns {Array} Returns a new flattened array.
+     */
+    function baseFlatten(array, isShallow, isArgArrays, fromIndex) {
+      var index = (fromIndex || 0) - 1,
+          length = array ? array.length : 0,
+          result = [];
+
+      while (++index < length) {
+        var value = array[index];
+
+        if (value && typeof value == 'object' && typeof value.length == 'number'
+            && (isArray(value) || isArguments(value))) {
+          // recursively flatten arrays (susceptible to call stack limits)
+          if (!isShallow) {
+            value = baseFlatten(value, isShallow, isArgArrays);
+          }
+          var valIndex = -1,
+              valLength = value.length,
+              resIndex = result.length;
+
+          result.length += valLength;
+          while (++valIndex < valLength) {
+            result[resIndex++] = value[valIndex];
+          }
+        } else if (!isArgArrays) {
+          result.push(value);
+        }
+      }
+      return result;
+    }
+
+    /**
+     * The base implementation of `_.isEqual`, without support for `thisArg` binding,
+     * that allows partial "_.where" style comparisons.
+     *
+     * @private
+     * @param {*} a The value to compare.
+     * @param {*} b The other value to compare.
+     * @param {Function} [callback] The function to customize comparing values.
+     * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
+     * @param {Array} [stackA=[]] Tracks traversed `a` objects.
+     * @param {Array} [stackB=[]] Tracks traversed `b` objects.
+     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+     */
+    function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
+      // used to indicate that when comparing objects, `a` has at least the properties of `b`
+      if (callback) {
+        var result = callback(a, b);
+        if (typeof result != 'undefined') {
+          return !!result;
+        }
+      }
+      // exit early for identical values
+      if (a === b) {
+        // treat `+0` vs. `-0` as not equal
+        return a !== 0 || (1 / a == 1 / b);
+      }
+      var type = typeof a,
+          otherType = typeof b;
+
+      // exit early for unlike primitive values
+      if (a === a &&
+          !(a && objectTypes[type]) &&
+          !(b && objectTypes[otherType])) {
+        return false;
+      }
+      // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
+      // http://es5.github.io/#x15.3.4.4
+      if (a == null || b == null) {
+        return a === b;
+      }
+      // compare [[Class]] names
+      var className = toString.call(a),
+          otherClass = toString.call(b);
+
+      if (className == argsClass) {
+        className = objectClass;
+      }
+      if (otherClass == argsClass) {
+        otherClass = objectClass;
+      }
+      if (className != otherClass) {
+        return false;
+      }
+      switch (className) {
+        case boolClass:
+        case dateClass:
+          // coerce dates and booleans to numbers, dates to milliseconds and booleans
+          // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
+          return +a == +b;
+
+        case numberClass:
+          // treat `NaN` vs. `NaN` as equal
+          return (a != +a)
+            ? b != +b
+            // but treat `+0` vs. `-0` as not equal
+            : (a == 0 ? (1 / a == 1 / b) : a == +b);
+
+        case regexpClass:
+        case stringClass:
+          // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
+          // treat string primitives and their corresponding object instances as equal
+          return a == String(b);
+      }
+      var isArr = className == arrayClass;
+      if (!isArr) {
+        // unwrap any `lodash` wrapped values
+        if (hasOwnProperty.call(a, '__wrapped__ ') || hasOwnProperty.call(b, '__wrapped__')) {
+          return baseIsEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, isWhere, stackA, stackB);
+        }
+        // exit for functions and DOM nodes
+        if (className != objectClass) {
+          return false;
+        }
+        // in older versions of Opera, `arguments` objects have `Array` constructors
+        var ctorA = a.constructor,
+            ctorB = b.constructor;
+
+        // non `Object` object instances with different constructors are not equal
+        if (ctorA != ctorB && !(
+              isFunction(ctorA) && ctorA instanceof ctorA &&
+              isFunction(ctorB) && ctorB instanceof ctorB
+            )) {
+          return false;
+        }
+      }
+      // assume cyclic structures are equal
+      // the algorithm for detecting cyclic structures is adapted from ES 5.1
+      // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
+      var initedStack = !stackA;
+      stackA || (stackA = getArray());
+      stackB || (stackB = getArray());
+
+      var length = stackA.length;
+      while (length--) {
+        if (stackA[length] == a) {
+          return stackB[length] == b;
+        }
+      }
+      var size = 0;
+      result = true;
+
+      // add `a` and `b` to the stack of traversed objects
+      stackA.push(a);
+      stackB.push(b);
+
+      // recursively compare objects and arrays (susceptible to call stack limits)
+      if (isArr) {
+        length = a.length;
+        size = b.length;
+
+        // compare lengths to determine if a deep comparison is necessary
+        result = size == a.length;
+        if (!result && !isWhere) {
+          return result;
+        }
+        // deep compare the contents, ignoring non-numeric properties
+        while (size--) {
+          var index = length,
+              value = b[size];
+
+          if (isWhere) {
+            while (index--) {
+              if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
+                break;
+              }
+            }
+          } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
+            break;
+          }
+        }
+        return result;
+      }
+      // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
+      // which, in this case, is more costly
+      forIn(b, function(value, key, b) {
+        if (hasOwnProperty.call(b, key)) {
+          // count the number of properties.
+          size++;
+          // deep compare each property value.
+          return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
+        }
+      });
+
+      if (result && !isWhere) {
+        // ensure both objects have the same number of properties
+        forIn(a, function(value, key, a) {
+          if (hasOwnProperty.call(a, key)) {
+            // `size` will be `-1` if `a` has more properties than `b`
+            return (result = --size > -1);
+          }
+        });
+      }
+      if (initedStack) {
+        releaseArray(stackA);
+        releaseArray(stackB);
+      }
+      return result;
+    }
+
+    /**
+     * The base implementation of `_.merge` without argument juggling or support
+     * for `thisArg` binding.
+     *
+     * @private
+     * @param {Object} object The destination object.
+     * @param {Object} source The source object.
+     * @param {Function} [callback] The function to customize merging properties.
+     * @param {Array} [stackA=[]] Tracks traversed source objects.
+     * @param {Array} [stackB=[]] Associates values with source counterparts.
+     */
+    function baseMerge(object, source, callback, stackA, stackB) {
+      (isArray(source) ? forEach : forOwn)(source, function(source, key) {
+        var found,
+            isArr,
+            result = source,
+            value = object[key];
+
+        if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
+          // avoid merging previously merged cyclic sources
+          var stackLength = stackA.length;
+          while (stackLength--) {
+            if ((found = stackA[stackLength] == source)) {
+              value = stackB[stackLength];
+              break;
+            }
+          }
+          if (!found) {
+            var isShallow;
+            if (callback) {
+              result = callback(value, source);
+              if ((isShallow = typeof result != 'undefined')) {
+                value = result;
+              }
+            }
+            if (!isShallow) {
+              value = isArr
+                ? (isArray(value) ? value : [])
+                : (isPlainObject(value) ? value : {});
+            }
+            // add `source` and associated `value` to the stack of traversed objects
+            stackA.push(source);
+            stackB.push(value);
+
+            // recursively merge objects and arrays (susceptible to call stack limits)
+            if (!isShallow) {
+              baseMerge(value, source, callback, stackA, stackB);
+            }
+          }
+        }
+        else {
+          if (callback) {
+            result = callback(value, source);
+            if (typeof result == 'undefined') {
+              result = source;
+            }
+          }
+          if (typeof result != 'undefined') {
+            value = result;
+          }
+        }
+        object[key] = value;
+      });
+    }
+
+    /**
+     * The base implementation of `_.uniq` without support for callback shorthands
+     * or `thisArg` binding.
+     *
+     * @private
+     * @param {Array} array The array to process.
+     * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
+     * @param {Function} [callback] The function called per iteration.
+     * @returns {Array} Returns a duplicate-value-free array.
+     */
+    function baseUniq(array, isSorted, callback) {
+      var index = -1,
+          indexOf = getIndexOf(),
+          length = array ? array.length : 0,
+          result = [];
+
+      var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
+          seen = (callback || isLarge) ? getArray() : result;
+
+      if (isLarge) {
+        var cache = createCache(seen);
+        if (cache) {
+          indexOf = cacheIndexOf;
+          seen = cache;
+        } else {
+          isLarge = false;
+          seen = callback ? seen : (releaseArray(seen), result);
+        }
+      }
+      while (++index < length) {
+        var value = array[index],
+            computed = callback ? callback(value, index, array) : value;
+
+        if (isSorted
+              ? !index || seen[seen.length - 1] !== computed
+              : indexOf(seen, computed) < 0
+            ) {
+          if (callback || isLarge) {
+            seen.push(computed);
+          }
+          result.push(value);
+        }
+      }
+      if (isLarge) {
+        releaseArray(seen.array);
+        releaseObject(seen);
+      } else if (callback) {
+        releaseArray(seen);
+      }
+      return result;
+    }
+
+    /**
+     * Creates a function that aggregates a collection, creating an object composed
+     * of keys generated from the results of running each element of the collection
+     * through a callback. The given `setter` function sets the keys and values
+     * of the composed object.
+     *
+     * @private
+     * @param {Function} setter The setter function.
+     * @returns {Function} Returns the new aggregator function.
+     */
+    function createAggregator(setter) {
+      return function(collection, callback, thisArg) {
+        var result = {};
+        callback = lodash.createCallback(callback, thisArg, 3);
+
+        var index = -1,
+            length = collection ? collection.length : 0;
+
+        if (typeof length == 'number') {
+          while (++index < length) {
+            var value = collection[index];
+            setter(result, value, callback(value, index, collection), collection);
+          }
+        } else {
+          forOwn(collection, function(value, key, collection) {
+            setter(result, value, callback(value, key, collection), collection);
+          });
+        }
+        return result;
+      };
+    }
+
+    /**
+     * Creates a function that, when called, either curries or invokes `func`
+     * with an optional `this` binding and partially applied arguments.
+     *
+     * @private
+     * @param {Function|string} func The function or method name to reference.
+     * @param {number} bitmask The bitmask of method flags to compose.
+     *  The bitmask may be composed of the following flags:
+     *  1 - `_.bind`
+     *  2 - `_.bindKey`
+     *  4 - `_.curry`
+     *  8 - `_.curry` (bound)
+     *  16 - `_.partial`
+     *  32 - `_.partialRight`
+     * @param {Array} [partialArgs] An array of arguments to prepend to those
+     *  provided to the new function.
+     * @param {Array} [partialRightArgs] An array of arguments to append to those
+     *  provided to the new function.
+     * @param {*} [thisArg] The `this` binding of `func`.
+     * @param {number} [arity] The arity of `func`.
+     * @returns {Function} Returns the new bound function.
+     */
+    function createBound(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
+      var isBind = bitmask & 1,
+          isBindKey = bitmask & 2,
+          isCurry = bitmask & 4,
+          isCurryBound = bitmask & 8,
+          isPartial = bitmask & 16,
+          isPartialRight = bitmask & 32,
+          key = func;
+
+      if (!isBindKey && !isFunction(func)) {
+        throw new TypeError;
+      }
+      if (isPartial && !partialArgs.length) {
+        bitmask &= ~16;
+        isPartial = partialArgs = false;
+      }
+      if (isPartialRight && !partialRightArgs.length) {
+        bitmask &= ~32;
+        isPartialRight = partialRightArgs = false;
+      }
+      var bindData = func && func.__bindData__;
+      if (bindData) {
+        if (isBind && !(bindData[1] & 1)) {
+          bindData[4] = thisArg;
+        }
+        if (!isBind && bindData[1] & 1) {
+          bitmask |= 8;
+        }
+        if (isCurry && !(bindData[1] & 4)) {
+          bindData[5] = arity;
+        }
+        if (isPartial) {
+          push.apply(bindData[2] || (bindData[2] = []), partialArgs);
+        }
+        if (isPartialRight) {
+          push.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
+        }
+        bindData[1] |= bitmask;
+        return createBound.apply(null, bindData);
+      }
+      // use `Function#bind` if it exists and is fast
+      // (in V8 `Function#bind` is slower except when partially applied)
+      if (isBind && !(isBindKey || isCurry || isPartialRight) &&
+          (support.fastBind || (nativeBind && isPartial))) {
+        if (isPartial) {
+          var args = [thisArg];
+          push.apply(args, partialArgs);
+        }
+        var bound = isPartial
+          ? nativeBind.apply(func, args)
+          : nativeBind.call(func, thisArg);
+      }
+      else {
+        bound = function() {
+          // `Function#bind` spec
+          // http://es5.github.io/#x15.3.4.5
+          var args = arguments,
+              thisBinding = isBind ? thisArg : this;
+
+          if (isCurry || isPartial || isPartialRight) {
+            args = nativeSlice.call(args);
+            if (isPartial) {
+              unshift.apply(args, partialArgs);
+            }
+            if (isPartialRight) {
+              push.apply(args, partialRightArgs);
+            }
+            if (isCurry && args.length < arity) {
+              bitmask |= 16 & ~32;
+              return createBound(func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity);
+            }
+          }
+          if (isBindKey) {
+            func = thisBinding[key];
+          }
+          if (this instanceof bound) {
+            // ensure `new bound` is an instance of `func`
+            thisBinding = createObject(func.prototype);
+
+            // mimic the constructor's `return` behavior
+            // http://es5.github.io/#x13.2.2
+            var result = func.apply(thisBinding, args);
+            return isObject(result) ? result : thisBinding;
+          }
+          return func.apply(thisBinding, args);
+        };
+      }
+      setBindData(bound, nativeSlice.call(arguments));
+      return bound;
+    }
+
+    /**
+     * Creates a new object with the specified `prototype`.
+     *
+     * @private
+     * @param {Object} prototype The prototype object.
+     * @returns {Object} Returns the new object.
+     */
+    function createObject(prototype) {
+      return isObject(prototype) ? nativeCreate(prototype) : {};
+    }
+    // fallback for browsers without `Object.create`
+    if (!nativeCreate) {
+      createObject = function(prototype) {
+        if (isObject(prototype)) {
+          noop.prototype = prototype;
+          var result = new noop;
+          noop.prototype = null;
+        }
+        return result || {};
+      };
+    }
+
+    /**
+     * Used by `escape` to convert characters to HTML entities.
+     *
+     * @private
+     * @param {string} match The matched character to escape.
+     * @returns {string} Returns the escaped character.
+     */
+    function escapeHtmlChar(match) {
+      return htmlEscapes[match];
+    }
+
+    /**
+     * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
+     * customized, this method returns the custom method, otherwise it returns
+     * the `baseIndexOf` function.
+     *
+     * @private
+     * @returns {Function} Returns the "indexOf" function.
+     */
+    function getIndexOf() {
+      var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
+      return result;
+    }
+
+    /**
+     * Sets `this` binding data on a given function.
+     *
+     * @private
+     * @param {Function} func The function to set data on.
+     * @param {*} value The value to set.
+     */
+    var setBindData = !defineProperty ? noop : function(func, value) {
+      descriptor.value = value;
+      defineProperty(func, '__bindData__', descriptor);
+    };
+
+    /**
+     * A fallback implementation of `isPlainObject` which checks if a given value
+     * is an object created by the `Object` constructor, assuming objects created
+     * by the `Object` constructor have no inherited enumerable properties and that
+     * there are no `Object.prototype` extensions.
+     *
+     * @private
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
+     */
+    function shimIsPlainObject(value) {
+      var ctor,
+          result;
+
+      // avoid non Object objects, `arguments` objects, and DOM elements
+      if (!(value && toString.call(value) == objectClass) ||
+          (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
+        return false;
+      }
+      // In most environments an object's own properties are iterated before
+      // its inherited properties. If the last iterated property is an object's
+      // own property then there are no inherited enumerable properties.
+      forIn(value, function(value, key) {
+        result = key;
+      });
+      return typeof result == 'undefined' || hasOwnProperty.call(value, result);
+    }
+
+    /**
+     * Used by `unescape` to convert HTML entities to characters.
+     *
+     * @private
+     * @param {string} match The matched character to unescape.
+     * @returns {string} Returns the unescaped character.
+     */
+    function unescapeHtmlChar(match) {
+      return htmlUnescapes[match];
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Checks if `value` is an `arguments` object.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
+     * @example
+     *
+     * (function() { return _.isArguments(arguments); })(1, 2, 3);
+     * // => true
+     *
+     * _.isArguments([1, 2, 3]);
+     * // => false
+     */
+    function isArguments(value) {
+      return value && typeof value == 'object' && typeof value.length == 'number' &&
+        toString.call(value) == argsClass || false;
+    }
+
+    /**
+     * Checks if `value` is an array.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is an array, else `false`.
+     * @example
+     *
+     * (function() { return _.isArray(arguments); })();
+     * // => false
+     *
+     * _.isArray([1, 2, 3]);
+     * // => true
+     */
+    var isArray = nativeIsArray || function(value) {
+      return value && typeof value == 'object' && typeof value.length == 'number' &&
+        toString.call(value) == arrayClass || false;
+    };
+
+    /**
+     * A fallback implementation of `Object.keys` which produces an array of the
+     * given object's own enumerable property names.
+     *
+     * @private
+     * @type Function
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property names.
+     */
+    var shimKeys = function(object) {
+      var index, iterable = object, result = [];
+      if (!iterable) return result;
+      if (!(objectTypes[typeof object])) return result;
+        for (index in iterable) {
+          if (hasOwnProperty.call(iterable, index)) {
+            result.push(index);
+          }
+        }
+      return result
+    };
+
+    /**
+     * Creates an array composed of the own enumerable property names of an object.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property names.
+     * @example
+     *
+     * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
+     * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
+     */
+    var keys = !nativeKeys ? shimKeys : function(object) {
+      if (!isObject(object)) {
+        return [];
+      }
+      return nativeKeys(object);
+    };
+
+    /**
+     * Used to convert characters to HTML entities:
+     *
+     * Though the `>` character is escaped for symmetry, characters like `>` and `/`
+     * don't require escaping in HTML and have no special meaning unless they're part
+     * of a tag or an unquoted attribute value.
+     * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
+     */
+    var htmlEscapes = {
+      '&': '&amp;',
+      '<': '&lt;',
+      '>': '&gt;',
+      '"': '&quot;',
+      "'": '&#39;'
+    };
+
+    /** Used to convert HTML entities to characters */
+    var htmlUnescapes = invert(htmlEscapes);
+
+    /** Used to match HTML entities and HTML characters */
+    var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
+        reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Assigns own enumerable properties of source object(s) to the destination
+     * object. Subsequent sources will overwrite property assignments of previous
+     * sources. If a callback is provided it will be executed to produce the
+     * assigned values. The callback is bound to `thisArg` and invoked with two
+     * arguments; (objectValue, sourceValue).
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @alias extend
+     * @category Objects
+     * @param {Object} object The destination object.
+     * @param {...Object} [source] The source objects.
+     * @param {Function} [callback] The function to customize assigning values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the destination object.
+     * @example
+     *
+     * _.assign({ 'name': 'moe' }, { 'age': 40 });
+     * // => { 'name': 'moe', 'age': 40 }
+     *
+     * var defaults = _.partialRight(_.assign, function(a, b) {
+     *   return typeof a == 'undefined' ? b : a;
+     * });
+     *
+     * var food = { 'name': 'apple' };
+     * defaults(food, { 'name': 'banana', 'type': 'fruit' });
+     * // => { 'name': 'apple', 'type': 'fruit' }
+     */
+    var assign = function(object, source, guard) {
+      var index, iterable = object, result = iterable;
+      if (!iterable) return result;
+      var args = arguments,
+          argsIndex = 0,
+          argsLength = typeof guard == 'number' ? 2 : args.length;
+      if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
+        var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);
+      } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
+        callback = args[--argsLength];
+      }
+      while (++argsIndex < argsLength) {
+        iterable = args[argsIndex];
+        if (iterable && objectTypes[typeof iterable]) {
+        var ownIndex = -1,
+            ownProps = objectTypes[typeof iterable] && keys(iterable),
+            length = ownProps ? ownProps.length : 0;
+
+        while (++ownIndex < length) {
+          index = ownProps[ownIndex];
+          result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
+        }
+        }
+      }
+      return result
+    };
+
+    /**
+     * Creates a clone of `value`. If `deep` is `true` nested objects will also
+     * be cloned, otherwise they will be assigned by reference. If a callback
+     * is provided it will be executed to produce the cloned values. If the
+     * callback returns `undefined` cloning will be handled by the method instead.
+     * The callback is bound to `thisArg` and invoked with one argument; (value).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to clone.
+     * @param {boolean} [deep=false] Specify a deep clone.
+     * @param {Function} [callback] The function to customize cloning values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the cloned value.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * var shallow = _.clone(stooges);
+     * shallow[0] === stooges[0];
+     * // => true
+     *
+     * var deep = _.clone(stooges, true);
+     * deep[0] === stooges[0];
+     * // => false
+     *
+     * _.mixin({
+     *   'clone': _.partialRight(_.clone, function(value) {
+     *     return _.isElement(value) ? value.cloneNode(false) : undefined;
+     *   })
+     * });
+     *
+     * var clone = _.clone(document.body);
+     * clone.childNodes.length;
+     * // => 0
+     */
+    function clone(value, deep, callback, thisArg) {
+      // allows working with "Collections" methods without using their `index`
+      // and `collection` arguments for `deep` and `callback`
+      if (typeof deep != 'boolean' && deep != null) {
+        thisArg = callback;
+        callback = deep;
+        deep = false;
+      }
+      return baseClone(value, deep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
+    }
+
+    /**
+     * Creates a deep clone of `value`. If a callback is provided it will be
+     * executed to produce the cloned values. If the callback returns `undefined`
+     * cloning will be handled by the method instead. The callback is bound to
+     * `thisArg` and invoked with one argument; (value).
+     *
+     * Note: This method is loosely based on the structured clone algorithm. Functions
+     * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
+     * objects created by constructors other than `Object` are cloned to plain `Object` objects.
+     * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to deep clone.
+     * @param {Function} [callback] The function to customize cloning values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the deep cloned value.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * var deep = _.cloneDeep(stooges);
+     * deep[0] === stooges[0];
+     * // => false
+     *
+     * var view = {
+     *   'label': 'docs',
+     *   'node': element
+     * };
+     *
+     * var clone = _.cloneDeep(view, function(value) {
+     *   return _.isElement(value) ? value.cloneNode(true) : undefined;
+     * });
+     *
+     * clone.node == view.node;
+     * // => false
+     */
+    function cloneDeep(value, callback, thisArg) {
+      return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
+    }
+
+    /**
+     * Assigns own enumerable properties of source object(s) to the destination
+     * object for all destination properties that resolve to `undefined`. Once a
+     * property is set, additional defaults of the same property will be ignored.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {Object} object The destination object.
+     * @param {...Object} [source] The source objects.
+     * @param- {Object} [guard] Allows working with `_.reduce` without using its
+     *  `key` and `object` arguments as sources.
+     * @returns {Object} Returns the destination object.
+     * @example
+     *
+     * var food = { 'name': 'apple' };
+     * _.defaults(food, { 'name': 'banana', 'type': 'fruit' });
+     * // => { 'name': 'apple', 'type': 'fruit' }
+     */
+    var defaults = function(object, source, guard) {
+      var index, iterable = object, result = iterable;
+      if (!iterable) return result;
+      var args = arguments,
+          argsIndex = 0,
+          argsLength = typeof guard == 'number' ? 2 : args.length;
+      while (++argsIndex < argsLength) {
+        iterable = args[argsIndex];
+        if (iterable && objectTypes[typeof iterable]) {
+        var ownIndex = -1,
+            ownProps = objectTypes[typeof iterable] && keys(iterable),
+            length = ownProps ? ownProps.length : 0;
+
+        while (++ownIndex < length) {
+          index = ownProps[ownIndex];
+          if (typeof result[index] == 'undefined') result[index] = iterable[index];
+        }
+        }
+      }
+      return result
+    };
+
+    /**
+     * This method is like `_.findIndex` except that it returns the key of the
+     * first element that passes the callback check, instead of the element itself.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to search.
+     * @param {Function|Object|string} [callback=identity] The function called per
+     *  iteration. If a property name or object is provided it will be used to
+     *  create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {string|undefined} Returns the key of the found element, else `undefined`.
+     * @example
+     *
+     * _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
+     *   return num % 2 == 0;
+     * });
+     * // => 'b' (property order is not guaranteed across environments)
+     */
+    function findKey(object, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forOwn(object, function(value, key, object) {
+        if (callback(value, key, object)) {
+          result = key;
+          return false;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * This method is like `_.findKey` except that it iterates over elements
+     * of a `collection` in the opposite order.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to search.
+     * @param {Function|Object|string} [callback=identity] The function called per
+     *  iteration. If a property name or object is provided it will be used to
+     *  create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {string|undefined} Returns the key of the found element, else `undefined`.
+     * @example
+     *
+     * _.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
+     *   return num % 2 == 1;
+     * });
+     * // => returns `c`, assuming `_.findKey` returns `a`
+     */
+    function findLastKey(object, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forOwnRight(object, function(value, key, object) {
+        if (callback(value, key, object)) {
+          result = key;
+          return false;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * Iterates over own and inherited enumerable properties of an object,
+     * executing the callback for each property. The callback is bound to `thisArg`
+     * and invoked with three arguments; (value, key, object). Callbacks may exit
+     * iteration early by explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * function Dog(name) {
+     *   this.name = name;
+     * }
+     *
+     * Dog.prototype.bark = function() {
+     *   console.log('Woof, woof!');
+     * };
+     *
+     * _.forIn(new Dog('Dagny'), function(value, key) {
+     *   console.log(key);
+     * });
+     * // => logs 'bark' and 'name' (property order is not guaranteed across environments)
+     */
+    var forIn = function(collection, callback, thisArg) {
+      var index, iterable = collection, result = iterable;
+      if (!iterable) return result;
+      if (!objectTypes[typeof iterable]) return result;
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+        for (index in iterable) {
+          if (callback(iterable[index], index, collection) === false) return result;
+        }
+      return result
+    };
+
+    /**
+     * This method is like `_.forIn` except that it iterates over elements
+     * of a `collection` in the opposite order.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * function Dog(name) {
+     *   this.name = name;
+     * }
+     *
+     * Dog.prototype.bark = function() {
+     *   console.log('Woof, woof!');
+     * };
+     *
+     * _.forInRight(new Dog('Dagny'), function(value, key) {
+     *   console.log(key);
+     * });
+     * // => logs 'name' and 'bark' assuming `_.forIn ` logs 'bark' and 'name'
+     */
+    function forInRight(object, callback, thisArg) {
+      var pairs = [];
+
+      forIn(object, function(value, key) {
+        pairs.push(key, value);
+      });
+
+      var length = pairs.length;
+      callback = baseCreateCallback(callback, thisArg, 3);
+      while (length--) {
+        if (callback(pairs[length--], pairs[length], object) === false) {
+          break;
+        }
+      }
+      return object;
+    }
+
+    /**
+     * Iterates over own enumerable properties of an object, executing the callback
+     * for each property. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, key, object). Callbacks may exit iteration early by
+     * explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
+     *   console.log(key);
+     * });
+     * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
+     */
+    var forOwn = function(collection, callback, thisArg) {
+      var index, iterable = collection, result = iterable;
+      if (!iterable) return result;
+      if (!objectTypes[typeof iterable]) return result;
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+        var ownIndex = -1,
+            ownProps = objectTypes[typeof iterable] && keys(iterable),
+            length = ownProps ? ownProps.length : 0;
+
+        while (++ownIndex < length) {
+          index = ownProps[ownIndex];
+          if (callback(iterable[index], index, collection) === false) return result;
+        }
+      return result
+    };
+
+    /**
+     * This method is like `_.forOwn` except that it iterates over elements
+     * of a `collection` in the opposite order.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
+     *   console.log(key);
+     * });
+     * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
+     */
+    function forOwnRight(object, callback, thisArg) {
+      var props = keys(object),
+          length = props.length;
+
+      callback = baseCreateCallback(callback, thisArg, 3);
+      while (length--) {
+        var key = props[length];
+        if (callback(object[key], key, object) === false) {
+          break;
+        }
+      }
+      return object;
+    }
+
+    /**
+     * Creates a sorted array of property names of all enumerable properties,
+     * own and inherited, of `object` that have function values.
+     *
+     * @static
+     * @memberOf _
+     * @alias methods
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property names that have function values.
+     * @example
+     *
+     * _.functions(_);
+     * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
+     */
+    function functions(object) {
+      var result = [];
+      forIn(object, function(value, key) {
+        if (isFunction(value)) {
+          result.push(key);
+        }
+      });
+      return result.sort();
+    }
+
+    /**
+     * Checks if the specified object `property` exists and is a direct property,
+     * instead of an inherited property.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to check.
+     * @param {string} property The property to check for.
+     * @returns {boolean} Returns `true` if key is a direct property, else `false`.
+     * @example
+     *
+     * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
+     * // => true
+     */
+    function has(object, property) {
+      return object ? hasOwnProperty.call(object, property) : false;
+    }
+
+    /**
+     * Creates an object composed of the inverted keys and values of the given object.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to invert.
+     * @returns {Object} Returns the created inverted object.
+     * @example
+     *
+     *  _.invert({ 'first': 'moe', 'second': 'larry' });
+     * // => { 'moe': 'first', 'larry': 'second' }
+     */
+    function invert(object) {
+      var index = -1,
+          props = keys(object),
+          length = props.length,
+          result = {};
+
+      while (++index < length) {
+        var key = props[index];
+        result[object[key]] = key;
+      }
+      return result;
+    }
+
+    /**
+     * Checks if `value` is a boolean value.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
+     * @example
+     *
+     * _.isBoolean(null);
+     * // => false
+     */
+    function isBoolean(value) {
+      return value === true || value === false || toString.call(value) == boolClass;
+    }
+
+    /**
+     * Checks if `value` is a date.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a date, else `false`.
+     * @example
+     *
+     * _.isDate(new Date);
+     * // => true
+     */
+    function isDate(value) {
+      return value ? (typeof value == 'object' && toString.call(value) == dateClass) : false;
+    }
+
+    /**
+     * Checks if `value` is a DOM element.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
+     * @example
+     *
+     * _.isElement(document.body);
+     * // => true
+     */
+    function isElement(value) {
+      return value ? value.nodeType === 1 : false;
+    }
+
+    /**
+     * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
+     * length of `0` and objects with no own enumerable properties are considered
+     * "empty".
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Array|Object|string} value The value to inspect.
+     * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
+     * @example
+     *
+     * _.isEmpty([1, 2, 3]);
+     * // => false
+     *
+     * _.isEmpty({});
+     * // => true
+     *
+     * _.isEmpty('');
+     * // => true
+     */
+    function isEmpty(value) {
+      var result = true;
+      if (!value) {
+        return result;
+      }
+      var className = toString.call(value),
+          length = value.length;
+
+      if ((className == arrayClass || className == stringClass || className == argsClass ) ||
+          (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
+        return !length;
+      }
+      forOwn(value, function() {
+        return (result = false);
+      });
+      return result;
+    }
+
+    /**
+     * Performs a deep comparison between two values to determine if they are
+     * equivalent to each other. If a callback is provided it will be executed
+     * to compare values. If the callback returns `undefined` comparisons will
+     * be handled by the method instead. The callback is bound to `thisArg` and
+     * invoked with two arguments; (a, b).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} a The value to compare.
+     * @param {*} b The other value to compare.
+     * @param {Function} [callback] The function to customize comparing values.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+     * @example
+     *
+     * var moe = { 'name': 'moe', 'age': 40 };
+     * var copy = { 'name': 'moe', 'age': 40 };
+     *
+     * moe == copy;
+     * // => false
+     *
+     * _.isEqual(moe, copy);
+     * // => true
+     *
+     * var words = ['hello', 'goodbye'];
+     * var otherWords = ['hi', 'goodbye'];
+     *
+     * _.isEqual(words, otherWords, function(a, b) {
+     *   var reGreet = /^(?:hello|hi)$/i,
+     *       aGreet = _.isString(a) && reGreet.test(a),
+     *       bGreet = _.isString(b) && reGreet.test(b);
+     *
+     *   return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
+     * });
+     * // => true
+     */
+    function isEqual(a, b, callback, thisArg) {
+      return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
+    }
+
+    /**
+     * Checks if `value` is, or can be coerced to, a finite number.
+     *
+     * Note: This is not the same as native `isFinite` which will return true for
+     * booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is finite, else `false`.
+     * @example
+     *
+     * _.isFinite(-101);
+     * // => true
+     *
+     * _.isFinite('10');
+     * // => true
+     *
+     * _.isFinite(true);
+     * // => false
+     *
+     * _.isFinite('');
+     * // => false
+     *
+     * _.isFinite(Infinity);
+     * // => false
+     */
+    function isFinite(value) {
+      return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
+    }
+
+    /**
+     * Checks if `value` is a function.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
+     * @example
+     *
+     * _.isFunction(_);
+     * // => true
+     */
+    function isFunction(value) {
+      return typeof value == 'function';
+    }
+
+    /**
+     * Checks if `value` is the language type of Object.
+     * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
+     * @example
+     *
+     * _.isObject({});
+     * // => true
+     *
+     * _.isObject([1, 2, 3]);
+     * // => true
+     *
+     * _.isObject(1);
+     * // => false
+     */
+    function isObject(value) {
+      // check if the value is the ECMAScript language type of Object
+      // http://es5.github.io/#x8
+      // and avoid a V8 bug
+      // http://code.google.com/p/v8/issues/detail?id=2291
+      return !!(value && objectTypes[typeof value]);
+    }
+
+    /**
+     * Checks if `value` is `NaN`.
+     *
+     * Note: This is not the same as native `isNaN` which will return `true` for
+     * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
+     * @example
+     *
+     * _.isNaN(NaN);
+     * // => true
+     *
+     * _.isNaN(new Number(NaN));
+     * // => true
+     *
+     * isNaN(undefined);
+     * // => true
+     *
+     * _.isNaN(undefined);
+     * // => false
+     */
+    function isNaN(value) {
+      // `NaN` as a primitive is the only value that is not equal to itself
+      // (perform the [[Class]] check first to avoid errors with some host objects in IE)
+      return isNumber(value) && value != +value;
+    }
+
+    /**
+     * Checks if `value` is `null`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
+     * @example
+     *
+     * _.isNull(null);
+     * // => true
+     *
+     * _.isNull(undefined);
+     * // => false
+     */
+    function isNull(value) {
+      return value === null;
+    }
+
+    /**
+     * Checks if `value` is a number.
+     *
+     * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a number, else `false`.
+     * @example
+     *
+     * _.isNumber(8.4 * 5);
+     * // => true
+     */
+    function isNumber(value) {
+      return typeof value == 'number' || toString.call(value) == numberClass;
+    }
+
+    /**
+     * Checks if `value` is an object created by the `Object` constructor.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
+     * @example
+     *
+     * function Stooge(name, age) {
+     *   this.name = name;
+     *   this.age = age;
+     * }
+     *
+     * _.isPlainObject(new Stooge('moe', 40));
+     * // => false
+     *
+     * _.isPlainObject([1, 2, 3]);
+     * // => false
+     *
+     * _.isPlainObject({ 'name': 'moe', 'age': 40 });
+     * // => true
+     */
+    var isPlainObject = function(value) {
+      if (!(value && toString.call(value) == objectClass)) {
+        return false;
+      }
+      var valueOf = value.valueOf,
+          objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
+
+      return objProto
+        ? (value == objProto || getPrototypeOf(value) == objProto)
+        : shimIsPlainObject(value);
+    };
+
+    /**
+     * Checks if `value` is a regular expression.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
+     * @example
+     *
+     * _.isRegExp(/moe/);
+     * // => true
+     */
+    function isRegExp(value) {
+      return value ? (typeof value == 'object' && toString.call(value) == regexpClass) : false;
+    }
+
+    /**
+     * Checks if `value` is a string.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is a string, else `false`.
+     * @example
+     *
+     * _.isString('moe');
+     * // => true
+     */
+    function isString(value) {
+      return typeof value == 'string' || toString.call(value) == stringClass;
+    }
+
+    /**
+     * Checks if `value` is `undefined`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {*} value The value to check.
+     * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
+     * @example
+     *
+     * _.isUndefined(void 0);
+     * // => true
+     */
+    function isUndefined(value) {
+      return typeof value == 'undefined';
+    }
+
+    /**
+     * Recursively merges own enumerable properties of the source object(s), that
+     * don't resolve to `undefined` into the destination object. Subsequent sources
+     * will overwrite property assignments of previous sources. If a callback is
+     * provided it will be executed to produce the merged values of the destination
+     * and source properties. If the callback returns `undefined` merging will
+     * be handled by the method instead. The callback is bound to `thisArg` and
+     * invoked with two arguments; (objectValue, sourceValue).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The destination object.
+     * @param {...Object} [source] The source objects.
+     * @param {Function} [callback] The function to customize merging properties.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the destination object.
+     * @example
+     *
+     * var names = {
+     *   'stooges': [
+     *     { 'name': 'moe' },
+     *     { 'name': 'larry' }
+     *   ]
+     * };
+     *
+     * var ages = {
+     *   'stooges': [
+     *     { 'age': 40 },
+     *     { 'age': 50 }
+     *   ]
+     * };
+     *
+     * _.merge(names, ages);
+     * // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] }
+     *
+     * var food = {
+     *   'fruits': ['apple'],
+     *   'vegetables': ['beet']
+     * };
+     *
+     * var otherFood = {
+     *   'fruits': ['banana'],
+     *   'vegetables': ['carrot']
+     * };
+     *
+     * _.merge(food, otherFood, function(a, b) {
+     *   return _.isArray(a) ? a.concat(b) : undefined;
+     * });
+     * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
+     */
+    function merge(object) {
+      var args = arguments,
+          length = 2;
+
+      if (!isObject(object)) {
+        return object;
+      }
+      // allows working with `_.reduce` and `_.reduceRight` without using
+      // their `index` and `collection` arguments
+      if (typeof args[2] != 'number') {
+        length = args.length;
+      }
+      if (length > 3 && typeof args[length - 2] == 'function') {
+        var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
+      } else if (length > 2 && typeof args[length - 1] == 'function') {
+        callback = args[--length];
+      }
+      var sources = nativeSlice.call(arguments, 1, length),
+          index = -1,
+          stackA = getArray(),
+          stackB = getArray();
+
+      while (++index < length) {
+        baseMerge(object, sources[index], callback, stackA, stackB);
+      }
+      releaseArray(stackA);
+      releaseArray(stackB);
+      return object;
+    }
+
+    /**
+     * Creates a shallow clone of `object` excluding the specified properties.
+     * Property names may be specified as individual arguments or as arrays of
+     * property names. If a callback is provided it will be executed for each
+     * property of `object` omitting the properties the callback returns truey
+     * for. The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, key, object).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The source object.
+     * @param {Function|...string|string[]} [callback] The properties to omit or the
+     *  function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns an object without the omitted properties.
+     * @example
+     *
+     * _.omit({ 'name': 'moe', 'age': 40 }, 'age');
+     * // => { 'name': 'moe' }
+     *
+     * _.omit({ 'name': 'moe', 'age': 40 }, function(value) {
+     *   return typeof value == 'number';
+     * });
+     * // => { 'name': 'moe' }
+     */
+    function omit(object, callback, thisArg) {
+      var indexOf = getIndexOf(),
+          isFunc = typeof callback == 'function',
+          result = {};
+
+      if (isFunc) {
+        callback = lodash.createCallback(callback, thisArg, 3);
+      } else {
+        var props = baseFlatten(arguments, true, false, 1);
+      }
+      forIn(object, function(value, key, object) {
+        if (isFunc
+              ? !callback(value, key, object)
+              : indexOf(props, key) < 0
+            ) {
+          result[key] = value;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * Creates a two dimensional array of an object's key-value pairs,
+     * i.e. `[[key1, value1], [key2, value2]]`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns new array of key-value pairs.
+     * @example
+     *
+     * _.pairs({ 'moe': 30, 'larry': 40 });
+     * // => [['moe', 30], ['larry', 40]] (property order is not guaranteed across environments)
+     */
+    function pairs(object) {
+      var index = -1,
+          props = keys(object),
+          length = props.length,
+          result = Array(length);
+
+      while (++index < length) {
+        var key = props[index];
+        result[index] = [key, object[key]];
+      }
+      return result;
+    }
+
+    /**
+     * Creates a shallow clone of `object` composed of the specified properties.
+     * Property names may be specified as individual arguments or as arrays of
+     * property names. If a callback is provided it will be executed for each
+     * property of `object` picking the properties the callback returns truey
+     * for. The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, key, object).
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The source object.
+     * @param {Function|...string|string[]} [callback] The function called per
+     *  iteration or property names to pick, specified as individual property
+     *  names or arrays of property names.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns an object composed of the picked properties.
+     * @example
+     *
+     * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
+     * // => { 'name': 'moe' }
+     *
+     * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
+     *   return key.charAt(0) != '_';
+     * });
+     * // => { 'name': 'moe' }
+     */
+    function pick(object, callback, thisArg) {
+      var result = {};
+      if (typeof callback != 'function') {
+        var index = -1,
+            props = baseFlatten(arguments, true, false, 1),
+            length = isObject(object) ? props.length : 0;
+
+        while (++index < length) {
+          var key = props[index];
+          if (key in object) {
+            result[key] = object[key];
+          }
+        }
+      } else {
+        callback = lodash.createCallback(callback, thisArg, 3);
+        forIn(object, function(value, key, object) {
+          if (callback(value, key, object)) {
+            result[key] = value;
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * An alternative to `_.reduce` this method transforms `object` to a new
+     * `accumulator` object which is the result of running each of its elements
+     * through a callback, with each callback execution potentially mutating
+     * the `accumulator` object. The callback is bound to `thisArg` and invoked
+     * with four arguments; (accumulator, value, key, object). Callbacks may exit
+     * iteration early by explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Array|Object} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [accumulator] The custom accumulator value.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the accumulated value.
+     * @example
+     *
+     * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
+     *   num *= num;
+     *   if (num % 2) {
+     *     return result.push(num) < 3;
+     *   }
+     * });
+     * // => [1, 9, 25]
+     *
+     * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
+     *   result[key] = num * 3;
+     * });
+     * // => { 'a': 3, 'b': 6, 'c': 9 }
+     */
+    function transform(object, callback, accumulator, thisArg) {
+      var isArr = isArray(object);
+      callback = baseCreateCallback(callback, thisArg, 4);
+
+      if (accumulator == null) {
+        if (isArr) {
+          accumulator = [];
+        } else {
+          var ctor = object && object.constructor,
+              proto = ctor && ctor.prototype;
+
+          accumulator = createObject(proto);
+        }
+      }
+      (isArr ? forEach : forOwn)(object, function(value, index, object) {
+        return callback(accumulator, value, index, object);
+      });
+      return accumulator;
+    }
+
+    /**
+     * Creates an array composed of the own enumerable property values of `object`.
+     *
+     * @static
+     * @memberOf _
+     * @category Objects
+     * @param {Object} object The object to inspect.
+     * @returns {Array} Returns an array of property values.
+     * @example
+     *
+     * _.values({ 'one': 1, 'two': 2, 'three': 3 });
+     * // => [1, 2, 3] (property order is not guaranteed across environments)
+     */
+    function values(object) {
+      var index = -1,
+          props = keys(object),
+          length = props.length,
+          result = Array(length);
+
+      while (++index < length) {
+        result[index] = object[props[index]];
+      }
+      return result;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates an array of elements from the specified indexes, or keys, of the
+     * `collection`. Indexes may be specified as individual arguments or as arrays
+     * of indexes.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
+     *   to retrieve, specified as individual indexes or arrays of indexes.
+     * @returns {Array} Returns a new array of elements corresponding to the
+     *  provided indexes.
+     * @example
+     *
+     * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
+     * // => ['a', 'c', 'e']
+     *
+     * _.at(['moe', 'larry', 'curly'], 0, 2);
+     * // => ['moe', 'curly']
+     */
+    function at(collection) {
+      var args = arguments,
+          index = -1,
+          props = baseFlatten(args, true, false, 1),
+          length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
+          result = Array(length);
+
+      while(++index < length) {
+        result[index] = collection[props[index]];
+      }
+      return result;
+    }
+
+    /**
+     * Checks if a given value is present in a collection using strict equality
+     * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
+     * offset from the end of the collection.
+     *
+     * @static
+     * @memberOf _
+     * @alias include
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {*} target The value to check for.
+     * @param {number} [fromIndex=0] The index to search from.
+     * @returns {boolean} Returns `true` if the `target` element is found, else `false`.
+     * @example
+     *
+     * _.contains([1, 2, 3], 1);
+     * // => true
+     *
+     * _.contains([1, 2, 3], 1, 2);
+     * // => false
+     *
+     * _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
+     * // => true
+     *
+     * _.contains('curly', 'ur');
+     * // => true
+     */
+    function contains(collection, target, fromIndex) {
+      var index = -1,
+          indexOf = getIndexOf(),
+          length = collection ? collection.length : 0,
+          result = false;
+
+      fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
+      if (isArray(collection)) {
+        result = indexOf(collection, target, fromIndex) > -1;
+      } else if (typeof length == 'number') {
+        result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
+      } else {
+        forOwn(collection, function(value) {
+          if (++index >= fromIndex) {
+            return !(result = value === target);
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Creates an object composed of keys generated from the results of running
+     * each element of `collection` through the callback. The corresponding value
+     * of each key is the number of times the key was returned by the callback.
+     * The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the composed aggregate object.
+     * @example
+     *
+     * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
+     * // => { '4': 1, '6': 2 }
+     *
+     * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
+     * // => { '4': 1, '6': 2 }
+     *
+     * _.countBy(['one', 'two', 'three'], 'length');
+     * // => { '3': 2, '5': 1 }
+     */
+    var countBy = createAggregator(function(result, value, key) {
+      (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
+    });
+
+    /**
+     * Checks if the given callback returns truey value for **all** elements of
+     * a collection. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias all
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {boolean} Returns `true` if all elements passed the callback check,
+     *  else `false`.
+     * @example
+     *
+     * _.every([true, 1, null, 'yes'], Boolean);
+     * // => false
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.every(stooges, 'age');
+     * // => true
+     *
+     * // using "_.where" callback shorthand
+     * _.every(stooges, { 'age': 50 });
+     * // => false
+     */
+    function every(collection, callback, thisArg) {
+      var result = true;
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          if (!(result = !!callback(collection[index], index, collection))) {
+            break;
+          }
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          return (result = !!callback(value, index, collection));
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Iterates over elements of a collection, returning an array of all elements
+     * the callback returns truey for. The callback is bound to `thisArg` and
+     * invoked with three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias select
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of elements that passed the callback check.
+     * @example
+     *
+     * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
+     * // => [2, 4, 6]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.filter(food, 'organic');
+     * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
+     *
+     * // using "_.where" callback shorthand
+     * _.filter(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
+     */
+    function filter(collection, callback, thisArg) {
+      var result = [];
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          var value = collection[index];
+          if (callback(value, index, collection)) {
+            result.push(value);
+          }
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          if (callback(value, index, collection)) {
+            result.push(value);
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Iterates over elements of a collection, returning the first element that
+     * the callback returns truey for. The callback is bound to `thisArg` and
+     * invoked with three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias detect, findWhere
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the found element, else `undefined`.
+     * @example
+     *
+     * _.find([1, 2, 3, 4], function(num) {
+     *   return num % 2 == 0;
+     * });
+     * // => 2
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'banana', 'organic': true,  'type': 'fruit' },
+     *   { 'name': 'beet',   'organic': false, 'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.find(food, { 'type': 'vegetable' });
+     * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
+     *
+     * // using "_.pluck" callback shorthand
+     * _.find(food, 'organic');
+     * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' }
+     */
+    function find(collection, callback, thisArg) {
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          var value = collection[index];
+          if (callback(value, index, collection)) {
+            return value;
+          }
+        }
+      } else {
+        var result;
+        forOwn(collection, function(value, index, collection) {
+          if (callback(value, index, collection)) {
+            result = value;
+            return false;
+          }
+        });
+        return result;
+      }
+    }
+
+    /**
+     * This method is like `_.find` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the found element, else `undefined`.
+     * @example
+     *
+     * _.findLast([1, 2, 3, 4], function(num) {
+     *   return num % 2 == 1;
+     * });
+     * // => 3
+     */
+    function findLast(collection, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forEachRight(collection, function(value, index, collection) {
+        if (callback(value, index, collection)) {
+          result = value;
+          return false;
+        }
+      });
+      return result;
+    }
+
+    /**
+     * Iterates over elements of a collection, executing the callback for each
+     * element. The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection). Callbacks may exit iteration early by
+     * explicitly returning `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias each
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array|Object|string} Returns `collection`.
+     * @example
+     *
+     * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
+     * // => logs each number and returns '1,2,3'
+     *
+     * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
+     * // => logs each number and returns the object (property order is not guaranteed across environments)
+     */
+    function forEach(collection, callback, thisArg) {
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+      if (typeof length == 'number') {
+        while (++index < length) {
+          if (callback(collection[index], index, collection) === false) {
+            break;
+          }
+        }
+      } else {
+        forOwn(collection, callback);
+      }
+      return collection;
+    }
+
+    /**
+     * This method is like `_.forEach` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @alias eachRight
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array|Object|string} Returns `collection`.
+     * @example
+     *
+     * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
+     * // => logs each number from right to left and returns '3,2,1'
+     */
+    function forEachRight(collection, callback, thisArg) {
+      var length = collection ? collection.length : 0;
+      callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+      if (typeof length == 'number') {
+        while (length--) {
+          if (callback(collection[length], length, collection) === false) {
+            break;
+          }
+        }
+      } else {
+        var props = keys(collection);
+        length = props.length;
+        forOwn(collection, function(value, key, collection) {
+          key = props ? props[--length] : --length;
+          return callback(collection[key], key, collection);
+        });
+      }
+      return collection;
+    }
+
+    /**
+     * Creates an object composed of keys generated from the results of running
+     * each element of a collection through the callback. The corresponding value
+     * of each key is an array of the elements responsible for generating the key.
+     * The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the composed aggregate object.
+     * @example
+     *
+     * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
+     * // => { '4': [4.2], '6': [6.1, 6.4] }
+     *
+     * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
+     * // => { '4': [4.2], '6': [6.1, 6.4] }
+     *
+     * // using "_.pluck" callback shorthand
+     * _.groupBy(['one', 'two', 'three'], 'length');
+     * // => { '3': ['one', 'two'], '5': ['three'] }
+     */
+    var groupBy = createAggregator(function(result, value, key) {
+      (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
+    });
+
+    /**
+     * Creates an object composed of keys generated from the results of running
+     * each element of the collection through the given callback. The corresponding
+     * value of each key is the last element responsible for generating the key.
+     * The callback is bound to `thisArg` and invoked with three arguments;
+     * (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Object} Returns the composed aggregate object.
+     * @example
+     *
+     * var keys = [
+     *   { 'dir': 'left', 'code': 97 },
+     *   { 'dir': 'right', 'code': 100 }
+     * ];
+     *
+     * _.indexBy(keys, 'dir');
+     * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
+     *
+     * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
+     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
+     *
+     * _.indexBy(stooges, function(key) { this.fromCharCode(key.code); }, String);
+     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
+     */
+    var indexBy = createAggregator(function(result, value, key) {
+      result[key] = value;
+    });
+
+    /**
+     * Invokes the method named by `methodName` on each element in the `collection`
+     * returning an array of the results of each invoked method. Additional arguments
+     * will be provided to each invoked method. If `methodName` is a function it
+     * will be invoked for, and `this` bound to, each element in the `collection`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|string} methodName The name of the method to invoke or
+     *  the function invoked per iteration.
+     * @param {...*} [arg] Arguments to invoke the method with.
+     * @returns {Array} Returns a new array of the results of each invoked method.
+     * @example
+     *
+     * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
+     * // => [[1, 5, 7], [1, 2, 3]]
+     *
+     * _.invoke([123, 456], String.prototype.split, '');
+     * // => [['1', '2', '3'], ['4', '5', '6']]
+     */
+    function invoke(collection, methodName) {
+      var args = nativeSlice.call(arguments, 2),
+          index = -1,
+          isFunc = typeof methodName == 'function',
+          length = collection ? collection.length : 0,
+          result = Array(typeof length == 'number' ? length : 0);
+
+      forEach(collection, function(value) {
+        result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
+      });
+      return result;
+    }
+
+    /**
+     * Creates an array of values by running each element in the collection
+     * through the callback. The callback is bound to `thisArg` and invoked with
+     * three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias collect
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of the results of each `callback` execution.
+     * @example
+     *
+     * _.map([1, 2, 3], function(num) { return num * 3; });
+     * // => [3, 6, 9]
+     *
+     * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
+     * // => [3, 6, 9] (property order is not guaranteed across environments)
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.map(stooges, 'name');
+     * // => ['moe', 'larry']
+     */
+    function map(collection, callback, thisArg) {
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      if (typeof length == 'number') {
+        var result = Array(length);
+        while (++index < length) {
+          result[index] = callback(collection[index], index, collection);
+        }
+      } else {
+        result = [];
+        forOwn(collection, function(value, key, collection) {
+          result[++index] = callback(value, key, collection);
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Retrieves the maximum value of a collection. If the collection is empty or
+     * falsey `-Infinity` is returned. If a callback is provided it will be executed
+     * for each value in the collection to generate the criterion by which the value
+     * is ranked. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the maximum value.
+     * @example
+     *
+     * _.max([4, 2, 8, 6]);
+     * // => 8
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * _.max(stooges, function(stooge) { return stooge.age; });
+     * // => { 'name': 'larry', 'age': 50 };
+     *
+     * // using "_.pluck" callback shorthand
+     * _.max(stooges, 'age');
+     * // => { 'name': 'larry', 'age': 50 };
+     */
+    function max(collection, callback, thisArg) {
+      var computed = -Infinity,
+          result = computed;
+
+      if (!callback && isArray(collection)) {
+        var index = -1,
+            length = collection.length;
+
+        while (++index < length) {
+          var value = collection[index];
+          if (value > result) {
+            result = value;
+          }
+        }
+      } else {
+        callback = (!callback && isString(collection))
+          ? charAtCallback
+          : lodash.createCallback(callback, thisArg, 3);
+
+        forEach(collection, function(value, index, collection) {
+          var current = callback(value, index, collection);
+          if (current > computed) {
+            computed = current;
+            result = value;
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Retrieves the minimum value of a collection. If the collection is empty or
+     * falsey `Infinity` is returned. If a callback is provided it will be executed
+     * for each value in the collection to generate the criterion by which the value
+     * is ranked. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the minimum value.
+     * @example
+     *
+     * _.min([4, 2, 8, 6]);
+     * // => 2
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * _.min(stooges, function(stooge) { return stooge.age; });
+     * // => { 'name': 'moe', 'age': 40 };
+     *
+     * // using "_.pluck" callback shorthand
+     * _.min(stooges, 'age');
+     * // => { 'name': 'moe', 'age': 40 };
+     */
+    function min(collection, callback, thisArg) {
+      var computed = Infinity,
+          result = computed;
+
+      if (!callback && isArray(collection)) {
+        var index = -1,
+            length = collection.length;
+
+        while (++index < length) {
+          var value = collection[index];
+          if (value < result) {
+            result = value;
+          }
+        }
+      } else {
+        callback = (!callback && isString(collection))
+          ? charAtCallback
+          : lodash.createCallback(callback, thisArg, 3);
+
+        forEach(collection, function(value, index, collection) {
+          var current = callback(value, index, collection);
+          if (current < computed) {
+            computed = current;
+            result = value;
+          }
+        });
+      }
+      return result;
+    }
+
+    /**
+     * Retrieves the value of a specified property from all elements in the `collection`.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {string} property The property to pluck.
+     * @returns {Array} Returns a new array of property values.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * _.pluck(stooges, 'name');
+     * // => ['moe', 'larry']
+     */
+    function pluck(collection, property) {
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        var result = Array(length);
+        while (++index < length) {
+          result[index] = collection[index][property];
+        }
+      }
+      return result || map(collection, property);
+    }
+
+    /**
+     * Reduces a collection to a value which is the accumulated result of running
+     * each element in the collection through the callback, where each successive
+     * callback execution consumes the return value of the previous execution. If
+     * `accumulator` is not provided the first element of the collection will be
+     * used as the initial `accumulator` value. The callback is bound to `thisArg`
+     * and invoked with four arguments; (accumulator, value, index|key, collection).
+     *
+     * @static
+     * @memberOf _
+     * @alias foldl, inject
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [accumulator] Initial value of the accumulator.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the accumulated value.
+     * @example
+     *
+     * var sum = _.reduce([1, 2, 3], function(sum, num) {
+     *   return sum + num;
+     * });
+     * // => 6
+     *
+     * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
+     *   result[key] = num * 3;
+     *   return result;
+     * }, {});
+     * // => { 'a': 3, 'b': 6, 'c': 9 }
+     */
+    function reduce(collection, callback, accumulator, thisArg) {
+      if (!collection) return accumulator;
+      var noaccum = arguments.length < 3;
+      callback = baseCreateCallback(callback, thisArg, 4);
+
+      var index = -1,
+          length = collection.length;
+
+      if (typeof length == 'number') {
+        if (noaccum) {
+          accumulator = collection[++index];
+        }
+        while (++index < length) {
+          accumulator = callback(accumulator, collection[index], index, collection);
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          accumulator = noaccum
+            ? (noaccum = false, value)
+            : callback(accumulator, value, index, collection)
+        });
+      }
+      return accumulator;
+    }
+
+    /**
+     * This method is like `_.reduce` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @alias foldr
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function} [callback=identity] The function called per iteration.
+     * @param {*} [accumulator] Initial value of the accumulator.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the accumulated value.
+     * @example
+     *
+     * var list = [[0, 1], [2, 3], [4, 5]];
+     * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
+     * // => [4, 5, 2, 3, 0, 1]
+     */
+    function reduceRight(collection, callback, accumulator, thisArg) {
+      var noaccum = arguments.length < 3;
+      callback = baseCreateCallback(callback, thisArg, 4);
+      forEachRight(collection, function(value, index, collection) {
+        accumulator = noaccum
+          ? (noaccum = false, value)
+          : callback(accumulator, value, index, collection);
+      });
+      return accumulator;
+    }
+
+    /**
+     * The opposite of `_.filter` this method returns the elements of a
+     * collection that the callback does **not** return truey for.
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of elements that failed the callback check.
+     * @example
+     *
+     * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
+     * // => [1, 3, 5]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.reject(food, 'organic');
+     * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
+     *
+     * // using "_.where" callback shorthand
+     * _.reject(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
+     */
+    function reject(collection, callback, thisArg) {
+      callback = lodash.createCallback(callback, thisArg, 3);
+      return filter(collection, function(value, index, collection) {
+        return !callback(value, index, collection);
+      });
+    }
+
+    /**
+     * Retrieves a random element or `n` random elements from a collection.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to sample.
+     * @param {number} [n] The number of elements to sample.
+     * @param- {Object} [guard] Allows working with functions, like `_.map`,
+     *  without using their `key` and `object` arguments as sources.
+     * @returns {Array} Returns the random sample(s) of `collection`.
+     * @example
+     *
+     * _.sample([1, 2, 3, 4]);
+     * // => 2
+     *
+     * _.sample([1, 2, 3, 4], 2);
+     * // => [3, 1]
+     */
+    function sample(collection, n, guard) {
+      var length = collection ? collection.length : 0;
+      if (typeof length != 'number') {
+        collection = values(collection);
+      }
+      if (n == null || guard) {
+        return collection ? collection[random(length - 1)] : undefined;
+      }
+      var result = shuffle(collection);
+      result.length = nativeMin(nativeMax(0, n), result.length);
+      return result;
+    }
+
+    /**
+     * Creates an array of shuffled values, using a version of the Fisher-Yates
+     * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to shuffle.
+     * @returns {Array} Returns a new shuffled collection.
+     * @example
+     *
+     * _.shuffle([1, 2, 3, 4, 5, 6]);
+     * // => [4, 1, 6, 3, 5, 2]
+     */
+    function shuffle(collection) {
+      var index = -1,
+          length = collection ? collection.length : 0,
+          result = Array(typeof length == 'number' ? length : 0);
+
+      forEach(collection, function(value) {
+        var rand = random(++index);
+        result[index] = result[rand];
+        result[rand] = value;
+      });
+      return result;
+    }
+
+    /**
+     * Gets the size of the `collection` by returning `collection.length` for arrays
+     * and array-like objects or the number of own enumerable properties for objects.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to inspect.
+     * @returns {number} Returns `collection.length` or number of own enumerable properties.
+     * @example
+     *
+     * _.size([1, 2]);
+     * // => 2
+     *
+     * _.size({ 'one': 1, 'two': 2, 'three': 3 });
+     * // => 3
+     *
+     * _.size('curly');
+     * // => 5
+     */
+    function size(collection) {
+      var length = collection ? collection.length : 0;
+      return typeof length == 'number' ? length : keys(collection).length;
+    }
+
+    /**
+     * Checks if the callback returns a truey value for **any** element of a
+     * collection. The function returns as soon as it finds a passing value and
+     * does not iterate over the entire collection. The callback is bound to
+     * `thisArg` and invoked with three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias any
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {boolean} Returns `true` if any element passed the callback check,
+     *  else `false`.
+     * @example
+     *
+     * _.some([null, 0, 'yes', false], Boolean);
+     * // => true
+     *
+     * var food = [
+     *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
+     *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.some(food, 'organic');
+     * // => true
+     *
+     * // using "_.where" callback shorthand
+     * _.some(food, { 'type': 'meat' });
+     * // => false
+     */
+    function some(collection, callback, thisArg) {
+      var result;
+      callback = lodash.createCallback(callback, thisArg, 3);
+
+      var index = -1,
+          length = collection ? collection.length : 0;
+
+      if (typeof length == 'number') {
+        while (++index < length) {
+          if ((result = callback(collection[index], index, collection))) {
+            break;
+          }
+        }
+      } else {
+        forOwn(collection, function(value, index, collection) {
+          return !(result = callback(value, index, collection));
+        });
+      }
+      return !!result;
+    }
+
+    /**
+     * Creates an array of elements, sorted in ascending order by the results of
+     * running each element in a collection through the callback. This method
+     * performs a stable sort, that is, it will preserve the original sort order
+     * of equal elements. The callback is bound to `thisArg` and invoked with
+     * three arguments; (value, index|key, collection).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of sorted elements.
+     * @example
+     *
+     * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
+     * // => [3, 1, 2]
+     *
+     * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
+     * // => [3, 1, 2]
+     *
+     * // using "_.pluck" callback shorthand
+     * _.sortBy(['banana', 'strawberry', 'apple'], 'length');
+     * // => ['apple', 'banana', 'strawberry']
+     */
+    function sortBy(collection, callback, thisArg) {
+      var index = -1,
+          length = collection ? collection.length : 0,
+          result = Array(typeof length == 'number' ? length : 0);
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      forEach(collection, function(value, key, collection) {
+        var object = result[++index] = getObject();
+        object.criteria = callback(value, key, collection);
+        object.index = index;
+        object.value = value;
+      });
+
+      length = result.length;
+      result.sort(compareAscending);
+      while (length--) {
+        var object = result[length];
+        result[length] = object.value;
+        releaseObject(object);
+      }
+      return result;
+    }
+
+    /**
+     * Converts the `collection` to an array.
+     *
+     * @static
+     * @memberOf _
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to convert.
+     * @returns {Array} Returns the new converted array.
+     * @example
+     *
+     * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
+     * // => [2, 3, 4]
+     */
+    function toArray(collection) {
+      if (collection && typeof collection.length == 'number') {
+        return slice(collection);
+      }
+      return values(collection);
+    }
+
+    /**
+     * Performs a deep comparison of each element in a `collection` to the given
+     * `properties` object, returning an array of all elements that have equivalent
+     * property values.
+     *
+     * @static
+     * @memberOf _
+     * @type Function
+     * @category Collections
+     * @param {Array|Object|string} collection The collection to iterate over.
+     * @param {Object} properties The object of property values to filter by.
+     * @returns {Array} Returns a new array of elements that have the given properties.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
+     *   { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }
+     * ];
+     *
+     * _.where(stooges, { 'age': 40 });
+     * // => [{ 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }]
+     *
+     * _.where(stooges, { 'quotes': ['Poifect!'] });
+     * // => [{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }]
+     */
+    var where = filter;
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates an array with all falsey values removed. The values `false`, `null`,
+     * `0`, `""`, `undefined`, and `NaN` are all falsey.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to compact.
+     * @returns {Array} Returns a new array of filtered values.
+     * @example
+     *
+     * _.compact([0, 1, false, 2, '', 3]);
+     * // => [1, 2, 3]
+     */
+    function compact(array) {
+      var index = -1,
+          length = array ? array.length : 0,
+          result = [];
+
+      while (++index < length) {
+        var value = array[index];
+        if (value) {
+          result.push(value);
+        }
+      }
+      return result;
+    }
+
+    /**
+     * Creates an array excluding all values of the provided arrays using strict
+     * equality for comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to process.
+     * @param {...Array} [array] The arrays of values to exclude.
+     * @returns {Array} Returns a new array of filtered values.
+     * @example
+     *
+     * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
+     * // => [1, 3, 4]
+     */
+    function difference(array) {
+      var index = -1,
+          indexOf = getIndexOf(),
+          length = array ? array.length : 0,
+          seen = baseFlatten(arguments, true, true, 1),
+          result = [];
+
+      var isLarge = length >= largeArraySize && indexOf === baseIndexOf;
+
+      if (isLarge) {
+        var cache = createCache(seen);
+        if (cache) {
+          indexOf = cacheIndexOf;
+          seen = cache;
+        } else {
+          isLarge = false;
+        }
+      }
+      while (++index < length) {
+        var value = array[index];
+        if (indexOf(seen, value) < 0) {
+          result.push(value);
+        }
+      }
+      if (isLarge) {
+        releaseObject(seen);
+      }
+      return result;
+    }
+
+    /**
+     * This method is like `_.find` except that it returns the index of the first
+     * element that passes the callback check, instead of the element itself.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {number} Returns the index of the found element, else `-1`.
+     * @example
+     *
+     * _.findIndex(['apple', 'banana', 'beet'], function(food) {
+     *   return /^b/.test(food);
+     * });
+     * // => 1
+     */
+    function findIndex(array, callback, thisArg) {
+      var index = -1,
+          length = array ? array.length : 0;
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      while (++index < length) {
+        if (callback(array[index], index, array)) {
+          return index;
+        }
+      }
+      return -1;
+    }
+
+    /**
+     * This method is like `_.findIndex` except that it iterates over elements
+     * of a `collection` from right to left.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {number} Returns the index of the found element, else `-1`.
+     * @example
+     *
+     * _.findLastIndex(['apple', 'banana', 'beet'], function(food) {
+     *   return /^b/.test(food);
+     * });
+     * // => 2
+     */
+    function findLastIndex(array, callback, thisArg) {
+      var length = array ? array.length : 0;
+      callback = lodash.createCallback(callback, thisArg, 3);
+      while (length--) {
+        if (callback(array[length], length, array)) {
+          return length;
+        }
+      }
+      return -1;
+    }
+
+    /**
+     * Gets the first element or first `n` elements of an array. If a callback
+     * is provided elements at the beginning of the array are returned as long
+     * as the callback returns truey. The callback is bound to `thisArg` and
+     * invoked with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias head, take
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback] The function called
+     *  per element or the number of elements to return. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the first element(s) of `array`.
+     * @example
+     *
+     * _.first([1, 2, 3]);
+     * // => 1
+     *
+     * _.first([1, 2, 3], 2);
+     * // => [1, 2]
+     *
+     * _.first([1, 2, 3], function(num) {
+     *   return num < 3;
+     * });
+     * // => [1, 2]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'organic': true },
+     *   { 'name': 'beet',   'organic': false },
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.first(food, 'organic');
+     * // => [{ 'name': 'banana', 'organic': true }]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'type': 'fruit' },
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.first(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }]
+     */
+    function first(array, callback, thisArg) {
+      var n = 0,
+          length = array ? array.length : 0;
+
+      if (typeof callback != 'number' && callback != null) {
+        var index = -1;
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (++index < length && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = callback;
+        if (n == null || thisArg) {
+          return array ? array[0] : undefined;
+        }
+      }
+      return slice(array, 0, nativeMin(nativeMax(0, n), length));
+    }
+
+    /**
+     * Flattens a nested array (the nesting can be to any depth). If `isShallow`
+     * is truey, the array will only be flattened a single level. If a callback
+     * is provided each element of the array is passed through the callback before
+     * flattening. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to flatten.
+     * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new flattened array.
+     * @example
+     *
+     * _.flatten([1, [2], [3, [[4]]]]);
+     * // => [1, 2, 3, 4];
+     *
+     * _.flatten([1, [2], [3, [[4]]]], true);
+     * // => [1, 2, 3, [[4]]];
+     *
+     * var stooges = [
+     *   { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
+     *   { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.flatten(stooges, 'quotes');
+     * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!']
+     */
+    function flatten(array, isShallow, callback, thisArg) {
+      // juggle arguments
+      if (typeof isShallow != 'boolean' && isShallow != null) {
+        thisArg = callback;
+        callback = !(thisArg && thisArg[isShallow] === array) ? isShallow : null;
+        isShallow = false;
+      }
+      if (callback != null) {
+        array = map(array, callback, thisArg);
+      }
+      return baseFlatten(array, isShallow);
+    }
+
+    /**
+     * Gets the index at which the first occurrence of `value` is found using
+     * strict equality for comparisons, i.e. `===`. If the array is already sorted
+     * providing `true` for `fromIndex` will run a faster binary search.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {*} value The value to search for.
+     * @param {boolean|number} [fromIndex=0] The index to search from or `true`
+     *  to perform a binary search on a sorted array.
+     * @returns {number} Returns the index of the matched value or `-1`.
+     * @example
+     *
+     * _.indexOf([1, 2, 3, 1, 2, 3], 2);
+     * // => 1
+     *
+     * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
+     * // => 4
+     *
+     * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
+     * // => 2
+     */
+    function indexOf(array, value, fromIndex) {
+      if (typeof fromIndex == 'number') {
+        var length = array ? array.length : 0;
+        fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
+      } else if (fromIndex) {
+        var index = sortedIndex(array, value);
+        return array[index] === value ? index : -1;
+      }
+      return baseIndexOf(array, value, fromIndex);
+    }
+
+    /**
+     * Gets all but the last element or last `n` elements of an array. If a
+     * callback is provided elements at the end of the array are excluded from
+     * the result as long as the callback returns truey. The callback is bound
+     * to `thisArg` and invoked with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback=1] The function called
+     *  per element or the number of elements to exclude. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a slice of `array`.
+     * @example
+     *
+     * _.initial([1, 2, 3]);
+     * // => [1, 2]
+     *
+     * _.initial([1, 2, 3], 2);
+     * // => [1]
+     *
+     * _.initial([1, 2, 3], function(num) {
+     *   return num > 1;
+     * });
+     * // => [1]
+     *
+     * var food = [
+     *   { 'name': 'beet',   'organic': false },
+     *   { 'name': 'carrot', 'organic': true }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.initial(food, 'organic');
+     * // => [{ 'name': 'beet',   'organic': false }]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' },
+     *   { 'name': 'carrot', 'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.initial(food, { 'type': 'vegetable' });
+     * // => [{ 'name': 'banana', 'type': 'fruit' }]
+     */
+    function initial(array, callback, thisArg) {
+      var n = 0,
+          length = array ? array.length : 0;
+
+      if (typeof callback != 'number' && callback != null) {
+        var index = length;
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (index-- && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = (callback == null || thisArg) ? 1 : callback || n;
+      }
+      return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
+    }
+
+    /**
+     * Creates an array of unique values present in all provided arrays using
+     * strict equality for comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {...Array} [array] The arrays to inspect.
+     * @returns {Array} Returns an array of composite values.
+     * @example
+     *
+     * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
+     * // => [1, 2]
+     */
+    function intersection(array) {
+      var args = arguments,
+          argsLength = args.length,
+          argsIndex = -1,
+          caches = getArray(),
+          index = -1,
+          indexOf = getIndexOf(),
+          length = array ? array.length : 0,
+          result = [],
+          seen = getArray();
+
+      while (++argsIndex < argsLength) {
+        var value = args[argsIndex];
+        caches[argsIndex] = indexOf === baseIndexOf &&
+          (value ? value.length : 0) >= largeArraySize &&
+          createCache(argsIndex ? args[argsIndex] : seen);
+      }
+      outer:
+      while (++index < length) {
+        var cache = caches[0];
+        value = array[index];
+
+        if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
+          argsIndex = argsLength;
+          (cache || seen).push(value);
+          while (--argsIndex) {
+            cache = caches[argsIndex];
+            if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
+              continue outer;
+            }
+          }
+          result.push(value);
+        }
+      }
+      while (argsLength--) {
+        cache = caches[argsLength];
+        if (cache) {
+          releaseObject(cache);
+        }
+      }
+      releaseArray(caches);
+      releaseArray(seen);
+      return result;
+    }
+
+    /**
+     * Gets the last element or last `n` elements of an array. If a callback is
+     * provided elements at the end of the array are returned as long as the
+     * callback returns truey. The callback is bound to `thisArg` and invoked
+     * with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback] The function called
+     *  per element or the number of elements to return. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {*} Returns the last element(s) of `array`.
+     * @example
+     *
+     * _.last([1, 2, 3]);
+     * // => 3
+     *
+     * _.last([1, 2, 3], 2);
+     * // => [2, 3]
+     *
+     * _.last([1, 2, 3], function(num) {
+     *   return num > 1;
+     * });
+     * // => [2, 3]
+     *
+     * var food = [
+     *   { 'name': 'beet',   'organic': false },
+     *   { 'name': 'carrot', 'organic': true }
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.last(food, 'organic');
+     * // => [{ 'name': 'carrot', 'organic': true }]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' },
+     *   { 'name': 'carrot', 'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.last(food, { 'type': 'vegetable' });
+     * // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }]
+     */
+    function last(array, callback, thisArg) {
+      var n = 0,
+          length = array ? array.length : 0;
+
+      if (typeof callback != 'number' && callback != null) {
+        var index = length;
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (index-- && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = callback;
+        if (n == null || thisArg) {
+          return array ? array[length - 1] : undefined;
+        }
+      }
+      return slice(array, nativeMax(0, length - n));
+    }
+
+    /**
+     * Gets the index at which the last occurrence of `value` is found using strict
+     * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
+     * as the offset from the end of the collection.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to search.
+     * @param {*} value The value to search for.
+     * @param {number} [fromIndex=array.length-1] The index to search from.
+     * @returns {number} Returns the index of the matched value or `-1`.
+     * @example
+     *
+     * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
+     * // => 4
+     *
+     * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
+     * // => 1
+     */
+    function lastIndexOf(array, value, fromIndex) {
+      var index = array ? array.length : 0;
+      if (typeof fromIndex == 'number') {
+        index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
+      }
+      while (index--) {
+        if (array[index] === value) {
+          return index;
+        }
+      }
+      return -1;
+    }
+
+    /**
+     * Removes all provided values from the given array using strict equality for
+     * comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to modify.
+     * @param {...*} [value] The values to remove.
+     * @returns {Array} Returns `array`.
+     * @example
+     *
+     * var array = [1, 2, 3, 1, 2, 3];
+     * _.pull(array, 2, 3);
+     * console.log(array);
+     * // => [1, 1]
+     */
+    function pull(array) {
+      var args = arguments,
+          argsIndex = 0,
+          argsLength = args.length,
+          length = array ? array.length : 0;
+
+      while (++argsIndex < argsLength) {
+        var index = -1,
+            value = args[argsIndex];
+        while (++index < length) {
+          if (array[index] === value) {
+            splice.call(array, index--, 1);
+            length--;
+          }
+        }
+      }
+      return array;
+    }
+
+    /**
+     * Creates an array of numbers (positive and/or negative) progressing from
+     * `start` up to but not including `end`. If `start` is less than `stop` a
+     * zero-length range is created unless a negative `step` is specified.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {number} [start=0] The start of the range.
+     * @param {number} end The end of the range.
+     * @param {number} [step=1] The value to increment or decrement by.
+     * @returns {Array} Returns a new range array.
+     * @example
+     *
+     * _.range(10);
+     * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+     *
+     * _.range(1, 11);
+     * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+     *
+     * _.range(0, 30, 5);
+     * // => [0, 5, 10, 15, 20, 25]
+     *
+     * _.range(0, -10, -1);
+     * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
+     *
+     * _.range(1, 4, 0);
+     * // => [1, 1, 1]
+     *
+     * _.range(0);
+     * // => []
+     */
+    function range(start, end, step) {
+      start = +start || 0;
+      step = typeof step == 'number' ? step : (+step || 1);
+
+      if (end == null) {
+        end = start;
+        start = 0;
+      }
+      // use `Array(length)` so engines, like Chakra and V8, avoid slower modes
+      // http://youtu.be/XAqIpGU8ZZk#t=17m25s
+      var index = -1,
+          length = nativeMax(0, ceil((end - start) / (step || 1))),
+          result = Array(length);
+
+      while (++index < length) {
+        result[index] = start;
+        start += step;
+      }
+      return result;
+    }
+
+    /**
+     * Removes all elements from an array that the callback returns truey for
+     * and returns an array of removed elements. The callback is bound to `thisArg`
+     * and invoked with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to modify.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a new array of removed elements.
+     * @example
+     *
+     * var array = [1, 2, 3, 4, 5, 6];
+     * var evens = _.remove(array, function(num) { return num % 2 == 0; });
+     *
+     * console.log(array);
+     * // => [1, 3, 5]
+     *
+     * console.log(evens);
+     * // => [2, 4, 6]
+     */
+    function remove(array, callback, thisArg) {
+      var index = -1,
+          length = array ? array.length : 0,
+          result = [];
+
+      callback = lodash.createCallback(callback, thisArg, 3);
+      while (++index < length) {
+        var value = array[index];
+        if (callback(value, index, array)) {
+          result.push(value);
+          splice.call(array, index--, 1);
+          length--;
+        }
+      }
+      return result;
+    }
+
+    /**
+     * The opposite of `_.initial` this method gets all but the first element or
+     * first `n` elements of an array. If a callback function is provided elements
+     * at the beginning of the array are excluded from the result as long as the
+     * callback returns truey. The callback is bound to `thisArg` and invoked
+     * with three arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias drop, tail
+     * @category Arrays
+     * @param {Array} array The array to query.
+     * @param {Function|Object|number|string} [callback=1] The function called
+     *  per element or the number of elements to exclude. If a property name or
+     *  object is provided it will be used to create a "_.pluck" or "_.where"
+     *  style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a slice of `array`.
+     * @example
+     *
+     * _.rest([1, 2, 3]);
+     * // => [2, 3]
+     *
+     * _.rest([1, 2, 3], 2);
+     * // => [3]
+     *
+     * _.rest([1, 2, 3], function(num) {
+     *   return num < 3;
+     * });
+     * // => [3]
+     *
+     * var food = [
+     *   { 'name': 'banana', 'organic': true },
+     *   { 'name': 'beet',   'organic': false },
+     * ];
+     *
+     * // using "_.pluck" callback shorthand
+     * _.rest(food, 'organic');
+     * // => [{ 'name': 'beet', 'organic': false }]
+     *
+     * var food = [
+     *   { 'name': 'apple',  'type': 'fruit' },
+     *   { 'name': 'banana', 'type': 'fruit' },
+     *   { 'name': 'beet',   'type': 'vegetable' }
+     * ];
+     *
+     * // using "_.where" callback shorthand
+     * _.rest(food, { 'type': 'fruit' });
+     * // => [{ 'name': 'beet', 'type': 'vegetable' }]
+     */
+    function rest(array, callback, thisArg) {
+      if (typeof callback != 'number' && callback != null) {
+        var n = 0,
+            index = -1,
+            length = array ? array.length : 0;
+
+        callback = lodash.createCallback(callback, thisArg, 3);
+        while (++index < length && callback(array[index], index, array)) {
+          n++;
+        }
+      } else {
+        n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
+      }
+      return slice(array, n);
+    }
+
+    /**
+     * Uses a binary search to determine the smallest index at which a value
+     * should be inserted into a given sorted array in order to maintain the sort
+     * order of the array. If a callback is provided it will be executed for
+     * `value` and each element of `array` to compute their sort ranking. The
+     * callback is bound to `thisArg` and invoked with one argument; (value).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to inspect.
+     * @param {*} value The value to evaluate.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {number} Returns the index at which `value` should be inserted
+     *  into `array`.
+     * @example
+     *
+     * _.sortedIndex([20, 30, 50], 40);
+     * // => 2
+     *
+     * // using "_.pluck" callback shorthand
+     * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
+     * // => 2
+     *
+     * var dict = {
+     *   'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
+     * };
+     *
+     * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
+     *   return dict.wordToNumber[word];
+     * });
+     * // => 2
+     *
+     * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
+     *   return this.wordToNumber[word];
+     * }, dict);
+     * // => 2
+     */
+    function sortedIndex(array, value, callback, thisArg) {
+      var low = 0,
+          high = array ? array.length : low;
+
+      // explicitly reference `identity` for better inlining in Firefox
+      callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
+      value = callback(value);
+
+      while (low < high) {
+        var mid = (low + high) >>> 1;
+        (callback(array[mid]) < value)
+          ? low = mid + 1
+          : high = mid;
+      }
+      return low;
+    }
+
+    /**
+     * Creates an array of unique values, in order, of the provided arrays using
+     * strict equality for comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {...Array} [array] The arrays to inspect.
+     * @returns {Array} Returns an array of composite values.
+     * @example
+     *
+     * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
+     * // => [1, 2, 3, 101, 10]
+     */
+    function union(array) {
+      return baseUniq(baseFlatten(arguments, true, true));
+    }
+
+    /**
+     * Creates a duplicate-value-free version of an array using strict equality
+     * for comparisons, i.e. `===`. If the array is sorted, providing
+     * `true` for `isSorted` will use a faster algorithm. If a callback is provided
+     * each element of `array` is passed through the callback before uniqueness
+     * is computed. The callback is bound to `thisArg` and invoked with three
+     * arguments; (value, index, array).
+     *
+     * If a property name is provided for `callback` the created "_.pluck" style
+     * callback will return the property value of the given element.
+     *
+     * If an object is provided for `callback` the created "_.where" style callback
+     * will return `true` for elements that have the properties of the given object,
+     * else `false`.
+     *
+     * @static
+     * @memberOf _
+     * @alias unique
+     * @category Arrays
+     * @param {Array} array The array to process.
+     * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
+     * @param {Function|Object|string} [callback=identity] The function called
+     *  per iteration. If a property name or object is provided it will be used
+     *  to create a "_.pluck" or "_.where" style callback, respectively.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns a duplicate-value-free array.
+     * @example
+     *
+     * _.uniq([1, 2, 1, 3, 1]);
+     * // => [1, 2, 3]
+     *
+     * _.uniq([1, 1, 2, 2, 3], true);
+     * // => [1, 2, 3]
+     *
+     * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
+     * // => ['A', 'b', 'C']
+     *
+     * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
+     * // => [1, 2.5, 3]
+     *
+     * // using "_.pluck" callback shorthand
+     * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
+     * // => [{ 'x': 1 }, { 'x': 2 }]
+     */
+    function uniq(array, isSorted, callback, thisArg) {
+      // juggle arguments
+      if (typeof isSorted != 'boolean' && isSorted != null) {
+        thisArg = callback;
+        callback = !(thisArg && thisArg[isSorted] === array) ? isSorted : null;
+        isSorted = false;
+      }
+      if (callback != null) {
+        callback = lodash.createCallback(callback, thisArg, 3);
+      }
+      return baseUniq(array, isSorted, callback);
+    }
+
+    /**
+     * Creates an array excluding all provided values using strict equality for
+     * comparisons, i.e. `===`.
+     *
+     * @static
+     * @memberOf _
+     * @category Arrays
+     * @param {Array} array The array to filter.
+     * @param {...*} [value] The values to exclude.
+     * @returns {Array} Returns a new array of filtered values.
+     * @example
+     *
+     * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
+     * // => [2, 3, 4]
+     */
+    function without(array) {
+      return difference(array, nativeSlice.call(arguments, 1));
+    }
+
+    /**
+     * Creates an array of grouped elements, the first of which contains the first
+     * elements of the given arrays, the second of which contains the second
+     * elements of the given arrays, and so on.
+     *
+     * @static
+     * @memberOf _
+     * @alias unzip
+     * @category Arrays
+     * @param {...Array} [array] Arrays to process.
+     * @returns {Array} Returns a new array of grouped elements.
+     * @example
+     *
+     * _.zip(['moe', 'larry'], [30, 40], [true, false]);
+     * // => [['moe', 30, true], ['larry', 40, false]]
+     */
+    function zip() {
+      var array = arguments.length > 1 ? arguments : arguments[0],
+          index = -1,
+          length = array ? max(pluck(array, 'length')) : 0,
+          result = Array(length < 0 ? 0 : length);
+
+      while (++index < length) {
+        result[index] = pluck(array, index);
+      }
+      return result;
+    }
+
+    /**
+     * Creates an object composed from arrays of `keys` and `values`. Provide
+     * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
+     * or two arrays, one of `keys` and one of corresponding `values`.
+     *
+     * @static
+     * @memberOf _
+     * @alias object
+     * @category Arrays
+     * @param {Array} keys The array of keys.
+     * @param {Array} [values=[]] The array of values.
+     * @returns {Object} Returns an object composed of the given keys and
+     *  corresponding values.
+     * @example
+     *
+     * _.zipObject(['moe', 'larry'], [30, 40]);
+     * // => { 'moe': 30, 'larry': 40 }
+     */
+    function zipObject(keys, values) {
+      var index = -1,
+          length = keys ? keys.length : 0,
+          result = {};
+
+      while (++index < length) {
+        var key = keys[index];
+        if (values) {
+          result[key] = values[index];
+        } else if (key) {
+          result[key[0]] = key[1];
+        }
+      }
+      return result;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates a function that executes `func`, with  the `this` binding and
+     * arguments of the created function, only after being called `n` times.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {number} n The number of times the function must be called before
+     *  `func` is executed.
+     * @param {Function} func The function to restrict.
+     * @returns {Function} Returns the new restricted function.
+     * @example
+     *
+     * var saves = ['profile', 'settings'];
+     *
+     * var done = _.after(saves.length, function() {
+     *   console.log('Done saving!');
+     * });
+     *
+     * _.forEach(saves, function(type) {
+     *   asyncSave({ 'type': type, 'complete': done });
+     * });
+     * // => logs 'Done saving!', after all saves have completed
+     */
+    function after(n, func) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      return function() {
+        if (--n < 1) {
+          return func.apply(this, arguments);
+        }
+      };
+    }
+
+    /**
+     * Creates a function that, when called, invokes `func` with the `this`
+     * binding of `thisArg` and prepends any additional `bind` arguments to those
+     * provided to the bound function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to bind.
+     * @param {*} [thisArg] The `this` binding of `func`.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new bound function.
+     * @example
+     *
+     * var func = function(greeting) {
+     *   return greeting + ' ' + this.name;
+     * };
+     *
+     * func = _.bind(func, { 'name': 'moe' }, 'hi');
+     * func();
+     * // => 'hi moe'
+     */
+    function bind(func, thisArg) {
+      return arguments.length > 2
+        ? createBound(func, 17, nativeSlice.call(arguments, 2), null, thisArg)
+        : createBound(func, 1, null, null, thisArg);
+    }
+
+    /**
+     * Binds methods of an object to the object itself, overwriting the existing
+     * method. Method names may be specified as individual arguments or as arrays
+     * of method names. If no method names are provided all the function properties
+     * of `object` will be bound.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Object} object The object to bind and assign the bound methods to.
+     * @param {...string} [methodName] The object method names to
+     *  bind, specified as individual method names or arrays of method names.
+     * @returns {Object} Returns `object`.
+     * @example
+     *
+     * var view = {
+     *  'label': 'docs',
+     *  'onClick': function() { console.log('clicked ' + this.label); }
+     * };
+     *
+     * _.bindAll(view);
+     * jQuery('#docs').on('click', view.onClick);
+     * // => logs 'clicked docs', when the button is clicked
+     */
+    function bindAll(object) {
+      var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
+          index = -1,
+          length = funcs.length;
+
+      while (++index < length) {
+        var key = funcs[index];
+        object[key] = createBound(object[key], 1, null, null, object);
+      }
+      return object;
+    }
+
+    /**
+     * Creates a function that, when called, invokes the method at `object[key]`
+     * and prepends any additional `bindKey` arguments to those provided to the bound
+     * function. This method differs from `_.bind` by allowing bound functions to
+     * reference methods that will be redefined or don't yet exist.
+     * See http://michaux.ca/articles/lazy-function-definition-pattern.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Object} object The object the method belongs to.
+     * @param {string} key The key of the method.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new bound function.
+     * @example
+     *
+     * var object = {
+     *   'name': 'moe',
+     *   'greet': function(greeting) {
+     *     return greeting + ' ' + this.name;
+     *   }
+     * };
+     *
+     * var func = _.bindKey(object, 'greet', 'hi');
+     * func();
+     * // => 'hi moe'
+     *
+     * object.greet = function(greeting) {
+     *   return greeting + ', ' + this.name + '!';
+     * };
+     *
+     * func();
+     * // => 'hi, moe!'
+     */
+    function bindKey(object, key) {
+      return arguments.length > 2
+        ? createBound(key, 19, nativeSlice.call(arguments, 2), null, object)
+        : createBound(key, 3, null, null, object);
+    }
+
+    /**
+     * Creates a function that is the composition of the provided functions,
+     * where each function consumes the return value of the function that follows.
+     * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
+     * Each function is executed with the `this` binding of the composed function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {...Function} [func] Functions to compose.
+     * @returns {Function} Returns the new composed function.
+     * @example
+     *
+     * var realNameMap = {
+     *   'curly': 'jerome'
+     * };
+     *
+     * var format = function(name) {
+     *   name = realNameMap[name.toLowerCase()] || name;
+     *   return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
+     * };
+     *
+     * var greet = function(formatted) {
+     *   return 'Hiya ' + formatted + '!';
+     * };
+     *
+     * var welcome = _.compose(greet, format);
+     * welcome('curly');
+     * // => 'Hiya Jerome!'
+     */
+    function compose() {
+      var funcs = arguments,
+          length = funcs.length;
+
+      while (length--) {
+        if (!isFunction(funcs[length])) {
+          throw new TypeError;
+        }
+      }
+      return function() {
+        var args = arguments,
+            length = funcs.length;
+
+        while (length--) {
+          args = [funcs[length].apply(this, args)];
+        }
+        return args[0];
+      };
+    }
+
+    /**
+     * Produces a callback bound to an optional `thisArg`. If `func` is a property
+     * name the created callback will return the property value for a given element.
+     * If `func` is an object the created callback will return `true` for elements
+     * that contain the equivalent object properties, otherwise it will return `false`.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {*} [func=identity] The value to convert to a callback.
+     * @param {*} [thisArg] The `this` binding of the created callback.
+     * @param {number} [argCount] The number of arguments the callback accepts.
+     * @returns {Function} Returns a callback function.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // wrap to create custom callback shorthands
+     * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
+     *   var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
+     *   return !match ? func(callback, thisArg) : function(object) {
+     *     return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
+     *   };
+     * });
+     *
+     * _.filter(stooges, 'age__gt45');
+     * // => [{ 'name': 'larry', 'age': 50 }]
+     */
+    function createCallback(func, thisArg, argCount) {
+      var type = typeof func;
+      if (func == null || type == 'function') {
+        return baseCreateCallback(func, thisArg, argCount);
+      }
+      // handle "_.pluck" style callback shorthands
+      if (type != 'object') {
+        return function(object) {
+          return object[func];
+        };
+      }
+      var props = keys(func),
+          key = props[0],
+          a = func[key];
+
+      // handle "_.where" style callback shorthands
+      if (props.length == 1 && a === a && !isObject(a)) {
+        // fast path the common case of providing an object with a single
+        // property containing a primitive value
+        return function(object) {
+          var b = object[key];
+          return a === b && (a !== 0 || (1 / a == 1 / b));
+        };
+      }
+      return function(object) {
+        var length = props.length,
+            result = false;
+
+        while (length--) {
+          if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
+            break;
+          }
+        }
+        return result;
+      };
+    }
+
+    /**
+     * Creates a function which accepts one or more arguments of `func` that when
+     * invoked either executes `func` returning its result, if all `func` arguments
+     * have been provided, or returns a function that accepts one or more of the
+     * remaining `func` arguments, and so on. The arity of `func` can be specified
+     * if `func.length` is not sufficient.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to curry.
+     * @param {number} [arity=func.length] The arity of `func`.
+     * @returns {Function} Returns the new curried function.
+     * @example
+     *
+     * var curried = _.curry(function(a, b, c) {
+     *   console.log(a + b + c);
+     * });
+     *
+     * curried(1)(2)(3);
+     * // => 6
+     *
+     * curried(1, 2)(3);
+     * // => 6
+     *
+     * curried(1, 2, 3);
+     * // => 6
+     */
+    function curry(func, arity) {
+      arity = typeof arity == 'number' ? arity : (+arity || func.length);
+      return createBound(func, 4, null, null, null, arity);
+    }
+
+    /**
+     * Creates a function that will delay the execution of `func` until after
+     * `wait` milliseconds have elapsed since the last time it was invoked.
+     * Provide an options object to indicate that `func` should be invoked on
+     * the leading and/or trailing edge of the `wait` timeout. Subsequent calls
+     * to the debounced function will return the result of the last `func` call.
+     *
+     * Note: If `leading` and `trailing` options are `true` `func` will be called
+     * on the trailing edge of the timeout only if the the debounced function is
+     * invoked more than once during the `wait` timeout.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to debounce.
+     * @param {number} wait The number of milliseconds to delay.
+     * @param {Object} [options] The options object.
+     * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
+     * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
+     * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
+     * @returns {Function} Returns the new debounced function.
+     * @example
+     *
+     * // avoid costly calculations while the window size is in flux
+     * var lazyLayout = _.debounce(calculateLayout, 150);
+     * jQuery(window).on('resize', lazyLayout);
+     *
+     * // execute `sendMail` when the click event is fired, debouncing subsequent calls
+     * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
+     *   'leading': true,
+     *   'trailing': false
+     * });
+     *
+     * // ensure `batchLog` is executed once after 1 second of debounced calls
+     * var source = new EventSource('/stream');
+     * source.addEventListener('message', _.debounce(batchLog, 250, {
+     *   'maxWait': 1000
+     * }, false);
+     */
+    function debounce(func, wait, options) {
+      var args,
+          maxTimeoutId,
+          result,
+          stamp,
+          thisArg,
+          timeoutId,
+          trailingCall,
+          lastCalled = 0,
+          maxWait = false,
+          trailing = true;
+
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      wait = nativeMax(0, wait) || 0;
+      if (options === true) {
+        var leading = true;
+        trailing = false;
+      } else if (isObject(options)) {
+        leading = options.leading;
+        maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
+        trailing = 'trailing' in options ? options.trailing : trailing;
+      }
+      var delayed = function() {
+        var remaining = wait - (now() - stamp);
+        if (remaining <= 0) {
+          if (maxTimeoutId) {
+            clearTimeout(maxTimeoutId);
+          }
+          var isCalled = trailingCall;
+          maxTimeoutId = timeoutId = trailingCall = undefined;
+          if (isCalled) {
+            lastCalled = now();
+            result = func.apply(thisArg, args);
+          }
+        } else {
+          timeoutId = setTimeout(delayed, remaining);
+        }
+      };
+
+      var maxDelayed = function() {
+        if (timeoutId) {
+          clearTimeout(timeoutId);
+        }
+        maxTimeoutId = timeoutId = trailingCall = undefined;
+        if (trailing || (maxWait !== wait)) {
+          lastCalled = now();
+          result = func.apply(thisArg, args);
+        }
+      };
+
+      return function() {
+        args = arguments;
+        stamp = now();
+        thisArg = this;
+        trailingCall = trailing && (timeoutId || !leading);
+
+        if (maxWait === false) {
+          var leadingCall = leading && !timeoutId;
+        } else {
+          if (!maxTimeoutId && !leading) {
+            lastCalled = stamp;
+          }
+          var remaining = maxWait - (stamp - lastCalled);
+          if (remaining <= 0) {
+            if (maxTimeoutId) {
+              maxTimeoutId = clearTimeout(maxTimeoutId);
+            }
+            lastCalled = stamp;
+            result = func.apply(thisArg, args);
+          }
+          else if (!maxTimeoutId) {
+            maxTimeoutId = setTimeout(maxDelayed, remaining);
+          }
+        }
+        if (!timeoutId && wait !== maxWait) {
+          timeoutId = setTimeout(delayed, wait);
+        }
+        if (leadingCall) {
+          result = func.apply(thisArg, args);
+        }
+        return result;
+      };
+    }
+
+    /**
+     * Defers executing the `func` function until the current call stack has cleared.
+     * Additional arguments will be provided to `func` when it is invoked.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to defer.
+     * @param {...*} [arg] Arguments to invoke the function with.
+     * @returns {number} Returns the timer id.
+     * @example
+     *
+     * _.defer(function() { console.log('deferred'); });
+     * // returns from the function before 'deferred' is logged
+     */
+    function defer(func) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      var args = nativeSlice.call(arguments, 1);
+      return setTimeout(function() { func.apply(undefined, args); }, 1);
+    }
+    // use `setImmediate` if available in Node.js
+    if (isV8 && moduleExports && typeof setImmediate == 'function') {
+      defer = function(func) {
+        if (!isFunction(func)) {
+          throw new TypeError;
+        }
+        return setImmediate.apply(context, arguments);
+      };
+    }
+
+    /**
+     * Executes the `func` function after `wait` milliseconds. Additional arguments
+     * will be provided to `func` when it is invoked.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to delay.
+     * @param {number} wait The number of milliseconds to delay execution.
+     * @param {...*} [arg] Arguments to invoke the function with.
+     * @returns {number} Returns the timer id.
+     * @example
+     *
+     * var log = _.bind(console.log, console);
+     * _.delay(log, 1000, 'logged later');
+     * // => 'logged later' (Appears after one second.)
+     */
+    function delay(func, wait) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      var args = nativeSlice.call(arguments, 2);
+      return setTimeout(function() { func.apply(undefined, args); }, wait);
+    }
+
+    /**
+     * Creates a function that memoizes the result of `func`. If `resolver` is
+     * provided it will be used to determine the cache key for storing the result
+     * based on the arguments provided to the memoized function. By default, the
+     * first argument provided to the memoized function is used as the cache key.
+     * The `func` is executed with the `this` binding of the memoized function.
+     * The result cache is exposed as the `cache` property on the memoized function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to have its output memoized.
+     * @param {Function} [resolver] A function used to resolve the cache key.
+     * @returns {Function} Returns the new memoizing function.
+     * @example
+     *
+     * var fibonacci = _.memoize(function(n) {
+     *   return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
+     * });
+     *
+     * var data = {
+     *   'moe': { 'name': 'moe', 'age': 40 },
+     *   'curly': { 'name': 'curly', 'age': 60 }
+     * };
+     *
+     * // modifying the result cache
+     * var stooge = _.memoize(function(name) { return data[name]; }, _.identity);
+     * stooge('curly');
+     * // => { 'name': 'curly', 'age': 60 }
+     *
+     * stooge.cache.curly.name = 'jerome';
+     * stooge('curly');
+     * // => { 'name': 'jerome', 'age': 60 }
+     */
+    function memoize(func, resolver) {
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      var memoized = function() {
+        var cache = memoized.cache,
+            key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
+
+        return hasOwnProperty.call(cache, key)
+          ? cache[key]
+          : (cache[key] = func.apply(this, arguments));
+      }
+      memoized.cache = {};
+      return memoized;
+    }
+
+    /**
+     * Creates a function that is restricted to execute `func` once. Repeat calls to
+     * the function will return the value of the first call. The `func` is executed
+     * with the `this` binding of the created function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to restrict.
+     * @returns {Function} Returns the new restricted function.
+     * @example
+     *
+     * var initialize = _.once(createApplication);
+     * initialize();
+     * initialize();
+     * // `initialize` executes `createApplication` once
+     */
+    function once(func) {
+      var ran,
+          result;
+
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      return function() {
+        if (ran) {
+          return result;
+        }
+        ran = true;
+        result = func.apply(this, arguments);
+
+        // clear the `func` variable so the function may be garbage collected
+        func = null;
+        return result;
+      };
+    }
+
+    /**
+     * Creates a function that, when called, invokes `func` with any additional
+     * `partial` arguments prepended to those provided to the new function. This
+     * method is similar to `_.bind` except it does **not** alter the `this` binding.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to partially apply arguments to.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new partially applied function.
+     * @example
+     *
+     * var greet = function(greeting, name) { return greeting + ' ' + name; };
+     * var hi = _.partial(greet, 'hi');
+     * hi('moe');
+     * // => 'hi moe'
+     */
+    function partial(func) {
+      return createBound(func, 16, nativeSlice.call(arguments, 1));
+    }
+
+    /**
+     * This method is like `_.partial` except that `partial` arguments are
+     * appended to those provided to the new function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to partially apply arguments to.
+     * @param {...*} [arg] Arguments to be partially applied.
+     * @returns {Function} Returns the new partially applied function.
+     * @example
+     *
+     * var defaultsDeep = _.partialRight(_.merge, _.defaults);
+     *
+     * var options = {
+     *   'variable': 'data',
+     *   'imports': { 'jq': $ }
+     * };
+     *
+     * defaultsDeep(options, _.templateSettings);
+     *
+     * options.variable
+     * // => 'data'
+     *
+     * options.imports
+     * // => { '_': _, 'jq': $ }
+     */
+    function partialRight(func) {
+      return createBound(func, 32, null, nativeSlice.call(arguments, 1));
+    }
+
+    /**
+     * Creates a function that, when executed, will only call the `func` function
+     * at most once per every `wait` milliseconds. Provide an options object to
+     * indicate that `func` should be invoked on the leading and/or trailing edge
+     * of the `wait` timeout. Subsequent calls to the throttled function will
+     * return the result of the last `func` call.
+     *
+     * Note: If `leading` and `trailing` options are `true` `func` will be called
+     * on the trailing edge of the timeout only if the the throttled function is
+     * invoked more than once during the `wait` timeout.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {Function} func The function to throttle.
+     * @param {number} wait The number of milliseconds to throttle executions to.
+     * @param {Object} [options] The options object.
+     * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
+     * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
+     * @returns {Function} Returns the new throttled function.
+     * @example
+     *
+     * // avoid excessively updating the position while scrolling
+     * var throttled = _.throttle(updatePosition, 100);
+     * jQuery(window).on('scroll', throttled);
+     *
+     * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
+     * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
+     *   'trailing': false
+     * }));
+     */
+    function throttle(func, wait, options) {
+      var leading = true,
+          trailing = true;
+
+      if (!isFunction(func)) {
+        throw new TypeError;
+      }
+      if (options === false) {
+        leading = false;
+      } else if (isObject(options)) {
+        leading = 'leading' in options ? options.leading : leading;
+        trailing = 'trailing' in options ? options.trailing : trailing;
+      }
+      debounceOptions.leading = leading;
+      debounceOptions.maxWait = wait;
+      debounceOptions.trailing = trailing;
+
+      var result = debounce(func, wait, debounceOptions);
+      return result;
+    }
+
+    /**
+     * Creates a function that provides `value` to the wrapper function as its
+     * first argument. Additional arguments provided to the function are appended
+     * to those provided to the wrapper function. The wrapper is executed with
+     * the `this` binding of the created function.
+     *
+     * @static
+     * @memberOf _
+     * @category Functions
+     * @param {*} value The value to wrap.
+     * @param {Function} wrapper The wrapper function.
+     * @returns {Function} Returns the new function.
+     * @example
+     *
+     * var hello = function(name) { return 'hello ' + name; };
+     * hello = _.wrap(hello, function(func) {
+     *   return 'before, ' + func('moe') + ', after';
+     * });
+     * hello();
+     * // => 'before, hello moe, after'
+     */
+    function wrap(value, wrapper) {
+      if (!isFunction(wrapper)) {
+        throw new TypeError;
+      }
+      return function() {
+        var args = [value];
+        push.apply(args, arguments);
+        return wrapper.apply(this, args);
+      };
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
+     * corresponding HTML entities.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} string The string to escape.
+     * @returns {string} Returns the escaped string.
+     * @example
+     *
+     * _.escape('Moe, Larry & Curly');
+     * // => 'Moe, Larry &amp; Curly'
+     */
+    function escape(string) {
+      return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
+    }
+
+    /**
+     * This method returns the first argument provided to it.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {*} value Any value.
+     * @returns {*} Returns `value`.
+     * @example
+     *
+     * var moe = { 'name': 'moe' };
+     * moe === _.identity(moe);
+     * // => true
+     */
+    function identity(value) {
+      return value;
+    }
+
+    /**
+     * Adds function properties of a source object to the `lodash` function and
+     * chainable wrapper.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {Object} object The object of function properties to add to `lodash`.
+     * @param {Object} object The object of function properties to add to `lodash`.
+     * @example
+     *
+     * _.mixin({
+     *   'capitalize': function(string) {
+     *     return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
+     *   }
+     * });
+     *
+     * _.capitalize('moe');
+     * // => 'Moe'
+     *
+     * _('moe').capitalize();
+     * // => 'Moe'
+     */
+    function mixin(object, source) {
+      var ctor = object,
+          isFunc = !source || isFunction(ctor);
+
+      if (!source) {
+        ctor = lodashWrapper;
+        source = object;
+        object = lodash;
+      }
+      forEach(functions(source), function(methodName) {
+        var func = object[methodName] = source[methodName];
+        if (isFunc) {
+          ctor.prototype[methodName] = function() {
+            var value = this.__wrapped__,
+                args = [value];
+
+            push.apply(args, arguments);
+            var result = func.apply(object, args);
+            if (value && typeof value == 'object' && value === result) {
+              return this;
+            }
+            result = new ctor(result);
+            result.__chain__ = this.__chain__;
+            return result;
+          };
+        }
+      });
+    }
+
+    /**
+     * Reverts the '_' variable to its previous value and returns a reference to
+     * the `lodash` function.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @returns {Function} Returns the `lodash` function.
+     * @example
+     *
+     * var lodash = _.noConflict();
+     */
+    function noConflict() {
+      context._ = oldDash;
+      return this;
+    }
+
+    /**
+     * Converts the given value into an integer of the specified radix.
+     * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
+     * `value` is a hexadecimal, in which case a `radix` of `16` is used.
+     *
+     * Note: This method avoids differences in native ES3 and ES5 `parseInt`
+     * implementations. See http://es5.github.io/#E.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} value The value to parse.
+     * @param {number} [radix] The radix used to interpret the value to parse.
+     * @returns {number} Returns the new integer value.
+     * @example
+     *
+     * _.parseInt('08');
+     * // => 8
+     */
+    var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
+      // Firefox and Opera still follow the ES3 specified implementation of `parseInt`
+      return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
+    };
+
+    /**
+     * Produces a random number between `min` and `max` (inclusive). If only one
+     * argument is provided a number between `0` and the given number will be
+     * returned. If `floating` is truey or either `min` or `max` are floats a
+     * floating-point number will be returned instead of an integer.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {number} [min=0] The minimum possible value.
+     * @param {number} [max=1] The maximum possible value.
+     * @param {boolean} [floating=false] Specify returning a floating-point number.
+     * @returns {number} Returns a random number.
+     * @example
+     *
+     * _.random(0, 5);
+     * // => an integer between 0 and 5
+     *
+     * _.random(5);
+     * // => also an integer between 0 and 5
+     *
+     * _.random(5, true);
+     * // => a floating-point number between 0 and 5
+     *
+     * _.random(1.2, 5.2);
+     * // => a floating-point number between 1.2 and 5.2
+     */
+    function random(min, max, floating) {
+      var noMin = min == null,
+          noMax = max == null;
+
+      if (floating == null) {
+        if (typeof min == 'boolean' && noMax) {
+          floating = min;
+          min = 1;
+        }
+        else if (!noMax && typeof max == 'boolean') {
+          floating = max;
+          noMax = true;
+        }
+      }
+      if (noMin && noMax) {
+        max = 1;
+      }
+      min = +min || 0;
+      if (noMax) {
+        max = min;
+        min = 0;
+      } else {
+        max = +max || 0;
+      }
+      var rand = nativeRandom();
+      return (floating || min % 1 || max % 1)
+        ? nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max)
+        : min + floor(rand * (max - min + 1));
+    }
+
+    /**
+     * Resolves the value of `property` on `object`. If `property` is a function
+     * it will be invoked with the `this` binding of `object` and its result returned,
+     * else the property value is returned. If `object` is falsey then `undefined`
+     * is returned.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {Object} object The object to inspect.
+     * @param {string} property The property to get the value of.
+     * @returns {*} Returns the resolved value.
+     * @example
+     *
+     * var object = {
+     *   'cheese': 'crumpets',
+     *   'stuff': function() {
+     *     return 'nonsense';
+     *   }
+     * };
+     *
+     * _.result(object, 'cheese');
+     * // => 'crumpets'
+     *
+     * _.result(object, 'stuff');
+     * // => 'nonsense'
+     */
+    function result(object, property) {
+      if (object) {
+        var value = object[property];
+        return isFunction(value) ? object[property]() : value;
+      }
+    }
+
+    /**
+     * A micro-templating method that handles arbitrary delimiters, preserves
+     * whitespace, and correctly escapes quotes within interpolated code.
+     *
+     * Note: In the development build, `_.template` utilizes sourceURLs for easier
+     * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
+     *
+     * For more information on precompiling templates see:
+     * http://lodash.com/#custom-builds
+     *
+     * For more information on Chrome extension sandboxes see:
+     * http://developer.chrome.com/stable/extensions/sandboxingEval.html
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} text The template text.
+     * @param {Object} data The data object used to populate the text.
+     * @param {Object} [options] The options object.
+     * @param {RegExp} [options.escape] The "escape" delimiter.
+     * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
+     * @param {Object} [options.imports] An object to import into the template as local variables.
+     * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
+     * @param {string} [sourceURL] The sourceURL of the template's compiled source.
+     * @param {string} [variable] The data object variable name.
+     * @returns {Function|string} Returns a compiled function when no `data` object
+     *  is given, else it returns the interpolated text.
+     * @example
+     *
+     * // using the "interpolate" delimiter to create a compiled template
+     * var compiled = _.template('hello <%= name %>');
+     * compiled({ 'name': 'moe' });
+     * // => 'hello moe'
+     *
+     * // using the "escape" delimiter to escape HTML in data property values
+     * _.template('<b><%- value %></b>', { 'value': '<script>' });
+     * // => '<b>&lt;script&gt;</b>'
+     *
+     * // using the "evaluate" delimiter to generate HTML
+     * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
+     * _.template(list, { 'people': ['moe', 'larry'] });
+     * // => '<li>moe</li><li>larry</li>'
+     *
+     * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
+     * _.template('hello ${ name }', { 'name': 'curly' });
+     * // => 'hello curly'
+     *
+     * // using the internal `print` function in "evaluate" delimiters
+     * _.template('<% print("hello " + name); %>!', { 'name': 'larry' });
+     * // => 'hello larry!'
+     *
+     * // using a custom template delimiters
+     * _.templateSettings = {
+     *   'interpolate': /{{([\s\S]+?)}}/g
+     * };
+     *
+     * _.template('hello {{ name }}!', { 'name': 'mustache' });
+     * // => 'hello mustache!'
+     *
+     * // using the `imports` option to import jQuery
+     * var list = '<% $.each(people, function(name) { %><li><%- name %></li><% }); %>';
+     * _.template(list, { 'people': ['moe', 'larry'] }, { 'imports': { '$': jQuery } });
+     * // => '<li>moe</li><li>larry</li>'
+     *
+     * // using the `sourceURL` option to specify a custom sourceURL for the template
+     * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
+     * compiled(data);
+     * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
+     *
+     * // using the `variable` option to ensure a with-statement isn't used in the compiled template
+     * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
+     * compiled.source;
+     * // => function(data) {
+     *   var __t, __p = '', __e = _.escape;
+     *   __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
+     *   return __p;
+     * }
+     *
+     * // using the `source` property to inline compiled templates for meaningful
+     * // line numbers in error messages and a stack trace
+     * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
+     *   var JST = {\
+     *     "main": ' + _.template(mainText).source + '\
+     *   };\
+     * ');
+     */
+    function template(text, data, options) {
+      // based on John Resig's `tmpl` implementation
+      // http://ejohn.org/blog/javascript-micro-templating/
+      // and Laura Doktorova's doT.js
+      // https://github.com/olado/doT
+      var settings = lodash.templateSettings;
+      text || (text = '');
+
+      // avoid missing dependencies when `iteratorTemplate` is not defined
+      options = defaults({}, options, settings);
+
+      var imports = defaults({}, options.imports, settings.imports),
+          importsKeys = keys(imports),
+          importsValues = values(imports);
+
+      var isEvaluating,
+          index = 0,
+          interpolate = options.interpolate || reNoMatch,
+          source = "__p += '";
+
+      // compile the regexp to match each delimiter
+      var reDelimiters = RegExp(
+        (options.escape || reNoMatch).source + '|' +
+        interpolate.source + '|' +
+        (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
+        (options.evaluate || reNoMatch).source + '|$'
+      , 'g');
+
+      text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
+        interpolateValue || (interpolateValue = esTemplateValue);
+
+        // escape characters that cannot be included in string literals
+        source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
+
+        // replace delimiters with snippets
+        if (escapeValue) {
+          source += "' +\n__e(" + escapeValue + ") +\n'";
+        }
+        if (evaluateValue) {
+          isEvaluating = true;
+          source += "';\n" + evaluateValue + ";\n__p += '";
+        }
+        if (interpolateValue) {
+          source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
+        }
+        index = offset + match.length;
+
+        // the JS engine embedded in Adobe products requires returning the `match`
+        // string in order to produce the correct `offset` value
+        return match;
+      });
+
+      source += "';\n";
+
+      // if `variable` is not specified, wrap a with-statement around the generated
+      // code to add the data object to the top of the scope chain
+      var variable = options.variable,
+          hasVariable = variable;
+
+      if (!hasVariable) {
+        variable = 'obj';
+        source = 'with (' + variable + ') {\n' + source + '\n}\n';
+      }
+      // cleanup code by stripping empty strings
+      source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
+        .replace(reEmptyStringMiddle, '$1')
+        .replace(reEmptyStringTrailing, '$1;');
+
+      // frame code as the function body
+      source = 'function(' + variable + ') {\n' +
+        (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
+        "var __t, __p = '', __e = _.escape" +
+        (isEvaluating
+          ? ', __j = Array.prototype.join;\n' +
+            "function print() { __p += __j.call(arguments, '') }\n"
+          : ';\n'
+        ) +
+        source +
+        'return __p\n}';
+
+      // Use a sourceURL for easier debugging.
+      // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
+      var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
+
+      try {
+        var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
+      } catch(e) {
+        e.source = source;
+        throw e;
+      }
+      if (data) {
+        return result(data);
+      }
+      // provide the compiled function's source by its `toString` method, in
+      // supported environments, or the `source` property as a convenience for
+      // inlining compiled templates during the build process
+      result.source = source;
+      return result;
+    }
+
+    /**
+     * Executes the callback `n` times, returning an array of the results
+     * of each callback execution. The callback is bound to `thisArg` and invoked
+     * with one argument; (index).
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {number} n The number of times to execute the callback.
+     * @param {Function} callback The function called per iteration.
+     * @param {*} [thisArg] The `this` binding of `callback`.
+     * @returns {Array} Returns an array of the results of each `callback` execution.
+     * @example
+     *
+     * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
+     * // => [3, 6, 4]
+     *
+     * _.times(3, function(n) { mage.castSpell(n); });
+     * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
+     *
+     * _.times(3, function(n) { this.cast(n); }, mage);
+     * // => also calls `mage.castSpell(n)` three times
+     */
+    function times(n, callback, thisArg) {
+      n = (n = +n) > -1 ? n : 0;
+      var index = -1,
+          result = Array(n);
+
+      callback = baseCreateCallback(callback, thisArg, 1);
+      while (++index < n) {
+        result[index] = callback(index);
+      }
+      return result;
+    }
+
+    /**
+     * The inverse of `_.escape` this method converts the HTML entities
+     * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their
+     * corresponding characters.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} string The string to unescape.
+     * @returns {string} Returns the unescaped string.
+     * @example
+     *
+     * _.unescape('Moe, Larry &amp; Curly');
+     * // => 'Moe, Larry & Curly'
+     */
+    function unescape(string) {
+      return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
+    }
+
+    /**
+     * Generates a unique ID. If `prefix` is provided the ID will be appended to it.
+     *
+     * @static
+     * @memberOf _
+     * @category Utilities
+     * @param {string} [prefix] The value to prefix the ID with.
+     * @returns {string} Returns the unique ID.
+     * @example
+     *
+     * _.uniqueId('contact_');
+     * // => 'contact_104'
+     *
+     * _.uniqueId();
+     * // => '105'
+     */
+    function uniqueId(prefix) {
+      var id = ++idCounter;
+      return String(prefix == null ? '' : prefix) + id;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * Creates a `lodash` object that wraps the given value with explicit
+     * method chaining enabled.
+     *
+     * @static
+     * @memberOf _
+     * @category Chaining
+     * @param {*} value The value to wrap.
+     * @returns {Object} Returns the wrapper object.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 },
+     *   { 'name': 'curly', 'age': 60 }
+     * ];
+     *
+     * var youngest = _.chain(stooges)
+     *     .sortBy('age')
+     *     .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
+     *     .first()
+     *     .value();
+     * // => 'moe is 40'
+     */
+    function chain(value) {
+      value = new lodashWrapper(value);
+      value.__chain__ = true;
+      return value;
+    }
+
+    /**
+     * Invokes `interceptor` with the `value` as the first argument and then
+     * returns `value`. The purpose of this method is to "tap into" a method
+     * chain in order to perform operations on intermediate results within
+     * the chain.
+     *
+     * @static
+     * @memberOf _
+     * @category Chaining
+     * @param {*} value The value to provide to `interceptor`.
+     * @param {Function} interceptor The function to invoke.
+     * @returns {*} Returns `value`.
+     * @example
+     *
+     * _([1, 2, 3, 4])
+     *  .filter(function(num) { return num % 2 == 0; })
+     *  .tap(function(array) { console.log(array); })
+     *  .map(function(num) { return num * num; })
+     *  .value();
+     * // => // [2, 4] (logged)
+     * // => [4, 16]
+     */
+    function tap(value, interceptor) {
+      interceptor(value);
+      return value;
+    }
+
+    /**
+     * Enables explicit method chaining on the wrapper object.
+     *
+     * @name chain
+     * @memberOf _
+     * @category Chaining
+     * @returns {*} Returns the wrapper object.
+     * @example
+     *
+     * var stooges = [
+     *   { 'name': 'moe', 'age': 40 },
+     *   { 'name': 'larry', 'age': 50 }
+     * ];
+     *
+     * // without explicit chaining
+     * _(stooges).first();
+     * // => { 'name': 'moe', 'age': 40 }
+     *
+     * // with explicit chaining
+     * _(stooges).chain()
+     *   .first()
+     *   .pick('age')
+     *   .value()
+     * // => { 'age': 40 }
+     */
+    function wrapperChain() {
+      this.__chain__ = true;
+      return this;
+    }
+
+    /**
+     * Produces the `toString` result of the wrapped value.
+     *
+     * @name toString
+     * @memberOf _
+     * @category Chaining
+     * @returns {string} Returns the string result.
+     * @example
+     *
+     * _([1, 2, 3]).toString();
+     * // => '1,2,3'
+     */
+    function wrapperToString() {
+      return String(this.__wrapped__);
+    }
+
+    /**
+     * Extracts the wrapped value.
+     *
+     * @name valueOf
+     * @memberOf _
+     * @alias value
+     * @category Chaining
+     * @returns {*} Returns the wrapped value.
+     * @example
+     *
+     * _([1, 2, 3]).valueOf();
+     * // => [1, 2, 3]
+     */
+    function wrapperValueOf() {
+      return this.__wrapped__;
+    }
+
+    /*--------------------------------------------------------------------------*/
+
+    // add functions that return wrapped values when chaining
+    lodash.after = after;
+    lodash.assign = assign;
+    lodash.at = at;
+    lodash.bind = bind;
+    lodash.bindAll = bindAll;
+    lodash.bindKey = bindKey;
+    lodash.chain = chain;
+    lodash.compact = compact;
+    lodash.compose = compose;
+    lodash.countBy = countBy;
+    lodash.createCallback = createCallback;
+    lodash.curry = curry;
+    lodash.debounce = debounce;
+    lodash.defaults = defaults;
+    lodash.defer = defer;
+    lodash.delay = delay;
+    lodash.difference = difference;
+    lodash.filter = filter;
+    lodash.flatten = flatten;
+    lodash.forEach = forEach;
+    lodash.forEachRight = forEachRight;
+    lodash.forIn = forIn;
+    lodash.forInRight = forInRight;
+    lodash.forOwn = forOwn;
+    lodash.forOwnRight = forOwnRight;
+    lodash.functions = functions;
+    lodash.groupBy = groupBy;
+    lodash.indexBy = indexBy;
+    lodash.initial = initial;
+    lodash.intersection = intersection;
+    lodash.invert = invert;
+    lodash.invoke = invoke;
+    lodash.keys = keys;
+    lodash.map = map;
+    lodash.max = max;
+    lodash.memoize = memoize;
+    lodash.merge = merge;
+    lodash.min = min;
+    lodash.omit = omit;
+    lodash.once = once;
+    lodash.pairs = pairs;
+    lodash.partial = partial;
+    lodash.partialRight = partialRight;
+    lodash.pick = pick;
+    lodash.pluck = pluck;
+    lodash.pull = pull;
+    lodash.range = range;
+    lodash.reject = reject;
+    lodash.remove = remove;
+    lodash.rest = rest;
+    lodash.shuffle = shuffle;
+    lodash.sortBy = sortBy;
+    lodash.tap = tap;
+    lodash.throttle = throttle;
+    lodash.times = times;
+    lodash.toArray = toArray;
+    lodash.transform = transform;
+    lodash.union = union;
+    lodash.uniq = uniq;
+    lodash.values = values;
+    lodash.where = where;
+    lodash.without = without;
+    lodash.wrap = wrap;
+    lodash.zip = zip;
+    lodash.zipObject = zipObject;
+
+    // add aliases
+    lodash.collect = map;
+    lodash.drop = rest;
+    lodash.each = forEach;
+    lodash.eachRight = forEachRight;
+    lodash.extend = assign;
+    lodash.methods = functions;
+    lodash.object = zipObject;
+    lodash.select = filter;
+    lodash.tail = rest;
+    lodash.unique = uniq;
+    lodash.unzip = zip;
+
+    // add functions to `lodash.prototype`
+    mixin(lodash);
+
+    /*--------------------------------------------------------------------------*/
+
+    // add functions that return unwrapped values when chaining
+    lodash.clone = clone;
+    lodash.cloneDeep = cloneDeep;
+    lodash.contains = contains;
+    lodash.escape = escape;
+    lodash.every = every;
+    lodash.find = find;
+    lodash.findIndex = findIndex;
+    lodash.findKey = findKey;
+    lodash.findLast = findLast;
+    lodash.findLastIndex = findLastIndex;
+    lodash.findLastKey = findLastKey;
+    lodash.has = has;
+    lodash.identity = identity;
+    lodash.indexOf = indexOf;
+    lodash.isArguments = isArguments;
+    lodash.isArray = isArray;
+    lodash.isBoolean = isBoolean;
+    lodash.isDate = isDate;
+    lodash.isElement = isElement;
+    lodash.isEmpty = isEmpty;
+    lodash.isEqual = isEqual;
+    lodash.isFinite = isFinite;
+    lodash.isFunction = isFunction;
+    lodash.isNaN = isNaN;
+    lodash.isNull = isNull;
+    lodash.isNumber = isNumber;
+    lodash.isObject = isObject;
+    lodash.isPlainObject = isPlainObject;
+    lodash.isRegExp = isRegExp;
+    lodash.isString = isString;
+    lodash.isUndefined = isUndefined;
+    lodash.lastIndexOf = lastIndexOf;
+    lodash.mixin = mixin;
+    lodash.noConflict = noConflict;
+    lodash.parseInt = parseInt;
+    lodash.random = random;
+    lodash.reduce = reduce;
+    lodash.reduceRight = reduceRight;
+    lodash.result = result;
+    lodash.runInContext = runInContext;
+    lodash.size = size;
+    lodash.some = some;
+    lodash.sortedIndex = sortedIndex;
+    lodash.template = template;
+    lodash.unescape = unescape;
+    lodash.uniqueId = uniqueId;
+
+    // add aliases
+    lodash.all = every;
+    lodash.any = some;
+    lodash.detect = find;
+    lodash.findWhere = find;
+    lodash.foldl = reduce;
+    lodash.foldr = reduceRight;
+    lodash.include = contains;
+    lodash.inject = reduce;
+
+    forOwn(lodash, function(func, methodName) {
+      if (!lodash.prototype[methodName]) {
+        lodash.prototype[methodName] = function() {
+          var args = [this.__wrapped__],
+              chainAll = this.__chain__;
+
+          push.apply(args, arguments);
+          var result = func.apply(lodash, args);
+          return chainAll
+            ? new lodashWrapper(result, chainAll)
+            : result;
+        };
+      }
+    });
+
+    /*--------------------------------------------------------------------------*/
+
+    // add functions capable of returning wrapped and unwrapped values when chaining
+    lodash.first = first;
+    lodash.last = last;
+    lodash.sample = sample;
+
+    // add aliases
+    lodash.take = first;
+    lodash.head = first;
+
+    forOwn(lodash, function(func, methodName) {
+      var callbackable = methodName !== 'sample';
+      if (!lodash.prototype[methodName]) {
+        lodash.prototype[methodName]= function(n, guard) {
+          var chainAll = this.__chain__,
+              result = func(this.__wrapped__, n, guard);
+
+          return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
+            ? result
+            : new lodashWrapper(result, chainAll);
+        };
+      }
+    });
+
+    /*--------------------------------------------------------------------------*/
+
+    /**
+     * The semantic version number.
+     *
+     * @static
+     * @memberOf _
+     * @type string
+     */
+    lodash.VERSION = '2.2.1';
+
+    // add "Chaining" functions to the wrapper
+    lodash.prototype.chain = wrapperChain;
+    lodash.prototype.toString = wrapperToString;
+    lodash.prototype.value = wrapperValueOf;
+    lodash.prototype.valueOf = wrapperValueOf;
+
+    // add `Array` functions that return unwrapped values
+    forEach(['join', 'pop', 'shift'], function(methodName) {
+      var func = arrayRef[methodName];
+      lodash.prototype[methodName] = function() {
+        var chainAll = this.__chain__,
+            result = func.apply(this.__wrapped__, arguments);
+
+        return chainAll
+          ? new lodashWrapper(result, chainAll)
+          : result;
+      };
+    });
+
+    // add `Array` functions that return the wrapped value
+    forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
+      var func = arrayRef[methodName];
+      lodash.prototype[methodName] = function() {
+        func.apply(this.__wrapped__, arguments);
+        return this;
+      };
+    });
+
+    // add `Array` functions that return new wrapped values
+    forEach(['concat', 'slice', 'splice'], function(methodName) {
+      var func = arrayRef[methodName];
+      lodash.prototype[methodName] = function() {
+        return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
+      };
+    });
+
+    return lodash;
+  }
+
+  /*--------------------------------------------------------------------------*/
+
+  // expose Lo-Dash
+  var _ = runInContext();
+
+  // some AMD build optimizers, like r.js, check for condition patterns like the following:
+  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
+    // Expose Lo-Dash to the global object even when an AMD loader is present in
+    // case Lo-Dash was injected by a third-party script and not intended to be
+    // loaded as a module. The global assignment can be reverted in the Lo-Dash
+    // module by its `noConflict()` method.
+    root._ = _;
+
+    // define as an anonymous module so, through path mapping, it can be
+    // referenced as the "underscore" module
+    define(function() {
+      return _;
+    });
+  }
+  // check for `exports` after `define` in case a build optimizer adds an `exports` object
+  else if (freeExports && freeModule) {
+    // in Node.js or RingoJS
+    if (moduleExports) {
+      (freeModule.exports = _)._ = _;
+    }
+    // in Narwhal or Rhino -require
+    else {
+      freeExports._ = _;
+    }
+  }
+  else {
+    // in a browser or Rhino
+    root._ = _;
+  }
+}.call(this));
+
+//     Backbone.js 1.0.0
+
+//     (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
+//     Backbone may be freely distributed under the MIT license.
+//     For all details and documentation:
+//     http://backbonejs.org
+
+(function(){
+
+  // Initial Setup
+  // -------------
+
+  // Save a reference to the global object (`window` in the browser, `exports`
+  // on the server).
+  var root = this;
+
+  // Save the previous value of the `Backbone` variable, so that it can be
+  // restored later on, if `noConflict` is used.
+  var previousBackbone = root.Backbone;
+
+  // Create local references to array methods we'll want to use later.
+  var array = [];
+  var push = array.push;
+  var slice = array.slice;
+  var splice = array.splice;
+
+  // The top-level namespace. All public Backbone classes and modules will
+  // be attached to this. Exported for both the browser and the server.
+  var Backbone;
+  if (typeof exports !== 'undefined') {
+    Backbone = exports;
+  } else {
+    Backbone = root.Backbone = {};
+  }
+
+  // Current version of the library. Keep in sync with `package.json`.
+  Backbone.VERSION = '1.0.0';
+
+  // Require Underscore, if we're on the server, and it's not already present.
+  var _ = root._;
+  if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
+
+  // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
+  // the `$` variable.
+  Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
+
+  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
+  // to its previous owner. Returns a reference to this Backbone object.
+  Backbone.noConflict = function() {
+    root.Backbone = previousBackbone;
+    return this;
+  };
+
+  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
+  // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
+  // set a `X-Http-Method-Override` header.
+  Backbone.emulateHTTP = false;
+
+  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
+  // `application/json` requests ... will encode the body as
+  // `application/x-www-form-urlencoded` instead and will send the model in a
+  // form param named `model`.
+  Backbone.emulateJSON = false;
+
+  // Backbone.Events
+  // ---------------
+
+  // A module that can be mixed in to *any object* in order to provide it with
+  // custom events. You may bind with `on` or remove with `off` callback
+  // functions to an event; `trigger`-ing an event fires all callbacks in
+  // succession.
+  //
+  //     var object = {};
+  //     _.extend(object, Backbone.Events);
+  //     object.on('expand', function(){ alert('expanded'); });
+  //     object.trigger('expand');
+  //
+  var Events = Backbone.Events = {
+
+    // Bind an event to a `callback` function. Passing `"all"` will bind
+    // the callback to all events fired.
+    on: function(name, callback, context) {
+      if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
+      this._events || (this._events = {});
+      var events = this._events[name] || (this._events[name] = []);
+      events.push({callback: callback, context: context, ctx: context || this});
+      return this;
+    },
+
+    // Bind an event to only be triggered a single time. After the first time
+    // the callback is invoked, it will be removed.
+    once: function(name, callback, context) {
+      if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
+      var self = this;
+      var once = _.once(function() {
+        self.off(name, once);
+        callback.apply(this, arguments);
+      });
+      once._callback = callback;
+      return this.on(name, once, context);
+    },
+
+    // Remove one or many callbacks. If `context` is null, removes all
+    // callbacks with that function. If `callback` is null, removes all
+    // callbacks for the event. If `name` is null, removes all bound
+    // callbacks for all events.
+    off: function(name, callback, context) {
+      var retain, ev, events, names, i, l, j, k;
+      if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
+      if (!name && !callback && !context) {
+        this._events = {};
+        return this;
+      }
+
+      names = name ? [name] : _.keys(this._events);
+      for (i = 0, l = names.length; i < l; i++) {
+        name = names[i];
+        if (events = this._events[name]) {
+          this._events[name] = retain = [];
+          if (callback || context) {
+            for (j = 0, k = events.length; j < k; j++) {
+              ev = events[j];
+              if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
+                  (context && context !== ev.context)) {
+                retain.push(ev);
+              }
+            }
+          }
+          if (!retain.length) delete this._events[name];
+        }
+      }
+
+      return this;
+    },
+
+    // Trigger one or many events, firing all bound callbacks. Callbacks are
+    // passed the same arguments as `trigger` is, apart from the event name
+    // (unless you're listening on `"all"`, which will cause your callback to
+    // receive the true name of the event as the first argument).
+    trigger: function(name) {
+      if (!this._events) return this;
+      var args = slice.call(arguments, 1);
+      if (!eventsApi(this, 'trigger', name, args)) return this;
+      var events = this._events[name];
+      var allEvents = this._events.all;
+      if (events) triggerEvents(events, args);
+      if (allEvents) triggerEvents(allEvents, arguments);
+      return this;
+    },
+
+    // Tell this object to stop listening to either specific events ... or
+    // to every object it's currently listening to.
+    stopListening: function(obj, name, callback) {
+      var listeners = this._listeners;
+      if (!listeners) return this;
+      var deleteListener = !name && !callback;
+      if (typeof name === 'object') callback = this;
+      if (obj) (listeners = {})[obj._listenerId] = obj;
+      for (var id in listeners) {
+        listeners[id].off(name, callback, this);
+        if (deleteListener) delete this._listeners[id];
+      }
+      return this;
+    }
+
+  };
+
+  // Regular expression used to split event strings.
+  var eventSplitter = /\s+/;
+
+  // Implement fancy features of the Events API such as multiple event
+  // names `"change blur"` and jQuery-style event maps `{change: action}`
+  // in terms of the existing API.
+  var eventsApi = function(obj, action, name, rest) {
+    if (!name) return true;
+
+    // Handle event maps.
+    if (typeof name === 'object') {
+      for (var key in name) {
+        obj[action].apply(obj, [key, name[key]].concat(rest));
+      }
+      return false;
+    }
+
+    // Handle space separated event names.
+    if (eventSplitter.test(name)) {
+      var names = name.split(eventSplitter);
+      for (var i = 0, l = names.length; i < l; i++) {
+        obj[action].apply(obj, [names[i]].concat(rest));
+      }
+      return false;
+    }
+
+    return true;
+  };
+
+  // A difficult-to-believe, but optimized internal dispatch function for
+  // triggering events. Tries to keep the usual cases speedy (most internal
+  // Backbone events have 3 arguments).
+  var triggerEvents = function(events, args) {
+    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
+    switch (args.length) {
+      case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
+      case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
+      case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
+      case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
+      default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
+    }
+  };
+
+  var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
+
+  // Inversion-of-control versions of `on` and `once`. Tell *this* object to
+  // listen to an event in another object ... keeping track of what it's
+  // listening to.
+  _.each(listenMethods, function(implementation, method) {
+    Events[method] = function(obj, name, callback) {
+      var listeners = this._listeners || (this._listeners = {});
+      var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
+      listeners[id] = obj;
+      if (typeof name === 'object') callback = this;
+      obj[implementation](name, callback, this);
+      return this;
+    };
+  });
+
+  // Aliases for backwards compatibility.
+  Events.bind   = Events.on;
+  Events.unbind = Events.off;
+
+  // Allow the `Backbone` object to serve as a global event bus, for folks who
+  // want global "pubsub" in a convenient place.
+  _.extend(Backbone, Events);
+
+  // Backbone.Model
+  // --------------
+
+  // Backbone **Models** are the basic data object in the framework --
+  // frequently representing a row in a table in a database on your server.
+  // A discrete chunk of data and a bunch of useful, related methods for
+  // performing computations and transformations on that data.
+
+  // Create a new model with the specified attributes. A client id (`cid`)
+  // is automatically generated and assigned for you.
+  var Model = Backbone.Model = function(attributes, options) {
+    var defaults;
+    var attrs = attributes || {};
+    options || (options = {});
+    this.cid = _.uniqueId('c');
+    this.attributes = {};
+    _.extend(this, _.pick(options, modelOptions));
+    if (options.parse) attrs = this.parse(attrs, options) || {};
+    if (defaults = _.result(this, 'defaults')) {
+      attrs = _.defaults({}, attrs, defaults);
+    }
+    this.set(attrs, options);
+    this.changed = {};
+    this.initialize.apply(this, arguments);
+  };
+
+  // A list of options to be attached directly to the model, if provided.
+  var modelOptions = ['url', 'urlRoot', 'collection'];
+
+  // Attach all inheritable methods to the Model prototype.
+  _.extend(Model.prototype, Events, {
+
+    // A hash of attributes whose current and previous value differ.
+    changed: null,
+
+    // The value returned during the last failed validation.
+    validationError: null,
+
+    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
+    // CouchDB users may want to set this to `"_id"`.
+    idAttribute: 'id',
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // Return a copy of the model's `attributes` object.
+    toJSON: function(options) {
+      return _.clone(this.attributes);
+    },
+
+    // Proxy `Backbone.sync` by default -- but override this if you need
+    // custom syncing semantics for *this* particular model.
+    sync: function() {
+      return Backbone.sync.apply(this, arguments);
+    },
+
+    // Get the value of an attribute.
+    get: function(attr) {
+      return this.attributes[attr];
+    },
+
+    // Get the HTML-escaped value of an attribute.
+    escape: function(attr) {
+      return _.escape(this.get(attr));
+    },
+
+    // Returns `true` if the attribute contains a value that is not null
+    // or undefined.
+    has: function(attr) {
+      return this.get(attr) != null;
+    },
+
+    // Set a hash of model attributes on the object, firing `"change"`. This is
+    // the core primitive operation of a model, updating the data and notifying
+    // anyone who needs to know about the change in state. The heart of the beast.
+    set: function(key, val, options) {
+      var attr, attrs, unset, changes, silent, changing, prev, current;
+      if (key == null) return this;
+
+      // Handle both `"key", value` and `{key: value}` -style arguments.
+      if (typeof key === 'object') {
+        attrs = key;
+        options = val;
+      } else {
+        (attrs = {})[key] = val;
+      }
+
+      options || (options = {});
+
+      // Run validation.
+      if (!this._validate(attrs, options)) return false;
+
+      // Extract attributes and options.
+      unset           = options.unset;
+      silent          = options.silent;
+      changes         = [];
+      changing        = this._changing;
+      this._changing  = true;
+
+      if (!changing) {
+        this._previousAttributes = _.clone(this.attributes);
+        this.changed = {};
+      }
+      current = this.attributes, prev = this._previousAttributes;
+
+      // Check for changes of `id`.
+      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
+
+      // For each `set` attribute, update or delete the current value.
+      for (attr in attrs) {
+        val = attrs[attr];
+        if (!_.isEqual(current[attr], val)) changes.push(attr);
+        if (!_.isEqual(prev[attr], val)) {
+          this.changed[attr] = val;
+        } else {
+          delete this.changed[attr];
+        }
+        unset ? delete current[attr] : current[attr] = val;
+      }
+
+      // Trigger all relevant attribute changes.
+      if (!silent) {
+        if (changes.length) this._pending = true;
+        for (var i = 0, l = changes.length; i < l; i++) {
+          this.trigger('change:' + changes[i], this, current[changes[i]], options);
+        }
+      }
+
+      // You might be wondering why there's a `while` loop here. Changes can
+      // be recursively nested within `"change"` events.
+      if (changing) return this;
+      if (!silent) {
+        while (this._pending) {
+          this._pending = false;
+          this.trigger('change', this, options);
+        }
+      }
+      this._pending = false;
+      this._changing = false;
+      return this;
+    },
+
+    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
+    // if the attribute doesn't exist.
+    unset: function(attr, options) {
+      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
+    },
+
+    // Clear all attributes on the model, firing `"change"`.
+    clear: function(options) {
+      var attrs = {};
+      for (var key in this.attributes) attrs[key] = void 0;
+      return this.set(attrs, _.extend({}, options, {unset: true}));
+    },
+
+    // Determine if the model has changed since the last `"change"` event.
+    // If you specify an attribute name, determine if that attribute has changed.
+    hasChanged: function(attr) {
+      if (attr == null) return !_.isEmpty(this.changed);
+      return _.has(this.changed, attr);
+    },
+
+    // Return an object containing all the attributes that have changed, or
+    // false if there are no changed attributes. Useful for determining what
+    // parts of a view need to be updated and/or what attributes need to be
+    // persisted to the server. Unset attributes will be set to undefined.
+    // You can also pass an attributes object to diff against the model,
+    // determining if there *would be* a change.
+    changedAttributes: function(diff) {
+      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
+      var val, changed = false;
+      var old = this._changing ? this._previousAttributes : this.attributes;
+      for (var attr in diff) {
+        if (_.isEqual(old[attr], (val = diff[attr]))) continue;
+        (changed || (changed = {}))[attr] = val;
+      }
+      return changed;
+    },
+
+    // Get the previous value of an attribute, recorded at the time the last
+    // `"change"` event was fired.
+    previous: function(attr) {
+      if (attr == null || !this._previousAttributes) return null;
+      return this._previousAttributes[attr];
+    },
+
+    // Get all of the attributes of the model at the time of the previous
+    // `"change"` event.
+    previousAttributes: function() {
+      return _.clone(this._previousAttributes);
+    },
+
+    // Fetch the model from the server. If the server's representation of the
+    // model differs from its current attributes, they will be overridden,
+    // triggering a `"change"` event.
+    fetch: function(options) {
+      options = options ? _.clone(options) : {};
+      if (options.parse === void 0) options.parse = true;
+      var model = this;
+      var success = options.success;
+      options.success = function(resp) {
+        if (!model.set(model.parse(resp, options), options)) return false;
+        if (success) success(model, resp, options);
+        model.trigger('sync', model, resp, options);
+      };
+      wrapError(this, options);
+      return this.sync('read', this, options);
+    },
+
+    // Set a hash of model attributes, and sync the model to the server.
+    // If the server returns an attributes hash that differs, the model's
+    // state will be `set` again.
+    save: function(key, val, options) {
+      var attrs, method, xhr, attributes = this.attributes;
+
+      // Handle both `"key", value` and `{key: value}` -style arguments.
+      if (key == null || typeof key === 'object') {
+        attrs = key;
+        options = val;
+      } else {
+        (attrs = {})[key] = val;
+      }
+
+      // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
+      if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
+
+      options = _.extend({validate: true}, options);
+
+      // Do not persist invalid models.
+      if (!this._validate(attrs, options)) return false;
+
+      // Set temporary attributes if `{wait: true}`.
+      if (attrs && options.wait) {
+        this.attributes = _.extend({}, attributes, attrs);
+      }
+
+      // After a successful server-side save, the client is (optionally)
+      // updated with the server-side state.
+      if (options.parse === void 0) options.parse = true;
+      var model = this;
+      var success = options.success;
+      options.success = function(resp) {
+        // Ensure attributes are restored during synchronous saves.
+        model.attributes = attributes;
+        var serverAttrs = model.parse(resp, options);
+        if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
+        if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
+          return false;
+        }
+        if (success) success(model, resp, options);
+        model.trigger('sync', model, resp, options);
+      };
+      wrapError(this, options);
+
+      method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
+      if (method === 'patch') options.attrs = attrs;
+      xhr = this.sync(method, this, options);
+
+      // Restore attributes.
+      if (attrs && options.wait) this.attributes = attributes;
+
+      return xhr;
+    },
+
+    // Destroy this model on the server if it was already persisted.
+    // Optimistically removes the model from its collection, if it has one.
+    // If `wait: true` is passed, waits for the server to respond before removal.
+    destroy: function(options) {
+      options = options ? _.clone(options) : {};
+      var model = this;
+      var success = options.success;
+
+      var destroy = function() {
+        model.trigger('destroy', model, model.collection, options);
+      };
+
+      options.success = function(resp) {
+        if (options.wait || model.isNew()) destroy();
+        if (success) success(model, resp, options);
+        if (!model.isNew()) model.trigger('sync', model, resp, options);
+      };
+
+      if (this.isNew()) {
+        options.success();
+        return false;
+      }
+      wrapError(this, options);
+
+      var xhr = this.sync('delete', this, options);
+      if (!options.wait) destroy();
+      return xhr;
+    },
+
+    // Default URL for the model's representation on the server -- if you're
+    // using Backbone's restful methods, override this to change the endpoint
+    // that will be called.
+    url: function() {
+      var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
+      if (this.isNew()) return base;
+      return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
+    },
+
+    // **parse** converts a response into the hash of attributes to be `set` on
+    // the model. The default implementation is just to pass the response along.
+    parse: function(resp, options) {
+      return resp;
+    },
+
+    // Create a new model with identical attributes to this one.
+    clone: function() {
+      return new this.constructor(this.attributes);
+    },
+
+    // A model is new if it has never been saved to the server, and lacks an id.
+    isNew: function() {
+      return this.id == null;
+    },
+
+    // Check if the model is currently in a valid state.
+    isValid: function(options) {
+      return this._validate({}, _.extend(options || {}, { validate: true }));
+    },
+
+    // Run validation against the next complete set of model attributes,
+    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
+    _validate: function(attrs, options) {
+      if (!options.validate || !this.validate) return true;
+      attrs = _.extend({}, this.attributes, attrs);
+      var error = this.validationError = this.validate(attrs, options) || null;
+      if (!error) return true;
+      this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
+      return false;
+    }
+
+  });
+
+  // Underscore methods that we want to implement on the Model.
+  var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
+
+  // Mix in each Underscore method as a proxy to `Model#attributes`.
+  _.each(modelMethods, function(method) {
+    Model.prototype[method] = function() {
+      var args = slice.call(arguments);
+      args.unshift(this.attributes);
+      return _[method].apply(_, args);
+    };
+  });
+
+  // Backbone.Collection
+  // -------------------
+
+  // If models tend to represent a single row of data, a Backbone Collection is
+  // more analagous to a table full of data ... or a small slice or page of that
+  // table, or a collection of rows that belong together for a particular reason
+  // -- all of the messages in this particular folder, all of the documents
+  // belonging to this particular author, and so on. Collections maintain
+  // indexes of their models, both in order, and for lookup by `id`.
+
+  // Create a new **Collection**, perhaps to contain a specific type of `model`.
+  // If a `comparator` is specified, the Collection will maintain
+  // its models in sort order, as they're added and removed.
+  var Collection = Backbone.Collection = function(models, options) {
+    options || (options = {});
+    if (options.url) this.url = options.url;
+    if (options.model) this.model = options.model;
+    if (options.comparator !== void 0) this.comparator = options.comparator;
+    this._reset();
+    this.initialize.apply(this, arguments);
+    if (models) this.reset(models, _.extend({silent: true}, options));
+  };
+
+  // Default options for `Collection#set`.
+  var setOptions = {add: true, remove: true, merge: true};
+  var addOptions = {add: true, merge: false, remove: false};
+
+  // Define the Collection's inheritable methods.
+  _.extend(Collection.prototype, Events, {
+
+    // The default model for a collection is just a **Backbone.Model**.
+    // This should be overridden in most cases.
+    model: Model,
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // The JSON representation of a Collection is an array of the
+    // models' attributes.
+    toJSON: function(options) {
+      return this.map(function(model){ return model.toJSON(options); });
+    },
+
+    // Proxy `Backbone.sync` by default.
+    sync: function() {
+      return Backbone.sync.apply(this, arguments);
+    },
+
+    // Add a model, or list of models to the set.
+    add: function(models, options) {
+      return this.set(models, _.defaults(options || {}, addOptions));
+    },
+
+    // Remove a model, or a list of models from the set.
+    remove: function(models, options) {
+      models = _.isArray(models) ? models.slice() : [models];
+      options || (options = {});
+      var i, l, index, model;
+      for (i = 0, l = models.length; i < l; i++) {
+        model = this.get(models[i]);
+        if (!model) continue;
+        delete this._byId[model.id];
+        delete this._byId[model.cid];
+        index = this.indexOf(model);
+        this.models.splice(index, 1);
+        this.length--;
+        if (!options.silent) {
+          options.index = index;
+          model.trigger('remove', model, this, options);
+        }
+        this._removeReference(model);
+      }
+      return this;
+    },
+
+    // Update a collection by `set`-ing a new list of models, adding new ones,
+    // removing models that are no longer present, and merging models that
+    // already exist in the collection, as necessary. Similar to **Model#set**,
+    // the core operation for updating the data contained by the collection.
+    set: function(models, options) {
+      options = _.defaults(options || {}, setOptions);
+      if (options.parse) models = this.parse(models, options);
+      if (!_.isArray(models)) models = models ? [models] : [];
+      var i, l, model, attrs, existing, sort;
+      var at = options.at;
+      var sortable = this.comparator && (at == null) && options.sort !== false;
+      var sortAttr = _.isString(this.comparator) ? this.comparator : null;
+      var toAdd = [], toRemove = [], modelMap = {};
+
+      // Turn bare objects into model references, and prevent invalid models
+      // from being added.
+      for (i = 0, l = models.length; i < l; i++) {
+        if (!(model = this._prepareModel(models[i], options))) continue;
+
+        // If a duplicate is found, prevent it from being added and
+        // optionally merge it into the existing model.
+        if (existing = this.get(model)) {
+          if (options.remove) modelMap[existing.cid] = true;
+          if (options.merge) {
+            existing.set(model.attributes, options);
+            if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
+          }
+
+        // This is a new model, push it to the `toAdd` list.
+        } else if (options.add) {
+          toAdd.push(model);
+
+          // Listen to added models' events, and index models for lookup by
+          // `id` and by `cid`.
+          model.on('all', this._onModelEvent, this);
+          this._byId[model.cid] = model;
+          if (model.id != null) this._byId[model.id] = model;
+        }
+      }
+
+      // Remove nonexistent models if appropriate.
+      if (options.remove) {
+        for (i = 0, l = this.length; i < l; ++i) {
+          if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
+        }
+        if (toRemove.length) this.remove(toRemove, options);
+      }
+
+      // See if sorting is needed, update `length` and splice in new models.
+      if (toAdd.length) {
+        if (sortable) sort = true;
+        this.length += toAdd.length;
+        if (at != null) {
+          splice.apply(this.models, [at, 0].concat(toAdd));
+        } else {
+          push.apply(this.models, toAdd);
+        }
+      }
+
+      // Silently sort the collection if appropriate.
+      if (sort) this.sort({silent: true});
+
+      if (options.silent) return this;
+
+      // Trigger `add` events.
+      for (i = 0, l = toAdd.length; i < l; i++) {
+        (model = toAdd[i]).trigger('add', model, this, options);
+      }
+
+      // Trigger `sort` if the collection was sorted.
+      if (sort) this.trigger('sort', this, options);
+      return this;
+    },
+
+    // When you have more items than you want to add or remove individually,
+    // you can reset the entire set with a new list of models, without firing
+    // any granular `add` or `remove` events. Fires `reset` when finished.
+    // Useful for bulk operations and optimizations.
+    reset: function(models, options) {
+      options || (options = {});
+      for (var i = 0, l = this.models.length; i < l; i++) {
+        this._removeReference(this.models[i]);
+      }
+      options.previousModels = this.models;
+      this._reset();
+      this.add(models, _.extend({silent: true}, options));
+      if (!options.silent) this.trigger('reset', this, options);
+      return this;
+    },
+
+    // Add a model to the end of the collection.
+    push: function(model, options) {
+      model = this._prepareModel(model, options);
+      this.add(model, _.extend({at: this.length}, options));
+      return model;
+    },
+
+    // Remove a model from the end of the collection.
+    pop: function(options) {
+      var model = this.at(this.length - 1);
+      this.remove(model, options);
+      return model;
+    },
+
+    // Add a model to the beginning of the collection.
+    unshift: function(model, options) {
+      model = this._prepareModel(model, options);
+      this.add(model, _.extend({at: 0}, options));
+      return model;
+    },
+
+    // Remove a model from the beginning of the collection.
+    shift: function(options) {
+      var model = this.at(0);
+      this.remove(model, options);
+      return model;
+    },
+
+    // Slice out a sub-array of models from the collection.
+    slice: function(begin, end) {
+      return this.models.slice(begin, end);
+    },
+
+    // Get a model from the set by id.
+    get: function(obj) {
+      if (obj == null) return void 0;
+      return this._byId[obj.id != null ? obj.id : obj.cid || obj];
+    },
+
+    // Get the model at the given index.
+    at: function(index) {
+      return this.models[index];
+    },
+
+    // Return models with matching attributes. Useful for simple cases of
+    // `filter`.
+    where: function(attrs, first) {
+      if (_.isEmpty(attrs)) return first ? void 0 : [];
+      return this[first ? 'find' : 'filter'](function(model) {
+        for (var key in attrs) {
+          if (attrs[key] !== model.get(key)) return false;
+        }
+        return true;
+      });
+    },
+
+    // Return the first model with matching attributes. Useful for simple cases
+    // of `find`.
+    findWhere: function(attrs) {
+      return this.where(attrs, true);
+    },
+
+    // Force the collection to re-sort itself. You don't need to call this under
+    // normal circumstances, as the set will maintain sort order as each item
+    // is added.
+    sort: function(options) {
+      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
+      options || (options = {});
+
+      // Run sort based on type of `comparator`.
+      if (_.isString(this.comparator) || this.comparator.length === 1) {
+        this.models = this.sortBy(this.comparator, this);
+      } else {
+        this.models.sort(_.bind(this.comparator, this));
+      }
+
+      if (!options.silent) this.trigger('sort', this, options);
+      return this;
+    },
+
+    // Figure out the smallest index at which a model should be inserted so as
+    // to maintain order.
+    sortedIndex: function(model, value, context) {
+      value || (value = this.comparator);
+      var iterator = _.isFunction(value) ? value : function(model) {
+        return model.get(value);
+      };
+      return _.sortedIndex(this.models, model, iterator, context);
+    },
+
+    // Pluck an attribute from each model in the collection.
+    pluck: function(attr) {
+      return _.invoke(this.models, 'get', attr);
+    },
+
+    // Fetch the default set of models for this collection, resetting the
+    // collection when they arrive. If `reset: true` is passed, the response
+    // data will be passed through the `reset` method instead of `set`.
+    fetch: function(options) {
+      options = options ? _.clone(options) : {};
+      if (options.parse === void 0) options.parse = true;
+      var success = options.success;
+      var collection = this;
+      options.success = function(resp) {
+        var method = options.reset ? 'reset' : 'set';
+        collection[method](resp, options);
+        if (success) success(collection, resp, options);
+        collection.trigger('sync', collection, resp, options);
+      };
+      wrapError(this, options);
+      return this.sync('read', this, options);
+    },
+
+    // Create a new instance of a model in this collection. Add the model to the
+    // collection immediately, unless `wait: true` is passed, in which case we
+    // wait for the server to agree.
+    create: function(model, options) {
+      options = options ? _.clone(options) : {};
+      if (!(model = this._prepareModel(model, options))) return false;
+      if (!options.wait) this.add(model, options);
+      var collection = this;
+      var success = options.success;
+      options.success = function(resp) {
+        if (options.wait) collection.add(model, options);
+        if (success) success(model, resp, options);
+      };
+      model.save(null, options);
+      return model;
+    },
+
+    // **parse** converts a response into a list of models to be added to the
+    // collection. The default implementation is just to pass it through.
+    parse: function(resp, options) {
+      return resp;
+    },
+
+    // Create a new collection with an identical list of models as this one.
+    clone: function() {
+      return new this.constructor(this.models);
+    },
+
+    // Private method to reset all internal state. Called when the collection
+    // is first initialized or reset.
+    _reset: function() {
+      this.length = 0;
+      this.models = [];
+      this._byId  = {};
+    },
+
+    // Prepare a hash of attributes (or other model) to be added to this
+    // collection.
+    _prepareModel: function(attrs, options) {
+      if (attrs instanceof Model) {
+        if (!attrs.collection) attrs.collection = this;
+        return attrs;
+      }
+      options || (options = {});
+      options.collection = this;
+      var model = new this.model(attrs, options);
+      if (!model._validate(attrs, options)) {
+        this.trigger('invalid', this, attrs, options);
+        return false;
+      }
+      return model;
+    },
+
+    // Internal method to sever a model's ties to a collection.
+    _removeReference: function(model) {
+      if (this === model.collection) delete model.collection;
+      model.off('all', this._onModelEvent, this);
+    },
+
+    // Internal method called every time a model in the set fires an event.
+    // Sets need to update their indexes when models change ids. All other
+    // events simply proxy through. "add" and "remove" events that originate
+    // in other collections are ignored.
+    _onModelEvent: function(event, model, collection, options) {
+      if ((event === 'add' || event === 'remove') && collection !== this) return;
+      if (event === 'destroy') this.remove(model, options);
+      if (model && event === 'change:' + model.idAttribute) {
+        delete this._byId[model.previous(model.idAttribute)];
+        if (model.id != null) this._byId[model.id] = model;
+      }
+      this.trigger.apply(this, arguments);
+    }
+
+  });
+
+  // Underscore methods that we want to implement on the Collection.
+  // 90% of the core usefulness of Backbone Collections is actually implemented
+  // right here:
+  var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
+    'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
+    'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
+    'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
+    'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
+    'isEmpty', 'chain'];
+
+  // Mix in each Underscore method as a proxy to `Collection#models`.
+  _.each(methods, function(method) {
+    Collection.prototype[method] = function() {
+      var args = slice.call(arguments);
+      args.unshift(this.models);
+      return _[method].apply(_, args);
+    };
+  });
+
+  // Underscore methods that take a property name as an argument.
+  var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
+
+  // Use attributes instead of properties.
+  _.each(attributeMethods, function(method) {
+    Collection.prototype[method] = function(value, context) {
+      var iterator = _.isFunction(value) ? value : function(model) {
+        return model.get(value);
+      };
+      return _[method](this.models, iterator, context);
+    };
+  });
+
+  // Backbone.View
+  // -------------
+
+  // Backbone Views are almost more convention than they are actual code. A View
+  // is simply a JavaScript object that represents a logical chunk of UI in the
+  // DOM. This might be a single item, an entire list, a sidebar or panel, or
+  // even the surrounding frame which wraps your whole app. Defining a chunk of
+  // UI as a **View** allows you to define your DOM events declaratively, without
+  // having to worry about render order ... and makes it easy for the view to
+  // react to specific changes in the state of your models.
+
+  // Creating a Backbone.View creates its initial element outside of the DOM,
+  // if an existing element is not provided...
+  var View = Backbone.View = function(options) {
+    this.cid = _.uniqueId('view');
+    this._configure(options || {});
+    this._ensureElement();
+    this.initialize.apply(this, arguments);
+    this.delegateEvents();
+  };
+
+  // Cached regex to split keys for `delegate`.
+  var delegateEventSplitter = /^(\S+)\s*(.*)$/;
+
+  // List of view options to be merged as properties.
+  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
+
+  // Set up all inheritable **Backbone.View** properties and methods.
+  _.extend(View.prototype, Events, {
+
+    // The default `tagName` of a View's element is `"div"`.
+    tagName: 'div',
+
+    // jQuery delegate for element lookup, scoped to DOM elements within the
+    // current view. This should be prefered to global lookups where possible.
+    $: function(selector) {
+      return this.$el.find(selector);
+    },
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // **render** is the core function that your view should override, in order
+    // to populate its element (`this.el`), with the appropriate HTML. The
+    // convention is for **render** to always return `this`.
+    render: function() {
+      return this;
+    },
+
+    // Remove this view by taking the element out of the DOM, and removing any
+    // applicable Backbone.Events listeners.
+    remove: function() {
+      this.$el.remove();
+      this.stopListening();
+      return this;
+    },
+
+    // Change the view's element (`this.el` property), including event
+    // re-delegation.
+    setElement: function(element, delegate) {
+      if (this.$el) this.undelegateEvents();
+      this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
+      this.el = this.$el[0];
+      if (delegate !== false) this.delegateEvents();
+      return this;
+    },
+
+    // Set callbacks, where `this.events` is a hash of
+    //
+    // *{"event selector": "callback"}*
+    //
+    //     {
+    //       'mousedown .title':  'edit',
+    //       'click .button':     'save'
+    //       'click .open':       function(e) { ... }
+    //     }
+    //
+    // pairs. Callbacks will be bound to the view, with `this` set properly.
+    // Uses event delegation for efficiency.
+    // Omitting the selector binds the event to `this.el`.
+    // This only works for delegate-able events: not `focus`, `blur`, and
+    // not `change`, `submit`, and `reset` in Internet Explorer.
+    delegateEvents: function(events) {
+      if (!(events || (events = _.result(this, 'events')))) return this;
+      this.undelegateEvents();
+      for (var key in events) {
+        var method = events[key];
+        if (!_.isFunction(method)) method = this[events[key]];
+        if (!method) continue;
+
+        var match = key.match(delegateEventSplitter);
+        var eventName = match[1], selector = match[2];
+        method = _.bind(method, this);
+        eventName += '.delegateEvents' + this.cid;
+        if (selector === '') {
+          this.$el.on(eventName, method);
+        } else {
+          this.$el.on(eventName, selector, method);
+        }
+      }
+      return this;
+    },
+
+    // Clears all callbacks previously bound to the view with `delegateEvents`.
+    // You usually don't need to use this, but may wish to if you have multiple
+    // Backbone views attached to the same DOM element.
+    undelegateEvents: function() {
+      this.$el.off('.delegateEvents' + this.cid);
+      return this;
+    },
+
+    // Performs the initial configuration of a View with a set of options.
+    // Keys with special meaning *(e.g. model, collection, id, className)* are
+    // attached directly to the view.  See `viewOptions` for an exhaustive
+    // list.
+    _configure: function(options) {
+      if (this.options) options = _.extend({}, _.result(this, 'options'), options);
+      _.extend(this, _.pick(options, viewOptions));
+      this.options = options;
+    },
+
+    // Ensure that the View has a DOM element to render into.
+    // If `this.el` is a string, pass it through `$()`, take the first
+    // matching element, and re-assign it to `el`. Otherwise, create
+    // an element from the `id`, `className` and `tagName` properties.
+    _ensureElement: function() {
+      if (!this.el) {
+        var attrs = _.extend({}, _.result(this, 'attributes'));
+        if (this.id) attrs.id = _.result(this, 'id');
+        if (this.className) attrs['class'] = _.result(this, 'className');
+        var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
+        this.setElement($el, false);
+      } else {
+        this.setElement(_.result(this, 'el'), false);
+      }
+    }
+
+  });
+
+  // Backbone.sync
+  // -------------
+
+  // Override this function to change the manner in which Backbone persists
+  // models to the server. You will be passed the type of request, and the
+  // model in question. By default, makes a RESTful Ajax request
+  // to the model's `url()`. Some possible customizations could be:
+  //
+  // * Use `setTimeout` to batch rapid-fire updates into a single request.
+  // * Send up the models as XML instead of JSON.
+  // * Persist models via WebSockets instead of Ajax.
+  //
+  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
+  // as `POST`, with a `_method` parameter containing the true HTTP method,
+  // as well as all requests with the body as `application/x-www-form-urlencoded`
+  // instead of `application/json` with the model in a param named `model`.
+  // Useful when interfacing with server-side languages like **PHP** that make
+  // it difficult to read the body of `PUT` requests.
+  Backbone.sync = function(method, model, options) {
+    var type = methodMap[method];
+
+    // Default options, unless specified.
+    _.defaults(options || (options = {}), {
+      emulateHTTP: Backbone.emulateHTTP,
+      emulateJSON: Backbone.emulateJSON
+    });
+
+    // Default JSON-request options.
+    var params = {type: type, dataType: 'json'};
+
+    // Ensure that we have a URL.
+    if (!options.url) {
+      params.url = _.result(model, 'url') || urlError();
+    }
+
+    // Ensure that we have the appropriate request data.
+    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
+      params.contentType = 'application/json';
+      params.data = JSON.stringify(options.attrs || model.toJSON(options));
+    }
+
+    // For older servers, emulate JSON by encoding the request into an HTML-form.
+    if (options.emulateJSON) {
+      params.contentType = 'application/x-www-form-urlencoded';
+      params.data = params.data ? {model: params.data} : {};
+    }
+
+    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
+    // And an `X-HTTP-Method-Override` header.
+    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
+      params.type = 'POST';
+      if (options.emulateJSON) params.data._method = type;
+      var beforeSend = options.beforeSend;
+      options.beforeSend = function(xhr) {
+        xhr.setRequestHeader('X-HTTP-Method-Override', type);
+        if (beforeSend) return beforeSend.apply(this, arguments);
+      };
+    }
+
+    // Don't process data on a non-GET request.
+    if (params.type !== 'GET' && !options.emulateJSON) {
+      params.processData = false;
+    }
+
+    // If we're sending a `PATCH` request, and we're in an old Internet Explorer
+    // that still has ActiveX enabled by default, override jQuery to use that
+    // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
+    if (params.type === 'PATCH' && window.ActiveXObject &&
+          !(window.external && window.external.msActiveXFilteringEnabled)) {
+      params.xhr = function() {
+        return new ActiveXObject("Microsoft.XMLHTTP");
+      };
+    }
+
+    // Make the request, allowing the user to override any Ajax options.
+    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
+    model.trigger('request', model, xhr, options);
+    return xhr;
+  };
+
+  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
+  var methodMap = {
+    'create': 'POST',
+    'update': 'PUT',
+    'patch':  'PATCH',
+    'delete': 'DELETE',
+    'read':   'GET'
+  };
+
+  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
+  // Override this if you'd like to use a different library.
+  Backbone.ajax = function() {
+    return Backbone.$.ajax.apply(Backbone.$, arguments);
+  };
+
+  // Backbone.Router
+  // ---------------
+
+  // Routers map faux-URLs to actions, and fire events when routes are
+  // matched. Creating a new one sets its `routes` hash, if not set statically.
+  var Router = Backbone.Router = function(options) {
+    options || (options = {});
+    if (options.routes) this.routes = options.routes;
+    this._bindRoutes();
+    this.initialize.apply(this, arguments);
+  };
+
+  // Cached regular expressions for matching named param parts and splatted
+  // parts of route strings.
+  var optionalParam = /\((.*?)\)/g;
+  var namedParam    = /(\(\?)?:\w+/g;
+  var splatParam    = /\*\w+/g;
+  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
+
+  // Set up all inheritable **Backbone.Router** properties and methods.
+  _.extend(Router.prototype, Events, {
+
+    // Initialize is an empty function by default. Override it with your own
+    // initialization logic.
+    initialize: function(){},
+
+    // Manually bind a single named route to a callback. For example:
+    //
+    //     this.route('search/:query/p:num', 'search', function(query, num) {
+    //       ...
+    //     });
+    //
+    route: function(route, name, callback) {
+      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
+      if (_.isFunction(name)) {
+        callback = name;
+        name = '';
+      }
+      if (!callback) callback = this[name];
+      var router = this;
+      Backbone.history.route(route, function(fragment) {
+        var args = router._extractParameters(route, fragment);
+        callback && callback.apply(router, args);
+        router.trigger.apply(router, ['route:' + name].concat(args));
+        router.trigger('route', name, args);
+        Backbone.history.trigger('route', router, name, args);
+      });
+      return this;
+    },
+
+    // Simple proxy to `Backbone.history` to save a fragment into the history.
+    navigate: function(fragment, options) {
+      Backbone.history.navigate(fragment, options);
+      return this;
+    },
+
+    // Bind all defined routes to `Backbone.history`. We have to reverse the
+    // order of the routes here to support behavior where the most general
+    // routes can be defined at the bottom of the route map.
+    _bindRoutes: function() {
+      if (!this.routes) return;
+      this.routes = _.result(this, 'routes');
+      var route, routes = _.keys(this.routes);
+      while ((route = routes.pop()) != null) {
+        this.route(route, this.routes[route]);
+      }
+    },
+
+    // Convert a route string into a regular expression, suitable for matching
+    // against the current location hash.
+    _routeToRegExp: function(route) {
+      route = route.replace(escapeRegExp, '\\$&')
+                   .replace(optionalParam, '(?:$1)?')
+                   .replace(namedParam, function(match, optional){
+                     return optional ? match : '([^\/]+)';
+                   })
+                   .replace(splatParam, '(.*?)');
+      return new RegExp('^' + route + '$');
+    },
+
+    // Given a route, and a URL fragment that it matches, return the array of
+    // extracted decoded parameters. Empty or unmatched parameters will be
+    // treated as `null` to normalize cross-browser behavior.
+    _extractParameters: function(route, fragment) {
+      var params = route.exec(fragment).slice(1);
+      return _.map(params, function(param) {
+        return param ? decodeURIComponent(param) : null;
+      });
+    }
+
+  });
+
+  // Backbone.History
+  // ----------------
+
+  // Handles cross-browser history management, based on either
+  // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
+  // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
+  // and URL fragments. If the browser supports neither (old IE, natch),
+  // falls back to polling.
+  var History = Backbone.History = function() {
+    this.handlers = [];
+    _.bindAll(this, 'checkUrl');
+
+    // Ensure that `History` can be used outside of the browser.
+    if (typeof window !== 'undefined') {
+      this.location = window.location;
+      this.history = window.history;
+    }
+  };
+
+  // Cached regex for stripping a leading hash/slash and trailing space.
+  var routeStripper = /^[#\/]|\s+$/g;
+
+  // Cached regex for stripping leading and trailing slashes.
+  var rootStripper = /^\/+|\/+$/g;
+
+  // Cached regex for detecting MSIE.
+  var isExplorer = /msie [\w.]+/;
+
+  // Cached regex for removing a trailing slash.
+  var trailingSlash = /\/$/;
+
+  // Has the history handling already been started?
+  History.started = false;
+
+  // Set up all inheritable **Backbone.History** properties and methods.
+  _.extend(History.prototype, Events, {
+
+    // The default interval to poll for hash changes, if necessary, is
+    // twenty times a second.
+    interval: 50,
+
+    // Gets the true hash value. Cannot use location.hash directly due to bug
+    // in Firefox where location.hash will always be decoded.
+    getHash: function(window) {
+      var match = (window || this).location.href.match(/#(.*)$/);
+      return match ? match[1] : '';
+    },
+
+    // Get the cross-browser normalized URL fragment, either from the URL,
+    // the hash, or the override.
+    getFragment: function(fragment, forcePushState) {
+      if (fragment == null) {
+        if (this._hasPushState || !this._wantsHashChange || forcePushState) {
+          fragment = this.location.pathname;
+          var root = this.root.replace(trailingSlash, '');
+          if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
+        } else {
+          fragment = this.getHash();
+        }
+      }
+      return fragment.replace(routeStripper, '');
+    },
+
+    // Start the hash change handling, returning `true` if the current URL matches
+    // an existing route, and `false` otherwise.
+    start: function(options) {
+      if (History.started) throw new Error("Backbone.history has already been started");
+      History.started = true;
+
+      // Figure out the initial configuration. Do we need an iframe?
+      // Is pushState desired ... is it available?
+      this.options          = _.extend({}, {root: '/'}, this.options, options);
+      this.root             = this.options.root;
+      this._wantsHashChange = this.options.hashChange !== false;
+      this._wantsPushState  = !!this.options.pushState;
+      this._hasPushState    = !!(this.options.pushState && this.history && this.history.pushState);
+      var fragment          = this.getFragment();
+      var docMode           = document.documentMode;
+      var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
+
+      // Normalize root to always include a leading and trailing slash.
+      this.root = ('/' + this.root + '/').replace(rootStripper, '/');
+
+      if (oldIE && this._wantsHashChange) {
+        this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
+        this.navigate(fragment);
+      }
+
+      // Depending on whether we're using pushState or hashes, and whether
+      // 'onhashchange' is supported, determine how we check the URL state.
+      if (this._hasPushState) {
+        Backbone.$(window).on('popstate', this.checkUrl);
+      } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
+        Backbone.$(window).on('hashchange', this.checkUrl);
+      } else if (this._wantsHashChange) {
+        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
+      }
+
+      // Determine if we need to change the base url, for a pushState link
+      // opened by a non-pushState browser.
+      this.fragment = fragment;
+      var loc = this.location;
+      var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
+
+      // If we've started off with a route from a `pushState`-enabled browser,
+      // but we're currently in a browser that doesn't support it...
+      if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
+        this.fragment = this.getFragment(null, true);
+        this.location.replace(this.root + this.location.search + '#' + this.fragment);
+        // Return immediately as browser will do redirect to new url
+        return true;
+
+      // Or if we've started out with a hash-based route, but we're currently
+      // in a browser where it could be `pushState`-based instead...
+      } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
+        this.fragment = this.getHash().replace(routeStripper, '');
+        this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
+      }
+
+      if (!this.options.silent) return this.loadUrl();
+    },
+
+    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
+    // but possibly useful for unit testing Routers.
+    stop: function() {
+      Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
+      clearInterval(this._checkUrlInterval);
+      History.started = false;
+    },
+
+    // Add a route to be tested when the fragment changes. Routes added later
+    // may override previous routes.
+    route: function(route, callback) {
+      this.handlers.unshift({route: route, callback: callback});
+    },
+
+    // Checks the current URL to see if it has changed, and if it has,
+    // calls `loadUrl`, normalizing across the hidden iframe.
+    checkUrl: function(e) {
+      var current = this.getFragment();
+      if (current === this.fragment && this.iframe) {
+        current = this.getFragment(this.getHash(this.iframe));
+      }
+      if (current === this.fragment) return false;
+      if (this.iframe) this.navigate(current);
+      this.loadUrl() || this.loadUrl(this.getHash());
+    },
+
+    // Attempt to load the current URL fragment. If a route succeeds with a
+    // match, returns `true`. If no defined routes matches the fragment,
+    // returns `false`.
+    loadUrl: function(fragmentOverride) {
+      var fragment = this.fragment = this.getFragment(fragmentOverride);
+      var matched = _.any(this.handlers, function(handler) {
+        if (handler.route.test(fragment)) {
+          handler.callback(fragment);
+          return true;
+        }
+      });
+      return matched;
+    },
+
+    // Save a fragment into the hash history, or replace the URL state if the
+    // 'replace' option is passed. You are responsible for properly URL-encoding
+    // the fragment in advance.
+    //
+    // The options object can contain `trigger: true` if you wish to have the
+    // route callback be fired (not usually desirable), or `replace: true`, if
+    // you wish to modify the current URL without adding an entry to the history.
+    navigate: function(fragment, options) {
+      if (!History.started) return false;
+      if (!options || options === true) options = {trigger: options};
+      fragment = this.getFragment(fragment || '');
+      if (this.fragment === fragment) return;
+      this.fragment = fragment;
+      var url = this.root + fragment;
+
+      // If pushState is available, we use it to set the fragment as a real URL.
+      if (this._hasPushState) {
+        this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
+
+      // If hash changes haven't been explicitly disabled, update the hash
+      // fragment to store history.
+      } else if (this._wantsHashChange) {
+        this._updateHash(this.location, fragment, options.replace);
+        if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
+          // Opening and closing the iframe tricks IE7 and earlier to push a
+          // history entry on hash-tag change.  When replace is true, we don't
+          // want this.
+          if(!options.replace) this.iframe.document.open().close();
+          this._updateHash(this.iframe.location, fragment, options.replace);
+        }
+
+      // If you've told us that you explicitly don't want fallback hashchange-
+      // based history, then `navigate` becomes a page refresh.
+      } else {
+        return this.location.assign(url);
+      }
+      if (options.trigger) this.loadUrl(fragment);
+    },
+
+    // Update the hash location, either replacing the current entry, or adding
+    // a new one to the browser history.
+    _updateHash: function(location, fragment, replace) {
+      if (replace) {
+        var href = location.href.replace(/(javascript:|#).*$/, '');
+        location.replace(href + '#' + fragment);
+      } else {
+        // Some browsers require that `hash` contains a leading #.
+        location.hash = '#' + fragment;
+      }
+    }
+
+  });
+
+  // Create the default Backbone.history.
+  Backbone.history = new History;
+
+  // Helpers
+  // -------
+
+  // Helper function to correctly set up the prototype chain, for subclasses.
+  // Similar to `goog.inherits`, but uses a hash of prototype properties and
+  // class properties to be extended.
+  var extend = function(protoProps, staticProps) {
+    var parent = this;
+    var child;
+
+    // The constructor function for the new subclass is either defined by you
+    // (the "constructor" property in your `extend` definition), or defaulted
+    // by us to simply call the parent's constructor.
+    if (protoProps && _.has(protoProps, 'constructor')) {
+      child = protoProps.constructor;
+    } else {
+      child = function(){ return parent.apply(this, arguments); };
+    }
+
+    // Add static properties to the constructor function, if supplied.
+    _.extend(child, parent, staticProps);
+
+    // Set the prototype chain to inherit from `parent`, without calling
+    // `parent`'s constructor function.
+    var Surrogate = function(){ this.constructor = child; };
+    Surrogate.prototype = parent.prototype;
+    child.prototype = new Surrogate;
+
+    // Add prototype properties (instance properties) to the subclass,
+    // if supplied.
+    if (protoProps) _.extend(child.prototype, protoProps);
+
+    // Set a convenience property in case the parent's prototype is needed
+    // later.
+    child.__super__ = parent.prototype;
+
+    return child;
+  };
+
+  // Set up inheritance for the model, collection, router, view and history.
+  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
+
+  // Throw an error when a URL is needed, and none is supplied.
+  var urlError = function() {
+    throw new Error('A "url" property or function must be specified');
+  };
+
+  // Wrap an optional error callback with a fallback error event.
+  var wrapError = function (model, options) {
+    var error = options.error;
+    options.error = function(resp) {
+      if (error) error(model, resp, options);
+      model.trigger('error', model, resp, options);
+    };
+  };
+
+}).call(this);
+
+// Vectorizer.
+// -----------
+
+// A tiny library for making your live easier when dealing with SVG.
+
+// Copyright © 2012 - 2014 client IO (http://client.io)
+
+(function(root, factory) {
+
+    if (typeof define === 'function' && define.amd) {
+        // AMD. Register as an anonymous module.
+        define([], factory);
+        
+    } else {
+        // Browser globals.
+        root.Vectorizer = root.V = factory();
+    }
+
+}(this, function() {
+
+    // Well, if SVG is not supported, this library is useless.
+    var SVGsupported = !!(window.SVGAngle || document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'));
+
+    // XML namespaces.
+    var ns = {
+        xmlns: 'http://www.w3.org/2000/svg',
+        xlink: 'http://www.w3.org/1999/xlink'
+    };
+    // SVG version.
+    var SVGversion = '1.1';
+
+    // A function returning a unique identifier for this client session with every call.
+    var idCounter = 0;
+    function uniqueId() {
+        var id = ++idCounter + '';
+        return 'v-' + id;
+    }
+
+    // Create SVG element.
+    // -------------------
+
+    function createElement(el, attrs, children) {
+
+        if (!el) return undefined;
+        
+        // If `el` is an object, it is probably a native SVG element. Wrap it to VElement.
+        if (typeof el === 'object') {
+            return new VElement(el);
+        }
+        attrs = attrs || {};
+
+        // If `el` is a `'svg'` or `'SVG'` string, create a new SVG canvas.
+        if (el.toLowerCase() === 'svg') {
+            
+            attrs.xmlns = ns.xmlns;
+            attrs['xmlns:xlink'] = ns.xlink;
+            attrs.version = SVGversion;
+            
+        } else if (el[0] === '<') {
+            // Create element from an SVG string.
+            // Allows constructs of type: `document.appendChild(Vectorizer('<rect></rect>').node)`.
+            
+            var svg = '<svg xmlns="' + ns.xmlns + '" xmlns:xlink="' + ns.xlink + '" version="' + SVGversion + '">' + el + '</svg>';
+            var parser = new DOMParser();
+            parser.async = false;
+            var svgDoc = parser.parseFromString(svg, 'text/xml').documentElement;
+
+            // Note that `createElement()` might also return an array should the SVG string passed as
+            // the first argument contain more then one root element.
+            if (svgDoc.childNodes.length > 1) {
+
+                // Map child nodes to `VElement`s.
+                var ret = [];
+                for (var i = 0, len = svgDoc.childNodes.length; i < len; i++) {
+
+                    var childNode = svgDoc.childNodes[i];
+                    ret.push(new VElement(document.importNode(childNode, true)));
+                }
+                return ret;
+            }
+            
+            return new VElement(document.importNode(svgDoc.firstChild, true));
+        }
+        
+        el = document.createElementNS(ns.xmlns, el);
+
+        // Set attributes.
+        for (var key in attrs) {
+
+            setAttribute(el, key, attrs[key]);
+        }
+        
+        // Normalize `children` array.
+        if (Object.prototype.toString.call(children) != '[object Array]') children = [children];
+
+        // Append children if they are specified.
+        var i = 0, len = (children[0] && children.length) || 0, child;
+        for (; i < len; i++) {
+            child = children[i];
+            el.appendChild(child instanceof VElement ? child.node : child);
+        }
+        
+        return new VElement(el);
+    }
+
+    function setAttribute(el, name, value) {
+        
+        if (name.indexOf(':') > -1) {
+            // Attribute names can be namespaced. E.g. `image` elements
+            // have a `xlink:href` attribute to set the source of the image.
+            var combinedKey = name.split(':');
+            el.setAttributeNS(ns[combinedKey[0]], combinedKey[1], value);
+        } else if (name === 'id') {
+            el.id = value;
+        } else {
+            el.setAttribute(name, value);
+        }
+    }
+
+    function parseTransformString(transform) {
+        var translate,
+            rotate,
+            scale;
+        
+        if (transform) {
+            var translateMatch = transform.match(/translate\((.*)\)/);
+            if (translateMatch) {
+                translate = translateMatch[1].split(',');
+            }
+            var rotateMatch = transform.match(/rotate\((.*)\)/);
+            if (rotateMatch) {
+                rotate = rotateMatch[1].split(',');
+            }
+            var scaleMatch = transform.match(/scale\((.*)\)/);
+            if (scaleMatch) {
+                scale = scaleMatch[1].split(',');
+            }
+        }
+
+        var sx = (scale && scale[0]) ? parseFloat(scale[0]) : 1;
+        
+        return {
+            translate: {
+                tx: (translate && translate[0]) ? parseInt(translate[0], 10) : 0,
+                ty: (translate && translate[1]) ? parseInt(translate[1], 10) : 0
+            },
+            rotate: {
+                angle: (rotate && rotate[0]) ? parseInt(rotate[0], 10) : 0,
+                cx: (rotate && rotate[1]) ? parseInt(rotate[1], 10) : undefined,
+                cy: (rotate && rotate[2]) ? parseInt(rotate[2], 10) : undefined
+            },
+            scale: {
+                sx: sx,
+                sy: (scale && scale[1]) ? parseFloat(scale[1]) : sx
+            }
+        };
+    }
+
+
+    // Matrix decomposition.
+    // ---------------------
+
+    function deltaTransformPoint(matrix, point)  {
+        
+       var dx = point.x * matrix.a + point.y * matrix.c + 0;
+       var dy = point.x * matrix.b + point.y * matrix.d + 0;
+       return { x: dx, y: dy };
+    }
+
+    function decomposeMatrix(matrix) {
+
+        // @see https://gist.github.com/2052247
+        
+        // calculate delta transform point
+       var px = deltaTransformPoint(matrix, { x: 0, y: 1 });
+       var py = deltaTransformPoint(matrix, { x: 1, y: 0 });
+        
+       // calculate skew
+       var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90);
+       var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x));
+        
+       return {
+            
+           translateX: matrix.e,
+           translateY: matrix.f,
+           scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b),
+           scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d),
+           skewX: skewX,
+           skewY: skewY,
+           rotation: skewX // rotation is the same as skew x
+       };
+    }
+    
+    // VElement.
+    // ---------
+
+    function VElement(el) {
+        this.node = el;
+        if (!this.node.id) {
+            this.node.id = uniqueId();
+        }
+    }
+
+    // VElement public API.
+    // --------------------
+
+    VElement.prototype = {
+        
+        translate: function(tx, ty) {
+            ty = ty || 0;
+            
+            var transformAttr = this.attr('transform') || '',
+                transform = parseTransformString(transformAttr);
+
+            // Is it a getter?
+            if (typeof tx === 'undefined') {
+                return transform.translate;
+            }
+            
+            transformAttr = transformAttr.replace(/translate\([^\)]*\)/g, '').trim();
+
+            var newTx = transform.translate.tx + tx,
+                newTy = transform.translate.ty + ty,
+                newTranslate = 'translate(' + newTx + ',' + newTy + ')';
+
+            // Note that `translate()` is always the first transformation. This is
+            // usually the desired case.
+            this.attr('transform', (newTranslate + ' ' + transformAttr).trim()); 
+            return this;
+        },
+
+        rotate: function(angle, cx, cy) {
+            var transformAttr = this.attr('transform') || '',
+                transform = parseTransformString(transformAttr);
+
+            // Is it a getter?
+            if (typeof angle === 'undefined') {
+                return transform.rotate;
+            }
+            
+            transformAttr = transformAttr.replace(/rotate\([^\)]*\)/g, '').trim();
+
+            var newAngle = transform.rotate.angle + angle % 360,
+                newOrigin = (cx !== undefined && cy !== undefined) ? ',' + cx + ',' + cy : '';
+            
+            this.attr('transform', transformAttr + ' rotate(' + newAngle + newOrigin + ')');
+            return this;
+        },
+
+        // Note that `scale` as the only transformation does not combine with previous values.
+        scale: function(sx, sy) {
+            sy = (typeof sy === 'undefined') ? sx : sy;
+            
+            var transformAttr = this.attr('transform') || '',
+                transform = parseTransformString(transformAttr);
+
+            // Is it a getter?
+            if (typeof sx === 'undefined') {
+                return transform.scale;
+            }
+            
+            transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim();
+
+            this.attr('transform', transformAttr + ' scale(' + sx + ',' + sy + ')');
+            return this;
+        },
+
+        // Get SVGRect that contains coordinates and dimension of the real bounding box,
+        // i.e. after transformations are applied.
+        // If `target` is specified, bounding box will be computed relatively to `target` element.
+        bbox: function(withoutTransformations, target) {
+
+            // If the element is not in the live DOM, it does not have a bounding box defined and
+            // so fall back to 'zero' dimension element.
+            if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 };
+            
+            var box;
+            try {
+
+                box = this.node.getBBox();
+
+               // Opera returns infinite values in some cases.
+               // Note that Infinity | 0 produces 0 as opposed to Infinity || 0.
+               // We also have to create new object as the standard says that you can't
+               // modify the attributes of a bbox.
+               box = { x: box.x | 0, y: box.y | 0, width: box.width | 0, height: box.height | 0};
+
+            } catch (e) {
+
+                // Fallback for IE.
+                box = {
+                    x: this.node.clientLeft,
+                    y: this.node.clientTop,
+                    width: this.node.clientWidth,
+                    height: this.node.clientHeight
+                };
+            }
+
+            if (withoutTransformations) {
+
+                return box;
+            }
+
+            var matrix = this.node.getTransformToElement(target || this.node.ownerSVGElement);
+            var corners = [];
+            var point = this.node.ownerSVGElement.createSVGPoint();
+
+
+            point.x = box.x;
+            point.y = box.y;
+            corners.push(point.matrixTransform(matrix));
+            
+            point.x = box.x + box.width;
+            point.y = box.y;
+            corners.push(point.matrixTransform(matrix));
+            
+            point.x = box.x + box.width;
+            point.y = box.y + box.height;
+            corners.push(point.matrixTransform(matrix));
+            
+            point.x = box.x;
+            point.y = box.y + box.height;
+            corners.push(point.matrixTransform(matrix));
+
+            var minX = corners[0].x;
+            var maxX = minX;
+            var minY = corners[0].y;
+            var maxY = minY;
+            
+            for (var i = 1, len = corners.length; i < len; i++) {
+                
+                var x = corners[i].x;
+                var y = corners[i].y;
+
+                if (x < minX) {
+                    minX = x;
+                } else if (x > maxX) {
+                    maxX = x;
+                }
+                
+                if (y < minY) {
+                    minY = y;
+                } else if (y > maxY) {
+                    maxY = y;
+                }
+            }
+
+            return {
+                x: minX,
+                y: minY,
+                width: maxX - minX,
+                height: maxY - minY
+            };
+        },
+
+        text: function(content) {
+            var lines = content.split('\n'), i = 0,
+                tspan;
+
+            // `alignment-baseline` does not work in Firefox.
+           // Setting `dominant-baseline` on the `<text>` element doesn't work in IE9.
+            // In order to have the 0,0 coordinate of the `<text>` element (or the first `<tspan>`)
+           // in the top left corner we translate the `<text>` element by `0.8em`.
+           // See `http://www.w3.org/Graphics/SVG/WG/wiki/How_to_determine_dominant_baseline`.
+           // See also `http://apike.ca/prog_svg_text_style.html`.
+           this.attr('y', '0.8em');
+
+            // An empty text gets rendered into the DOM in webkit-based browsers.
+            // In order to unify this behaviour across all browsers
+            // we rather hide the text element when it's empty.
+            this.attr('display', content ? null : 'none');
+            
+            if (lines.length === 1) {
+                this.node.textContent = content;
+                return this;
+            }
+            // Easy way to erase all `<tspan>` children;
+            this.node.textContent = '';
+            
+            for (; i < lines.length; i++) {
+
+                // Shift all the <tspan> but first by one line (`1em`)
+                tspan = V('tspan', { dy: (i == 0 ? '0em' : '1em'), x: this.attr('x') || 0});
+                tspan.node.textContent = lines[i];
+                
+                this.append(tspan);
+            }
+            return this;
+        },
+        
+        attr: function(name, value) {
+            
+            if (typeof name === 'string' && typeof value === 'undefined') {
+                return this.node.getAttribute(name);
+            }
+            
+            if (typeof name === 'object') {
+
+                for (var attrName in name) {
+                    if (name.hasOwnProperty(attrName)) {
+                        setAttribute(this.node, attrName, name[attrName]);
+                    }
+                }
+                
+            } else {
+
+                setAttribute(this.node, name, value);
+            }
+
+            return this;
+        },
+
+        remove: function() {
+            if (this.node.parentNode) {
+                this.node.parentNode.removeChild(this.node);
+            }
+        },
+
+        append: function(el) {
+
+            var els = el;
+            
+            if (Object.prototype.toString.call(el) !== '[object Array]') {
+                
+                els = [el];
+            }
+
+            for (var i = 0, len = els.length; i < len; i++) {
+                el = els[i];
+                this.node.appendChild(el instanceof VElement ? el.node : el);
+            }
+            
+            return this;
+        },
+
+        prepend: function(el) {
+            this.node.insertBefore(el instanceof VElement ? el.node : el, this.node.firstChild);
+        },
+
+        svg: function() {
+
+            return this.node instanceof window.SVGSVGElement ? this : V(this.node.ownerSVGElement);
+        },
+
+        defs: function() {
+
+            var defs = this.svg().node.getElementsByTagName('defs');
+            
+            return (defs && defs.length) ? V(defs[0]) : undefined;
+        },
+
+        clone: function() {
+            var clone = V(this.node.cloneNode(true));
+            // Note that clone inherits also ID. Therefore, we need to change it here.
+            clone.node.id = uniqueId();
+            return clone;
+        },
+
+        findOne: function(selector) {
+
+            var found = this.node.querySelector(selector);
+            return found ? V(found) : undefined;
+        },
+
+        find: function(selector) {
+
+            var nodes = this.node.querySelectorAll(selector);
+
+            // Map DOM elements to `VElement`s.
+            for (var i = 0, len = nodes.length; i < len; i++) {
+                nodes[i] = V(nodes[i]);
+            }
+            return nodes;
+        },
+        
+        // Convert global point into the coordinate space of this element.
+        toLocalPoint: function(x, y) {
+
+            var svg = this.svg().node;
+            
+            var p = svg.createSVGPoint();
+            p.x = x;
+            p.y = y;
+
+           try {
+
+               var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse());
+               var globalToLocalMatrix = this.node.getTransformToElement(svg).inverse();
+
+           } catch(e) {
+               // IE9 throws an exception in odd cases. (`Unexpected call to method or property access`)
+               // We have to make do with the original coordianates.
+               return p;
+           }
+
+            return globalPoint.matrixTransform(globalToLocalMatrix);
+        },
+
+        translateCenterToPoint: function(p) {
+
+            var bbox = this.bbox();
+            var center = g.rect(bbox).center();
+
+            this.translate(p.x - center.x, p.y - center.y);
+        },
+
+        // Efficiently auto-orient an element. This basically implements the orient=auto attribute
+        // of markers. The easiest way of understanding on what this does is to imagine the element is an
+        // arrowhead. Calling this method on the arrowhead makes it point to the `position` point while
+        // being auto-oriented (properly rotated) towards the `reference` point.
+        // `target` is the element relative to which the transformations are applied. Usually a viewport.
+        translateAndAutoOrient: function(position, reference, target) {
+
+            // Clean-up previously set transformations except the scale. If we didn't clean up the
+            // previous transformations then they'd add up with the old ones. Scale is an exception as
+            // it doesn't add up, consider: `this.scale(2).scale(2).scale(2)`. The result is that the
+            // element is scaled by the factor 2, not 8.
+
+            var s = this.scale();
+            this.attr('transform', '');
+            this.scale(s.sx, s.sy);
+
+            var svg = this.svg().node;
+            var bbox = this.bbox(false, target);
+
+            // 1. Translate to origin.
+            var translateToOrigin = svg.createSVGTransform();
+            translateToOrigin.setTranslate(-bbox.x - bbox.width/2, -bbox.y - bbox.height/2);
+
+            // 2. Rotate around origin.
+            var rotateAroundOrigin = svg.createSVGTransform();
+            var angle = g.point(position).changeInAngle(position.x - reference.x, position.y - reference.y, reference);
+            rotateAroundOrigin.setRotate(angle, 0, 0);
+
+            // 3. Translate to the `position` + the offset (half my width) towards the `reference` point.
+            var translateFinal = svg.createSVGTransform();
+            var finalPosition = g.point(position).move(reference, bbox.width/2);
+            translateFinal.setTranslate(position.x + (position.x - finalPosition.x), position.y + (position.y - finalPosition.y));
+
+            // 4. Apply transformations.
+            var ctm = this.node.getTransformToElement(target);
+            var transform = svg.createSVGTransform();
+            transform.setMatrix(
+                translateFinal.matrix.multiply(
+                    rotateAroundOrigin.matrix.multiply(
+                        translateToOrigin.matrix.multiply(
+                            ctm)))
+            );
+
+            // Instead of directly setting the `matrix()` transform on the element, first, decompose
+            // the matrix into separate transforms. This allows us to use normal Vectorizer methods
+            // as they don't work on matrices. An example of this is to retrieve a scale of an element.
+            // this.node.transform.baseVal.initialize(transform);
+
+            var decomposition = decomposeMatrix(transform.matrix);
+
+            this.translate(decomposition.translateX, decomposition.translateY);
+            this.rotate(decomposition.rotation);
+            // Note that scale has been already applied, hence the following line stays commented. (it's here just for reference).
+            //this.scale(decomposition.scaleX, decomposition.scaleY);
+
+            return this;
+        },
+
+        animateAlongPath: function(attrs, path) {
+
+            var animateMotion = V('animateMotion', attrs);
+            var mpath = V('mpath', { 'xlink:href': '#' + V(path).node.id });
+
+            animateMotion.append(mpath);
+
+            this.append(animateMotion);
+            try {
+                animateMotion.node.beginElement();
+            } catch (e) {
+                // Fallback for IE 9.
+               // Run the animation programatically if FakeSmile (`http://leunen.me/fakesmile/`) present 
+               if (document.documentElement.getAttribute('smiling') === 'fake') {
+
+                   // Register the animation. (See `https://answers.launchpad.net/smil/+question/203333`)
+                   var animation = animateMotion.node;
+                   animation.animators = [];
+
+                   var animationID = animation.getAttribute('id');
+                   if (animationID) id2anim[animationID] = animation;
+
+                    var targets = getTargets(animation);
+                    for (var i = 0, len = targets.length; i < len; i++) {
+                        var target = targets[i];
+                       var animator = new Animator(animation, target, i);
+                       animators.push(animator);
+                       animation.animators[i] = animator;
+                        animator.register();
+                    }
+               }
+            }
+        },
+
+        hasClass: function(className) {
+
+            return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.node.getAttribute('class'));
+        },
+
+        addClass: function(className) {
+
+            if (!this.hasClass(className)) {
+                this.node.setAttribute('class', this.node.getAttribute('class') + ' ' + className);
+            }
+
+            return this;
+        },
+
+        removeClass: function(className) {
+
+            var removedClass = this.node.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
+
+            if (this.hasClass(className)) {
+                this.node.setAttribute('class', removedClass);
+            }
+
+            return this;
+        },
+
+        toggleClass: function(className, toAdd) {
+
+            var toRemove = typeof toAdd === 'undefined' ? this.hasClass(className) : !toAdd;
+
+            if (toRemove) {
+                this.removeClass(className);
+            } else {
+                this.addClass(className);
+            }
+
+            return this;
+        }
+    };
+
+    // Convert a rectangle to SVG path commands. `r` is an object of the form:
+    // `{ x: [number], y: [number], width: [number], height: [number], top-ry: [number], top-ry: [number], bottom-rx: [number], bottom-ry: [number] }`,
+    // where `x, y, width, height` are the usual rectangle attributes and [top-/bottom-]rx/ry allows for
+    // specifying radius of the rectangle for all its sides (as opposed to the built-in SVG rectangle
+    // that has only `rx` and `ry` attributes).
+    function rectToPath(r) {
+
+        var topRx = r.rx || r['top-rx'] || 0;
+        var bottomRx = r.rx || r['bottom-rx'] || 0;
+        var topRy = r.ry || r['top-ry'] || 0;
+        var bottomRy = r.ry || r['bottom-ry'] || 0;
+
+        return [
+            'M', r.x, r.y + topRy,
+            'v', r.height - topRy - bottomRy,
+            'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, bottomRy,
+            'h', r.width - 2 * bottomRx,
+            'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, -bottomRy,
+            'v', -(r.height - bottomRy - topRy),
+            'a', topRx, topRy, 0, 0, 0, -topRx, -topRy,
+            'h', -(r.width - 2 * topRx),
+            'a', topRx, topRy, 0, 0, 0, -topRx, topRy
+        ].join(' ');
+    }
+
+    var V = createElement;
+
+    V.decomposeMatrix = decomposeMatrix;
+    V.rectToPath = rectToPath;
+
+    var svgDocument = V('svg').node;
+    
+    V.createSVGMatrix = function(m) {
+
+        var svgMatrix = svgDocument.createSVGMatrix();
+        for (var component in m) {
+            svgMatrix[component] = m[component];
+        }
+        
+        return svgMatrix;
+    };
+
+    V.createSVGTransform = function() {
+
+        return svgDocument.createSVGTransform();
+    };
+
+    V.createSVGPoint = function(x, y) {
+
+        var p = svgDocument.createSVGPoint();
+        p.x = x;
+        p.y = y;
+        return p;
+    };
+
+    return V;
+
+}));
+
+
+//      Geometry library.
+//      (c) 2011-2013 client IO
+
+
+(function(root, factory) {
+
+    if (typeof define === 'function' && define.amd) {
+        // AMD. Register as an anonymous module.
+        define([], factory);
+        
+    } else if (typeof exports === 'object') {
+        // Node. Does not work with strict CommonJS, but
+        // only CommonJS-like environments that support module.exports,
+        // like Node.
+        module.exports = factory();
+        
+    } else {
+        // Browser globals.
+        root.g = factory();
+    }
+
+}(this, function() {
+
+
+    // Declare shorthands to the most used math functions.
+    var math = Math;
+    var abs = math.abs;
+    var cos = math.cos;
+    var sin = math.sin;
+    var sqrt = math.sqrt;
+    var mmin = math.min;
+    var mmax = math.max;
+    var atan = math.atan;
+    var atan2 = math.atan2;
+    var acos = math.acos;
+    var round = math.round;
+    var floor = math.floor;
+    var PI = math.PI;
+    var random = math.random;
+    var toDeg = function(rad) { return (180*rad / PI) % 360; };
+    var toRad = function(deg) { return (deg % 360) * PI / 180; };
+    var snapToGrid = function(val, gridSize) { return gridSize * Math.round(val/gridSize); };
+    var normalizeAngle = function(angle) { return (angle % 360) + (angle < 0 ? 360 : 0); };
+
+    // Point
+    // -----
+
+    // Point is the most basic object consisting of x/y coordinate,.
+
+    // Possible instantiations are:
+
+    // * `point(10, 20)`
+    // * `new point(10, 20)`
+    // * `point('10 20')`
+    // * `point(point(10, 20))`
+    function point(x, y) {
+        if (!(this instanceof point))
+            return new point(x, y);
+        var xy;
+        if (y === undefined && Object(x) !== x) {
+            xy = x.split(x.indexOf('@') === -1 ? ' ' : '@');
+            this.x = parseInt(xy[0], 10);
+            this.y = parseInt(xy[1], 10);
+        } else if (Object(x) === x) {
+            this.x = x.x;
+            this.y = x.y;
+        } else {
+            this.x = x;
+            this.y = y;
+        }
+    }
+
+    point.prototype = {
+        toString: function() {
+            return this.x + "@" + this.y;
+        },
+        // If point lies outside rectangle `r`, return the nearest point on the boundary of rect `r`,
+        // otherwise return point itself.
+        // (see Squeak Smalltalk, Point>>adhereTo:)
+        adhereToRect: function(r) {
+           if (r.containsPoint(this)){
+               return this;
+           }
+           this.x = mmin(mmax(this.x, r.x), r.x + r.width);
+           this.y = mmin(mmax(this.y, r.y), r.y + r.height);
+           return this;
+        },
+        // Compute the angle between me and `p` and the x axis.
+        // (cartesian-to-polar coordinates conversion)
+        // Return theta angle in degrees.
+        theta: function(p) {
+            p = point(p);
+            // Invert the y-axis.
+           var y = -(p.y - this.y);
+           var x = p.x - this.x;
+            // Makes sure that the comparison with zero takes rounding errors into account.
+            var PRECISION = 10;
+            // Note that `atan2` is not defined for `x`, `y` both equal zero.
+           var rad = (y.toFixed(PRECISION) == 0 && x.toFixed(PRECISION) == 0) ? 0 : atan2(y, x); 
+
+            // Correction for III. and IV. quadrant.
+           if (rad < 0) { 
+               rad = 2*PI + rad;
+           }
+           return 180*rad / PI;
+        },
+        // Returns distance between me and point `p`.
+        distance: function(p) {
+           return line(this, p).length();
+        },
+        // Returns a manhattan (taxi-cab) distance between me and point `p`.
+        manhattanDistance: function(p) {
+            return abs(p.x - this.x) + abs(p.y - this.y);
+        },
+        // Offset me by the specified amount.
+        offset: function(dx, dy) {
+           this.x += dx || 0;
+           this.y += dy || 0;
+           return this;
+        },
+        magnitude: function() {
+            return sqrt((this.x*this.x) + (this.y*this.y)) || 0.01;
+        },
+        update: function(x, y) {
+            this.x = x || 0;
+            this.y = y || 0;
+            return this;
+        },
+        round: function(decimals) {
+            this.x = decimals ? this.x.toFixed(decimals) : round(this.x);
+            this.y = decimals ? this.y.toFixed(decimals) : round(this.y);
+            return this;
+        },
+        // Scale the line segment between (0,0) and me to have a length of len.
+        normalize: function(len) {
+           var s = (len || 1) / this.magnitude();
+           this.x = s * this.x;
+           this.y = s * this.y;
+           return this;
+        },
+        difference: function(p) {
+            return point(this.x - p.x, this.y - p.y);
+        },
+        // Return the bearing between me and point `p`.
+        bearing: function(p) {
+            return line(this, p).bearing();
+        },        
+        // Converts rectangular to polar coordinates.
+        // An origin can be specified, otherwise it's 0@0.
+        toPolar: function(o) {
+            o = (o && point(o)) || point(0,0);
+            var x = this.x;
+            var y = this.y;
+            this.x = sqrt((x-o.x)*(x-o.x) + (y-o.y)*(y-o.y));   // r
+            this.y = toRad(o.theta(point(x,y)));
+            return this;
+        },
+        // Rotate point by angle around origin o.
+        rotate: function(o, angle) {
+            angle = (angle + 360) % 360;
+            this.toPolar(o);
+            this.y += toRad(angle);
+            var p = point.fromPolar(this.x, this.y, o);
+            this.x = p.x;
+            this.y = p.y;
+            return this;
+        },
+        // Move point on line starting from ref ending at me by
+        // distance distance.
+        move: function(ref, distance) {
+            var theta = toRad(point(ref).theta(this));
+            return this.offset(cos(theta) * distance, -sin(theta) * distance);
+        },
+        // Returns change in angle from my previous position (-dx, -dy) to my new position
+        // relative to ref point.
+        changeInAngle: function(dx, dy, ref) {
+            // Revert the translation and measure the change in angle around x-axis.
+            return point(this).offset(-dx, -dy).theta(ref) - this.theta(ref);
+        },
+        equals: function(p) {
+            return this.x === p.x && this.y === p.y;
+        },
+        snapToGrid: function(gx, gy) {
+            this.x = snapToGrid(this.x, gx)
+            this.y = snapToGrid(this.y, gy || gx)
+            return this;
+        }
+    };
+    // Alternative constructor, from polar coordinates.
+    // @param {number} r Distance.
+    // @param {number} angle Angle in radians.
+    // @param {point} [optional] o Origin.
+    point.fromPolar = function(r, angle, o) {
+        o = (o && point(o)) || point(0,0);
+        var x = abs(r * cos(angle));
+        var y = abs(r * sin(angle));
+        var deg = normalizeAngle(toDeg(angle));
+
+        if (deg < 90) y = -y;
+        else if (deg < 180) { x = -x; y = -y; }
+        else if (deg < 270) x = -x;
+        
+        return point(o.x + x, o.y + y);
+    };
+
+    // Create a point with random coordinates that fall into the range `[x1, x2]` and `[y1, y2]`.
+    point.random = function(x1, x2, y1, y2) {
+        return point(floor(random() * (x2 - x1 + 1) + x1), floor(random() * (y2 - y1 + 1) + y1));
+    };
+
+    // Line.
+    // -----
+    function line(p1, p2) {
+        if (!(this instanceof line))
+            return new line(p1, p2);
+        this.start = point(p1);
+        this.end = point(p2);
+    }
+    
+    line.prototype = {
+        toString: function() {
+           return this.start.toString() + ' ' + this.end.toString();
+        },
+        // @return {double} length of the line
+        length: function() {
+            return sqrt(this.squaredLength());
+        },
+        // @return {integer} length without sqrt
+        // @note for applications where the exact length is not necessary (e.g. compare only)
+        squaredLength: function() {
+           var x0 = this.start.x;
+            var y0 = this.start.y;
+           var x1 = this.end.x;
+            var y1 = this.end.y;
+           return (x0 -= x1)*x0 + (y0 -= y1)*y0;
+        },
+        // @return {point} my midpoint
+        midpoint: function() {
+           return point((this.start.x + this.end.x) / 2,
+                        (this.start.y + this.end.y) / 2);
+        },
+        // @return {point} Point where I'm intersecting l.
+        // @see Squeak Smalltalk, LineSegment>>intersectionWith:
+        intersection: function(l) {
+           var pt1Dir = point(this.end.x - this.start.x, this.end.y - this.start.y);
+           var pt2Dir = point(l.end.x - l.start.x, l.end.y - l.start.y);
+           var det = (pt1Dir.x * pt2Dir.y) - (pt1Dir.y * pt2Dir.x);
+           var deltaPt = point(l.start.x - this.start.x, l.start.y - this.start.y);
+           var alpha = (deltaPt.x * pt2Dir.y) - (deltaPt.y * pt2Dir.x);
+           var beta = (deltaPt.x * pt1Dir.y) - (deltaPt.y * pt1Dir.x);
+
+           if (det === 0 ||
+               alpha * det < 0 ||
+               beta * det < 0) {
+                // No intersection found.
+               return null;    
+           }
+           if (det > 0){
+               if (alpha > det || beta > det){
+                   return null;
+               }
+           } else {
+               if (alpha < det || beta < det){
+                   return null;
+               }
+           }
+           return point(this.start.x + (alpha * pt1Dir.x / det),
+                        this.start.y + (alpha * pt1Dir.y / det));
+        },
+        
+        // @return the bearing (cardinal direction) of the line. For example N, W, or SE.
+        // @returns {String} One of the following bearings : NE, E, SE, S, SW, W, NW, N.
+        bearing: function() {
+            
+            var lat1 = toRad(this.start.y);
+            var lat2 = toRad(this.end.y);
+            var lon1 = this.start.x;
+            var lon2 = this.end.x;
+            var dLon = toRad(lon2 - lon1);
+            var y = sin(dLon) * cos(lat2);
+            var x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
+            var brng = toDeg(atan2(y, x));
+
+            var bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'];
+
+            var index = brng - 22.5;
+            if (index < 0)
+                index += 360;
+            index = parseInt(index / 45);
+
+            return bearings[index];
+        }
+    };
+
+    // Rectangle.
+    // ----------
+    function rect(x, y, w, h) {
+        if (!(this instanceof rect))
+            return new rect(x, y, w, h);
+        if (y === undefined) {
+            y = x.y;
+            w = x.width;
+            h = x.height;
+            x = x.x;        
+        }
+        this.x = x;
+        this.y = y;
+        this.width = w;
+        this.height = h;
+    }
+    
+    rect.prototype = {
+        toString: function() {
+           return this.origin().toString() + ' ' + this.corner().toString();
+        },
+        origin: function() {
+            return point(this.x, this.y);
+        },
+        corner: function() {
+            return point(this.x + this.width, this.y + this.height);
+        },
+        topRight: function() {
+            return point(this.x + this.width, this.y);
+        },
+        bottomLeft: function() {
+            return point(this.x, this.y + this.height);
+        },
+        center: function() {
+            return point(this.x + this.width/2, this.y + this.height/2);
+        },
+        // @return {boolean} true if rectangles intersect
+        intersect: function(r) {
+           var myOrigin = this.origin();
+           var myCorner = this.corner();
+           var rOrigin = r.origin();
+           var rCorner = r.corner();
+            
+           if (rCorner.x <= myOrigin.x ||
+               rCorner.y <= myOrigin.y ||
+               rOrigin.x >= myCorner.x ||
+               rOrigin.y >= myCorner.y) return false;
+           return true;
+        },
+        // @return {string} (left|right|top|bottom) side which is nearest to point
+        // @see Squeak Smalltalk, Rectangle>>sideNearestTo:
+        sideNearestToPoint: function(p) {
+            p = point(p);
+           var distToLeft = p.x - this.x;
+           var distToRight = (this.x + this.width) - p.x;
+           var distToTop = p.y - this.y;
+           var distToBottom = (this.y + this.height) - p.y;
+           var closest = distToLeft;
+           var side = 'left';
+            
+           if (distToRight < closest) {
+               closest = distToRight;
+               side = 'right';
+           }
+           if (distToTop < closest) {
+               closest = distToTop;
+               side = 'top';
+           }
+           if (distToBottom < closest) {
+               closest = distToBottom;
+               side = 'bottom';
+           }
+           return side;
+        },
+        // @return {bool} true if point p is insight me
+        containsPoint: function(p) {
+            p = point(p);
+           if (p.x >= this.x && p.x <= this.x + this.width &&
+               p.y >= this.y && p.y <= this.y + this.height) {
+               return true;
+           }
+           return false;
+        },
+        // Algorithm ported from java.awt.Rectangle from OpenJDK.
+        // @return {bool} true if rectangle `r` is inside me.
+        containsRect: function(r) {
+            var nr = rect(r).normalize();
+            var W = nr.width;
+            var H = nr.height;
+            var X = nr.x;
+            var Y = nr.y;
+            var w = this.width;
+            var h = this.height;
+            if ((w | h | W | H) < 0) {
+                // At least one of the dimensions is negative...
+                return false;
+            }
+            // Note: if any dimension is zero, tests below must return false...
+            var x = this.x;
+            var y = this.y;
+            if (X < x || Y < y) {
+                return false;
+            }
+            w += x;
+            W += X;
+            if (W <= X) {
+                // X+W overflowed or W was zero, return false if...
+                // either original w or W was zero or
+                // x+w did not overflow or
+                // the overflowed x+w is smaller than the overflowed X+W
+                if (w >= x || W > w) return false;
+            } else {
+                // X+W did not overflow and W was not zero, return false if...
+                // original w was zero or
+                // x+w did not overflow and x+w is smaller than X+W
+                if (w >= x && W > w) return false;
+            }
+            h += y;
+            H += Y;
+            if (H <= Y) {
+                if (h >= y || H > h) return false;
+            } else {
+                if (h >= y && H > h) return false;
+            }
+            return true;
+        },        
+        // @return {point} a point on my boundary nearest to p
+        // @see Squeak Smalltalk, Rectangle>>pointNearestTo:
+        pointNearestToPoint: function(p) {
+            p = point(p);
+           if (this.containsPoint(p)) {
+               var side = this.sideNearestToPoint(p);
+               switch (side){
+                 case "right": return point(this.x + this.width, p.y);
+                 case "left": return point(this.x, p.y);
+                 case "bottom": return point(p.x, this.y + this.height);
+                 case "top": return point(p.x, this.y);
+               }
+           }
+           return p.adhereToRect(this);
+        },
+        // Find point on my boundary where line starting
+        // from my center ending in point p intersects me.
+        // @param {number} angle If angle is specified, intersection with rotated rectangle is computed.
+        intersectionWithLineFromCenterToPoint: function(p, angle) {
+            p = point(p);
+           var center = point(this.x + this.width/2, this.y + this.height/2);
+            var result;
+            if (angle) p.rotate(center, angle);
+            
+           // (clockwise, starting from the top side)
+           var sides = [
+               line(this.origin(), this.topRight()),
+               line(this.topRight(), this.corner()),
+               line(this.corner(), this.bottomLeft()),
+               line(this.bottomLeft(), this.origin())
+           ];
+           var connector = line(center, p);
+            
+           for (var i = sides.length - 1; i >= 0; --i){
+               var intersection = sides[i].intersection(connector);
+               if (intersection !== null){
+                   result = intersection;
+                    break;
+               }
+           }
+            if (result && angle) result.rotate(center, -angle);
+            return result;
+        },
+        // Move and expand me.
+        // @param r {rectangle} representing deltas
+        moveAndExpand: function(r) {
+           this.x += r.x;
+           this.y += r.y;
+           this.width += r.width;
+           this.height += r.height;
+           return this;
+        },
+        round: function(decimals) {
+            this.x = decimals ? this.x.toFixed(decimals) : round(this.x);
+            this.y = decimals ? this.y.toFixed(decimals) : round(this.y);
+            this.width = decimals ? this.width.toFixed(decimals) : round(this.width);
+            this.height = decimals ? this.height.toFixed(decimals) : round(this.height);
+            return this;
+        },
+        // Normalize the rectangle; i.e., make it so that it has a non-negative width and height.
+        // If width < 0 the function swaps the left and right corners,
+        // and it swaps the top and bottom corners if height < 0
+        // like in http://qt-project.org/doc/qt-4.8/qrectf.html#normalized
+        normalize: function() {
+            var newx = this.x;
+            var newy = this.y;
+            var newwidth = this.width;
+            var newheight = this.height;
+            if (this.width < 0) {
+                newx = this.x + this.width;
+                newwidth = -this.width;
+            }
+            if (this.height < 0) {
+                newy = this.y + this.height;
+                newheight = -this.height;
+            }
+            this.x = newx;
+            this.y = newy;
+            this.width = newwidth;
+            this.height = newheight;
+            return this;
+        }        
+    };
+
+    // Ellipse.
+    // --------
+    function ellipse(c, a, b) {
+        if (!(this instanceof ellipse))
+            return new ellipse(c, a, b);
+        c = point(c);
+        this.x = c.x;
+        this.y = c.y;
+        this.a = a;
+        this.b = b;
+    }
+
+    ellipse.prototype = {
+        toString: function() {
+            return point(this.x, this.y).toString() + ' ' + this.a + ' ' + this.b;
+        },
+        bbox: function() {
+               return rect(this.x - this.a, this.y - this.b, 2*this.a, 2*this.b);
+        },
+        // Find point on me where line from my center to
+        // point p intersects my boundary.
+        // @param {number} angle If angle is specified, intersection with rotated ellipse is computed.
+        intersectionWithLineFromCenterToPoint: function(p, angle) {
+           p = point(p);
+            if (angle) p.rotate(point(this.x, this.y), angle);
+            var dx = p.x - this.x;
+           var dy = p.y - this.y;
+            var result;
+           if (dx === 0) {
+               result = this.bbox().pointNearestToPoint(p);
+                if (angle) return result.rotate(point(this.x, this.y), -angle);
+                return result;
+           }
+           var m = dy / dx;
+           var mSquared = m * m;
+           var aSquared = this.a * this.a;
+           var bSquared = this.b * this.b;
+           var x = sqrt(1 / ((1 / aSquared) + (mSquared / bSquared)));
+
+            x = dx < 0 ? -x : x;
+           var y = m * x;
+           result = point(this.x + x, this.y + y);
+            if (angle) return result.rotate(point(this.x, this.y), -angle);
+            return result;
+        }
+    };
+
+    // Bezier curve.
+    // -------------
+    var bezier = {
+        // Cubic Bezier curve path through points.
+        // Ported from C# implementation by Oleg V. Polikarpotchkin and Peter Lee (http://www.codeproject.com/KB/graphics/BezierSpline.aspx).
+        // @param {array} points Array of points through which the smooth line will go.
+        // @return {array} SVG Path commands as an array
+        curveThroughPoints: function(points) {
+            var controlPoints = this.getCurveControlPoints(points);
+            var path = ['M', points[0].x, points[0].y];
+
+            for (var i = 0; i < controlPoints[0].length; i++) {
+                path.push('C', controlPoints[0][i].x, controlPoints[0][i].y, controlPoints[1][i].x, controlPoints[1][i].y, points[i+1].x, points[i+1].y);        
+            }
+            return path;
+        },
+        
+        // Get open-ended Bezier Spline Control Points.
+        // @param knots Input Knot Bezier spline points (At least two points!).
+        // @param firstControlPoints Output First Control points. Array of knots.length - 1 length.
+        //  @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
+        getCurveControlPoints: function(knots) {
+            var firstControlPoints = [];
+            var secondControlPoints = [];
+            var n = knots.length - 1;
+            var i;
+
+            // Special case: Bezier curve should be a straight line.
+            if (n == 1) { 
+               // 3P1 = 2P0 + P3
+               firstControlPoints[0] = point((2 * knots[0].x + knots[1].x) / 3,
+                                             (2 * knots[0].y + knots[1].y) / 3);
+               // P2 = 2P1 – P0
+               secondControlPoints[0] = point(2 * firstControlPoints[0].x - knots[0].x,
+                                              2 * firstControlPoints[0].y - knots[0].y);
+               return [firstControlPoints, secondControlPoints];
+            }
+            
+                // Calculate first Bezier control points.
+            // Right hand side vector.
+            var rhs = [];
+            
+            // Set right hand side X values.
+            for (i = 1; i < n - 1; i++) {
+                rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
+            }
+            rhs[0] = knots[0].x + 2 * knots[1].x;
+            rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;
+            // Get first control points X-values.
+            var x = this.getFirstControlPoints(rhs);
+            
+            // Set right hand side Y values.
+            for (i = 1; i < n - 1; ++i) {
+               rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
+            }
+            rhs[0] = knots[0].y + 2 * knots[1].y;
+            rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;
+            // Get first control points Y-values.
+            var y = this.getFirstControlPoints(rhs);
+            
+            // Fill output arrays.
+            for (i = 0; i < n; i++) {
+               // First control point.
+               firstControlPoints.push(point(x[i], y[i]));
+               // Second control point.
+               if (i < n - 1) {
+                   secondControlPoints.push(point(2 * knots [i + 1].x - x[i + 1],
+                                                   2 * knots[i + 1].y - y[i + 1]));
+               } else {
+                   secondControlPoints.push(point((knots[n].x + x[n - 1]) / 2,
+                                                  (knots[n].y + y[n - 1]) / 2));
+               }
+            }
+            return [firstControlPoints, secondControlPoints];
+        },
+
+        // Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points.
+        // @param rhs Right hand side vector.
+        // @return Solution vector.
+        getFirstControlPoints: function(rhs) {
+            var n = rhs.length;
+            // `x` is a solution vector.
+            var x = [];
+            var tmp = [];
+            var b = 2.0;
+            
+            x[0] = rhs[0] / b;
+            // Decomposition and forward substitution.
+            for (var i = 1; i < n; i++) { 
+               tmp[i] = 1 / b;
+               b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
+               x[i] = (rhs[i] - x[i - 1]) / b;
+            }
+            for (i = 1; i < n; i++) {
+                // Backsubstitution.
+               x[n - i - 1] -= tmp[n - i] * x[n - i]; 
+            }
+            return x;
+        }
+    };
+
+    // Scale.
+    var scale = {
+
+        // Return the `value` from the `domain` interval scaled to the `range` interval.
+        linear: function(domain, range, value) {
+
+            var domainSpan = domain[1] - domain[0];
+            var rangeSpan = range[1] - range[0];
+            return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0;
+        }
+    };
+
+    return {
+
+        toDeg: toDeg,
+        toRad: toRad,
+        snapToGrid: snapToGrid,
+       normalizeAngle: normalizeAngle,
+        point: point,
+        line: line,
+        rect: rect,
+        ellipse: ellipse,
+        bezier: bezier,
+        scale: scale
+    }
+}));
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+if (typeof exports === 'object') {
+
+    var _ = require('lodash');
+}
+
+
+// Global namespace.
+
+var joint = {
+
+    // `joint.dia` namespace.
+    dia: {},
+
+    // `joint.ui` namespace.
+    ui: {},
+
+    // `joint.layout` namespace.
+    layout: {},
+
+    // `joint.shapes` namespace.
+    shapes: {},
+
+    // `joint.format` namespace.
+    format: {},
+
+    // `joint.connectors` namespace.
+    connectors: {},
+
+    // `joint.routers` namespace.
+    routers: {},
+
+    util: {
+
+        // Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/.
+        hashCode: function(str) {
+
+            var hash = 0;
+            if (str.length == 0) return hash;
+            for (var i = 0; i < str.length; i++) {
+                var c = str.charCodeAt(i);
+                hash = ((hash << 5) - hash) + c;
+                hash = hash & hash; // Convert to 32bit integer
+            }
+            return hash;
+        },
+
+        getByPath: function(obj, path, delim) {
+            
+            delim = delim || '.';
+            var keys = path.split(delim);
+            var key;
+            
+            while (keys.length) {
+                key = keys.shift();
+                if (key in obj) {
+                    obj = obj[key];
+                } else {
+                    return undefined;
+                }
+            }
+            return obj;
+        },
+
+        setByPath: function(obj, path, value, delim) {
+
+            delim = delim || '.';
+
+            var keys = path.split(delim);
+            var diver = obj;
+            var i = 0;
+
+            if (path.indexOf(delim) > -1) {
+
+                for (var len = keys.length; i < len - 1; i++) {
+                    // diver creates an empty object if there is no nested object under such a key.
+                    // This means that one can populate an empty nested object with setByPath().
+                    diver = diver[keys[i]] || (diver[keys[i]] = {});
+                }
+                diver[keys[len - 1]] = value;
+            } else {
+                obj[path] = value;
+            }
+            return obj;
+        },
+
+        unsetByPath: function(obj, path, delim) {
+
+            delim = delim || '.';
+
+            // index of the last delimiter
+            var i = path.lastIndexOf(delim);
+
+            if (i > -1) {
+
+                // unsetting a nested attribute
+                var parent = joint.util.getByPath(obj, path.substr(0, i), delim);
+
+                if (parent) {
+
+                    delete parent[path.slice(i + 1)];
+                }
+
+            } else {
+
+                // unsetting a primitive attribute
+                delete obj[path];
+            }
+
+            return obj;
+        },
+
+        flattenObject: function(obj, delim, stop) {
+            
+            delim = delim || '.';
+            var ret = {};
+           
+           for (var key in obj) {
+               if (!obj.hasOwnProperty(key)) continue;
+
+                var shouldGoDeeper = typeof obj[key] === 'object';
+                if (shouldGoDeeper && stop && stop(obj[key])) {
+                    shouldGoDeeper = false;
+                }
+                
+               if (shouldGoDeeper) {
+                   var flatObject = this.flattenObject(obj[key], delim, stop);
+                   for (var flatKey in flatObject) {
+                       if (!flatObject.hasOwnProperty(flatKey)) continue;
+                       
+                       ret[key + delim + flatKey] = flatObject[flatKey];
+                   }
+               } else {
+                   ret[key] = obj[key];
+               }
+           }
+           return ret;
+        },
+
+        uuid: function() {
+
+            // credit: http://stackoverflow.com/posts/2117523/revisions
+            
+            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
+                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
+                return v.toString(16);
+            });
+        },
+
+        // Generate global unique id for obj and store it as a property of the object.
+        guid: function(obj) {
+            
+            this.guid.id = this.guid.id || 1;
+            obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id);
+            return obj.id;
+        },
+
+        // Copy all the properties to the first argument from the following arguments.
+        // All the properties will be overwritten by the properties from the following
+        // arguments. Inherited properties are ignored.
+        mixin: function() {
+            
+            var target = arguments[0];
+            
+            for (var i = 1, l = arguments.length; i < l; i++) {
+                
+                var extension = arguments[i];
+                
+                // Only functions and objects can be mixined.
+
+                if ((Object(extension) !== extension) &&
+                    !_.isFunction(extension) &&
+                    (extension === null || extension === undefined)) {
+
+                    continue;
+                }
+
+                _.each(extension, function(copy, key) {
+                    
+                    if (this.mixin.deep && (Object(copy) === copy)) {
+
+                        if (!target[key]) {
+
+                            target[key] = _.isArray(copy) ? [] : {};
+                        }
+                        
+                        this.mixin(target[key], copy);
+                        return;
+                    }
+                    
+                    if (target[key] !== copy) {
+                        
+                        if (!this.mixin.supplement || !target.hasOwnProperty(key)) {
+                            
+                           target[key] = copy;
+                        }
+
+                    }
+                    
+                }, this);
+            }
+            
+            return target;
+        },
+
+        // Copy all properties to the first argument from the following
+        // arguments only in case if they don't exists in the first argument.
+        // All the function propererties in the first argument will get
+        // additional property base pointing to the extenders same named
+        // property function's call method.
+        supplement: function() {
+
+            this.mixin.supplement = true;
+            var ret = this.mixin.apply(this, arguments);
+            this.mixin.supplement = false;
+            return ret;
+        },
+
+        // Same as `mixin()` but deep version.
+        deepMixin: function() {
+            
+            this.mixin.deep = true;
+            var ret = this.mixin.apply(this, arguments);
+            this.mixin.deep = false;
+            return ret;
+        },
+
+        // Same as `supplement()` but deep version.
+        deepSupplement: function() {
+            
+            this.mixin.deep = this.mixin.supplement = true;
+            var ret = this.mixin.apply(this, arguments);
+            this.mixin.deep = this.mixin.supplement = false;
+            return ret;
+        },
+
+        normalizeEvent: function(evt) {
+
+            return (evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches.length) ? evt.originalEvent.changedTouches[0] : evt;
+        },
+
+       nextFrame:(function() {
+
+           var raf;
+           var client = typeof window != 'undefined';
+
+           if (client) {
+
+               raf = window.requestAnimationFrame       ||
+                     window.webkitRequestAnimationFrame ||
+                     window.mozRequestAnimationFrame    ||
+                     window.oRequestAnimationFrame      ||
+                     window.msRequestAnimationFrame;
+
+           }
+
+           if (!raf) {
+
+               var lastTime = 0;
+
+               raf = function(callback) {
+
+                   var currTime = new Date().getTime();
+                   var timeToCall = Math.max(0, 16 - (currTime - lastTime));
+                   var id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
+                   lastTime = currTime + timeToCall;
+                   return id;
+
+               };
+           }
+
+           return client ? _.bind(raf, window) : raf;
+       })(),
+
+       cancelFrame: (function() {
+
+           var caf;
+           var client = typeof window != 'undefined';
+
+           if (client) {
+
+               caf = window.cancelAnimationFrame              ||
+                     window.webkitCancelAnimationFrame        ||
+                     window.webkitCancelRequestAnimationFrame ||
+                     window.msCancelAnimationFrame            ||
+                     window.msCancelRequestAnimationFrame     ||
+                     window.oCancelAnimationFrame             ||
+                     window.oCancelRequestAnimationFrame      ||
+                     window.mozCancelAnimationFrame           ||
+                     window.mozCancelRequestAnimationFrame;
+
+           }
+
+           caf = caf || clearTimeout;
+
+           return client ? _.bind(caf, window) : caf;
+       })(),
+
+        breakText: function(text, size, styles, opt) {
+
+            opt = opt || {};
+
+            var width = size.width;
+            var height = size.height;
+
+            var svgDocument = opt.svgDocument || V('svg').node;
+            var textElement = V('<text><tspan></tspan></text>').attr(styles || {}).node;
+            var textSpan = textElement.firstChild;
+            var textNode = document.createTextNode('');
+
+            textSpan.appendChild(textNode);
+
+            svgDocument.appendChild(textElement);
+
+            if (!opt.svgDocument) {
+
+                document.body.appendChild(svgDocument);
+            }
+
+            var words = text.split(' ');
+            var full = [];
+            var lines = [];
+            var p;
+
+            for (var i = 0, l = 0, len = words.length; i < len; i++) {
+
+                var word = words[i];
+
+                textNode.data = lines[l] ? lines[l] + ' ' + word : word;
+
+                if (textSpan.getComputedTextLength() <= width) {
+
+                    // the current line fits
+                    lines[l] = textNode.data;
+
+                    if (p) {
+                        // We were partitioning. Put rest of the word onto next line
+                        full[l++] = true;
+
+                        // cancel partitioning
+                        p = 0;
+                    }
+
+                } else {
+
+                    if (!lines[l] || p) {
+
+                        var partition = !!p;
+
+                        p = word.length - 1;
+
+                        if (partition || !p) {
+
+                            // word has only one character.
+                            if (!p) {
+
+                                if (!lines[l]) {
+
+                                    // we won't fit this text within our rect
+                                    lines = [];
+
+                                    break;
+                                }
+
+                                // partitioning didn't help on the non-empty line
+                                // try again, but this time start with a new line
+
+                                // cancel partitions created
+                                words.splice(i,2, word + words[i+1]);
+
+                                // adjust word length
+                                len--;
+
+                                full[l++] = true;
+                                i--;
+
+                                continue;
+                            }
+
+                            // move last letter to the beginning of the next word
+                            words[i] = word.substring(0,p);
+                            words[i+1] = word.substring(p) + words[i+1];
+
+                        } else {
+
+                            // We initiate partitioning
+                            // split the long word into two words
+                            words.splice(i, 1, word.substring(0,p), word.substring(p));
+
+                            // adjust words length
+                            len++;
+
+                            if (l && !full[l-1]) {
+                                // if the previous line is not full, try to fit max part of
+                                // the current word there
+                                l--;
+                            }
+                        }
+
+                        i--;
+
+                        continue;
+                    }
+
+                    l++;
+                    i--;
+                }
+
+                // if size.height is defined we have to check whether the height of the entire
+                // text exceeds the rect height
+                if (typeof height !== 'undefined') {
+
+                    // get line height as text height / 0.8 (as text height is approx. 0.8em
+                    // and line height is 1em. See vectorizer.text())
+                    var lh = lh || textElement.getBBox().height * 1.25;
+
+                    if (lh * lines.length > height) {
+
+                        // remove overflowing lines
+                        lines.splice(Math.floor(height / lh));
+
+                        break;
+                    }
+                }
+            }
+
+            if (opt.svgDocument) {
+
+                // svg document was provided, remove the text element only
+                svgDocument.removeChild(textElement);
+
+            } else {
+
+                // clean svg document
+                document.body.removeChild(svgDocument);
+            }
+
+            return lines.join('\n');
+        },
+
+       timing: {
+
+           linear: function(t) {
+               return t;
+           },
+
+           quad: function(t) {
+               return t * t;
+           },
+
+           cubic: function(t) {
+               return t * t * t;
+           },
+
+           inout: function(t) {
+               if (t <= 0) return 0;
+               if (t >= 1) return 1;
+               var t2 = t * t, t3 = t2 * t;
+               return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
+           },
+
+           exponential: function(t) {
+               return Math.pow(2, 10 * (t - 1));
+           },
+
+           bounce: function(t) {
+               for(var a = 0, b = 1; 1; a += b, b /= 2) {
+                   if (t >= (7 - 4 * a) / 11) {
+                       var q = (11 - 6 * a - 11 * t) / 4;
+                       return -q * q + b * b;
+                   }
+               }
+           },
+
+           reverse: function(f) {
+               return function(t) {
+                   return 1 - f(1 - t)
+               }
+           },
+
+           reflect: function(f) {
+               return function(t) {
+                   return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t)));
+               };
+           },
+
+           clamp: function(f,n,x) {
+               n = n || 0;
+               x = x || 1;
+               return function(t) {
+                   var r = f(t);
+                   return r < n ? n : r > x ? x : r;
+               }
+           },
+
+           back: function(s) {
+               if (!s) s = 1.70158;
+               return function(t) {
+                   return t * t * ((s + 1) * t - s);
+               };
+           },
+
+           elastic: function(x) {
+               if (!x) x = 1.5;
+               return function(t) {
+                   return Math.pow(2, 10 * (t - 1)) * Math.cos(20*Math.PI*x/3*t);
+               }
+           }
+
+       },
+
+       interpolate: {
+
+           number: function(a, b) {
+               var d = b - a;
+               return function(t) { return a + d * t; };
+           },
+
+           object: function(a, b) {
+               var s = _.keys(a);
+               return function(t) {
+                   var i, p, r = {};
+                   for (i = s.length - 1; i != -1; i--) {
+                       p = s[i];
+                       r[p] = a[p] + (b[p] - a[p]) * t;
+                   }
+                   return  r;
+               }
+           },
+
+           hexColor: function(a, b) {
+
+               var ca = parseInt(a.slice(1), 16), cb = parseInt(b.slice(1), 16);
+
+               var ra = ca & 0x0000ff, rd = (cb & 0x0000ff) - ra;
+               var ga = ca & 0x00ff00, gd = (cb & 0x00ff00) - ga;
+               var ba = ca & 0xff0000, bd = (cb & 0xff0000) - ba;
+
+               return function(t) {
+                    var r = (ra + rd * t) & 0x000000ff;
+                    var g = (ga + gd * t) & 0x0000ff00;
+                    var b = (ba + bd * t) & 0x00ff0000;
+                   return '#' + (1 << 24 | r | g | b ).toString(16).slice(1);
+               };
+           },
+
+           unit: function(a, b) {
+
+               var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/;
+
+               var ma = r.exec(a), mb = r.exec(b);
+               var p = mb[1].indexOf('.'), f = p > 0 ? mb[1].length - p - 1 : 0;
+               var a = +ma[1], d = +mb[1] - a, u = ma[2];
+
+               return function(t) {
+                   return (a + d * t).toFixed(f) + u;
+               }
+           }
+       },
+
+        // SVG filters.
+        filter: {
+
+            // `x` ... horizontal blur
+            // `y` ... vertical blur (optional)
+            blur: function(args) {
+                
+                var x = _.isFinite(args.x) ? args.x : 2;
+
+                return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>', {
+                    stdDeviation: _.isFinite(args.y) ? [x, args.y] : x
+                });
+            },
+
+            // `dx` ... horizontal shift
+            // `dy` ... vertical shift
+            // `blur` ... blur
+            // `color` ... color
+            // `opacity` ... opacity
+            dropShadow: function(args) {
+
+                var tpl = 'SVGFEDropShadowElement' in window
+                    ? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>'
+                    : '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>';
+
+                return _.template(tpl, {
+                    dx: args.dx || 0,
+                    dy: args.dy || 0,
+                    opacity: _.isFinite(args.opacity) ? args.opacity : 1,
+                    color: args.color || 'black',
+                    blur: _.isFinite(args.blur) ? args.blur : 4
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged.
+            grayscale: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+                
+                return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>', {
+                    a: 0.2126 + 0.7874 * (1 - amount),
+                    b: 0.7152 - 0.7152 * (1 - amount),
+                    c: 0.0722 - 0.0722 * (1 - amount),
+                    d: 0.2126 - 0.2126 * (1 - amount),
+                    e: 0.7152 + 0.2848 * (1 - amount),
+                    f: 0.0722 - 0.0722 * (1 - amount),
+                    g: 0.2126 - 0.2126 * (1 - amount),
+                    h: 0.0722 + 0.9278 * (1 - amount)
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 1 is completely sepia. A value of 0 leaves the input unchanged.
+            sepia: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+
+                return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>', {
+                    a: 0.393 + 0.607 * (1 - amount),
+                    b: 0.769 - 0.769 * (1 - amount),
+                    c: 0.189 - 0.189 * (1 - amount),
+                    d: 0.349 - 0.349 * (1 - amount),
+                    e: 0.686 + 0.314 * (1 - amount),
+                    f: 0.168 - 0.168 * (1 - amount),
+                    g: 0.272 - 0.272 * (1 - amount),
+                    h: 0.534 - 0.534 * (1 - amount),
+                    i: 0.131 + 0.869 * (1 - amount)
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged.
+            saturate: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+
+                return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', {
+                    amount: 1 - amount
+                });
+            },
+
+            // `angle` ...  the number of degrees around the color circle the input samples will be adjusted.
+            hueRotate: function(args) {
+
+                return _.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>', {
+                    angle: args.angle || 0
+                });
+            },
+
+            // `amount` ... the proportion of the conversion. A value of 1 is completely inverted. A value of 0 leaves the input unchanged.
+            invert: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+                
+                return _.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>', {
+                    amount: amount,
+                    amount2: 1 - amount
+                });
+            },
+
+            // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
+            brightness: function(args) {
+
+                return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>', {
+                    amount: _.isFinite(args.amount) ? args.amount : 1
+                });
+            },
+
+            // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
+            contrast: function(args) {
+
+                var amount = _.isFinite(args.amount) ? args.amount : 1;
+                
+                return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>', {
+                    amount: amount,
+                    amount2: .5 - amount / 2
+                });
+            }
+        },
+
+        format: {
+
+            // Formatting numbers via the Python Format Specification Mini-language.
+            // See http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
+            // Heavilly inspired by the D3.js library implementation.
+            number: function(specifier, value, locale) {
+
+                locale = locale || {
+
+                    currency: ['$', ''],
+                    decimal: '.',
+                    thousands: ',',
+                    grouping: [3]
+                };
+                
+                // See Python format specification mini-language: http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
+                // [[fill]align][sign][symbol][0][width][,][.precision][type]
+                var re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
+
+                var match = re.exec(specifier);
+                var fill = match[1] || ' ';
+                var align = match[2] || '>';
+                var sign = match[3] || '';
+                var symbol = match[4] || '';
+                var zfill = match[5];
+                var width = +match[6];
+                var comma = match[7];
+                var precision = match[8];
+                var type = match[9];
+                var scale = 1;
+                var prefix = '';
+                var suffix = '';
+                var integer = false;
+
+                if (precision) precision = +precision.substring(1);
+                
+                if (zfill || fill === '0' && align === '=') {
+                    zfill = fill = '0';
+                    align = '=';
+                    if (comma) width -= Math.floor((width - 1) / 4);
+                }
+
+                switch (type) {
+                  case 'n': comma = true; type = 'g'; break;
+                  case '%': scale = 100; suffix = '%'; type = 'f'; break;
+                  case 'p': scale = 100; suffix = '%'; type = 'r'; break;
+                  case 'b':
+                  case 'o':
+                  case 'x':
+                  case 'X': if (symbol === '#') prefix = '0' + type.toLowerCase();
+                  case 'c':
+                  case 'd': integer = true; precision = 0; break;
+                  case 's': scale = -1; type = 'r'; break;
+                }
+
+                if (symbol === '$') {
+                    prefix = locale.currency[0];
+                    suffix = locale.currency[1];
+                }
+
+                // If no precision is specified for `'r'`, fallback to general notation.
+                if (type == 'r' && !precision) type = 'g';
+
+                // Ensure that the requested precision is in the supported range.
+                if (precision != null) {
+                    if (type == 'g') precision = Math.max(1, Math.min(21, precision));
+                    else if (type == 'e' || type == 'f') precision = Math.max(0, Math.min(20, precision));
+                }
+
+                var zcomma = zfill && comma;
+
+                // Return the empty string for floats formatted as ints.
+                if (integer && (value % 1)) return '';
+
+                // Convert negative to positive, and record the sign prefix.
+                var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, '-') : sign;
+
+                var fullSuffix = suffix;
+                
+                // Apply the scale, computing it from the value's exponent for si format.
+                // Preserve the existing suffix, if any, such as the currency symbol.
+                if (scale < 0) {
+                    var unit = this.prefix(value, precision);
+                    value = unit.scale(value);
+                    fullSuffix = unit.symbol + suffix;
+                } else {
+                    value *= scale;
+                }
+
+                // Convert to the desired precision.
+                value = this.convert(type, value, precision);
+
+                // Break the value into the integer part (before) and decimal part (after).
+                var i = value.lastIndexOf('.');
+                var before = i < 0 ? value : value.substring(0, i);
+                var after = i < 0 ? '' : locale.decimal + value.substring(i + 1);
+
+                function formatGroup(value) {
+                    
+                    var i = value.length;
+                    var t = [];
+                    var j = 0;
+                    var g = locale.grouping[0];
+                    while (i > 0 && g > 0) {
+                        t.push(value.substring(i -= g, i + g));
+                        g = locale.grouping[j = (j + 1) % locale.grouping.length];
+                    }
+                    return t.reverse().join(locale.thousands);
+                }
+                
+                // If the fill character is not `'0'`, grouping is applied before padding.
+                if (!zfill && comma && locale.grouping) {
+
+                    before = formatGroup(before);
+                }
+
+                var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length);
+                var padding = length < width ? new Array(length = width - length + 1).join(fill) : '';
+
+                // If the fill character is `'0'`, grouping is applied after padding.
+                if (zcomma) before = formatGroup(padding + before);
+
+                // Apply prefix.
+                negative += prefix;
+
+                // Rejoin integer and decimal parts.
+                value = before + after;
+
+                return (align === '<' ? negative + value + padding
+                        : align === '>' ? padding + negative + value
+                        : align === '^' ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length)
+                        : negative + (zcomma ? value : padding + value)) + fullSuffix;
+            },
+
+            convert: function(type, value, precision) {
+
+                switch (type) {
+                  case 'b': return value.toString(2);
+                  case 'c': return String.fromCharCode(value);
+                  case 'o': return value.toString(8);
+                  case 'x': return value.toString(16);
+                  case 'X': return value.toString(16).toUpperCase();
+                  case 'g': return value.toPrecision(precision);
+                  case 'e': return value.toExponential(precision);
+                  case 'f': return value.toFixed(precision);
+                  case 'r': return (value = this.round(value, this.precision(value, precision))).toFixed(Math.max(0, Math.min(20, this.precision(value * (1 + 1e-15), precision))));
+                default: return value + '';
+                }
+            },
+
+            round: function(value, precision) {
+
+                return precision
+                    ? Math.round(value * (precision = Math.pow(10, precision))) / precision
+                    : Math.round(value);
+            },
+
+            precision: function(value, precision) {
+                
+                return precision - (value ? Math.ceil(Math.log(value) / Math.LN10) : 1);
+            },
+
+            prefix: function(value, precision) {
+
+                var prefixes = _.map(['y','z','a','f','p','n','µ','m','','k','M','G','T','P','E','Z','Y'], function(d, i) {
+                    var k = Math.pow(10, abs(8 - i) * 3);
+                    return {
+                        scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; },
+                        symbol: d
+                    };
+                });
+                
+                var i = 0;
+                if (value) {
+                    if (value < 0) value *= -1;
+                    if (precision) value = d3.round(value, this.precision(value, precision));
+                    i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
+                    i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3));
+                }
+                return prefixes[8 + i / 3];
+            }
+        }
+    }
+};
+
+if (typeof exports === 'object') {
+
+    module.exports = joint;
+}
+
+//      JointJS, the JavaScript diagramming library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        dia: {
+            Link: require('./joint.dia.link').Link,
+            Element: require('./joint.dia.element').Element
+        },
+        shapes: require('../plugins/shapes')
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+    var g = require('./geometry');
+}
+
+
+
+joint.dia.GraphCells = Backbone.Collection.extend({
+
+    initialize: function() {
+        
+        // Backbone automatically doesn't trigger re-sort if models attributes are changed later when
+        // they're already in the collection. Therefore, we're triggering sort manually here.
+        this.on('change:z', this.sort, this);
+    },
+
+    model: function(attrs, options) {
+
+        if (attrs.type === 'link') {
+
+            return new joint.dia.Link(attrs, options);
+        }
+
+        var module = attrs.type.split('.')[0];
+        var entity = attrs.type.split('.')[1];
+
+        if (joint.shapes[module] && joint.shapes[module][entity]) {
+
+            return new joint.shapes[module][entity](attrs, options);
+        }
+        
+        return new joint.dia.Element(attrs, options);
+    },
+
+    // `comparator` makes it easy to sort cells based on their `z` index.
+    comparator: function(model) {
+
+        return model.get('z') || 0;
+    },
+
+    // Get all inbound and outbound links connected to the cell `model`.
+    getConnectedLinks: function(model, opt) {
+
+        opt = opt || {};
+
+        if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) {
+            opt.inbound = opt.outbound = true;
+        }
+
+        var links = [];
+        
+        this.each(function(cell) {
+
+            var source = cell.get('source');
+            var target = cell.get('target');
+
+            if (source && source.id === model.id && opt.outbound) {
+                
+                links.push(cell);
+            }
+
+            if (target && target.id === model.id && opt.inbound) {
+
+                links.push(cell);
+            }
+        });
+
+        return links;
+    }
+});
+
+
+joint.dia.Graph = Backbone.Model.extend({
+
+    initialize: function() {
+
+        this.set('cells', new joint.dia.GraphCells);
+
+        // Make all the events fired in the `cells` collection available.
+        // to the outside world.
+        this.get('cells').on('all', this.trigger, this);
+        
+        this.get('cells').on('remove', this.removeCell, this);
+    },
+
+    toJSON: function() {
+
+        // Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections.
+        // It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitely.
+        var json = Backbone.Model.prototype.toJSON.apply(this, arguments);
+        json.cells = this.get('cells').toJSON();
+        return json;
+    },
+
+    fromJSON: function(json) {
+
+        if (!json.cells) {
+
+            throw new Error('Graph JSON must contain cells array.');
+        }
+
+        var attrs = json;
+
+        // Cells are the only attribute that is being set differently, using `cells.add()`.
+        var cells = json.cells;
+        delete attrs.cells;
+        
+        this.set(attrs);
+        
+        this.resetCells(cells);
+    },
+
+    clear: function() {
+
+        this.trigger('batch:start');
+        this.get('cells').remove(this.get('cells').models);
+        this.trigger('batch:stop');
+    },
+
+    _prepareCell: function(cell) {
+
+        if (cell instanceof Backbone.Model && _.isUndefined(cell.get('z'))) {
+
+            cell.set('z', this.maxZIndex() + 1, { silent: true });
+            
+        } else if (_.isUndefined(cell.z)) {
+
+            cell.z = this.maxZIndex() + 1;
+        }
+
+        return cell;
+    },
+
+    maxZIndex: function() {
+
+        var lastCell = this.get('cells').last();
+        return lastCell ? (lastCell.get('z') || 0) : 0;
+    },
+
+    addCell: function(cell, options) {
+
+        if (_.isArray(cell)) {
+
+            return this.addCells(cell, options);
+        }
+
+        this.get('cells').add(this._prepareCell(cell), options || {});
+
+        return this;
+    },
+
+    addCells: function(cells, options) {
+
+        _.each(cells, function(cell) { this.addCell(cell, options); }, this);
+
+        return this;
+    },
+
+    // When adding a lot of cells, it is much more efficient to
+    // reset the entire cells collection in one go.
+    // Useful for bulk operations and optimizations.
+    resetCells: function(cells) {
+        
+        this.get('cells').reset(_.map(cells, this._prepareCell, this));
+
+        return this;
+    },
+
+    removeCell: function(cell, collection, options) {
+
+        // Applications might provide a `disconnectLinks` option set to `true` in order to
+        // disconnect links when a cell is removed rather then removing them. The default
+        // is to remove all the associated links.
+        if (options && options.disconnectLinks) {
+            
+            this.disconnectLinks(cell);
+
+        } else {
+
+            this.removeLinks(cell);
+        }
+
+        // Silently remove the cell from the cells collection. Silently, because
+        // `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is
+        // then propagated to the graph model. If we didn't remove the cell silently, two `remove` events
+        // would be triggered on the graph model.
+        this.get('cells').remove(cell, { silent: true });
+    },
+
+    // Get a cell by `id`.
+    getCell: function(id) {
+
+        return this.get('cells').get(id);
+    },
+
+    getElements: function() {
+
+        return this.get('cells').filter(function(cell) {
+
+            return cell instanceof joint.dia.Element;
+        });
+    },
+    
+    getLinks: function() {
+
+        return this.get('cells').filter(function(cell) {
+
+            return cell instanceof joint.dia.Link;
+        });
+    },
+
+    // Get all inbound and outbound links connected to the cell `model`.
+    getConnectedLinks: function(model, opt) {
+
+        return this.get('cells').getConnectedLinks(model, opt);
+    },
+
+    getNeighbors: function(el) {
+
+        var links = this.getConnectedLinks(el);
+        var neighbors = [];
+        var cells = this.get('cells');
+        
+        _.each(links, function(link) {
+
+            var source = link.get('source');
+            var target = link.get('target');
+
+            // Discard if it is a point.
+            if (!source.x) {
+                var sourceElement = cells.get(source.id);
+                if (sourceElement !== el) {
+
+                    neighbors.push(sourceElement);
+                }
+            }
+            if (!target.x) {
+                var targetElement = cells.get(target.id);
+                if (targetElement !== el) {
+
+                    neighbors.push(targetElement);
+                }
+            }
+        });
+
+        return neighbors;
+    },
+    
+    // Disconnect links connected to the cell `model`.
+    disconnectLinks: function(model) {
+
+        _.each(this.getConnectedLinks(model), function(link) {
+
+            link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0));
+        });
+    },
+
+    // Remove links connected to the cell `model` completely.
+    removeLinks: function(model) {
+
+        _.invoke(this.getConnectedLinks(model), 'remove');
+    },
+
+    // Find all views at given point
+    findModelsFromPoint: function(p) {
+
+       return _.filter(this.getElements(), function(el) {
+           return el.getBBox().containsPoint(p);
+       });
+    },
+
+
+    // Find all views in given area
+    findModelsInArea: function(r) {
+
+       return _.filter(this.getElements(), function(el) {
+           return el.getBBox().intersect(r);
+       });
+    }
+
+});
+
+
+if (typeof exports === 'object') {
+
+    module.exports.Graph = joint.dia.Graph;
+}
+//      JointJS.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('./core').util,
+        dia: {
+            Link: require('./joint.dia.link').Link
+        }
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+}
+
+
+// joint.dia.Cell base model.
+// --------------------------
+
+joint.dia.Cell = Backbone.Model.extend({
+
+    // This is the same as Backbone.Model with the only difference that is uses _.merge
+    // instead of just _.extend. The reason is that we want to mixin attributes set in upper classes.
+    constructor: function(attributes, options) {
+
+        var defaults;
+        var attrs = attributes || {};
+        this.cid = _.uniqueId('c');
+        this.attributes = {};
+        if (options && options.collection) this.collection = options.collection;
+        if (options && options.parse) attrs = this.parse(attrs, options) || {};
+        if (defaults = _.result(this, 'defaults')) {
+            //<custom code>
+            // Replaced the call to _.defaults with _.merge.
+            attrs = _.merge({}, defaults, attrs);
+            //</custom code>
+        }
+        this.set(attrs, options);
+        this.changed = {};
+        this.initialize.apply(this, arguments);
+    },
+
+    toJSON: function() {
+
+        var defaultAttrs = this.constructor.prototype.defaults.attrs || {};
+        var attrs = this.attributes.attrs;
+        var finalAttrs = {};
+
+        // Loop through all the attributes and
+        // omit the default attributes as they are implicitly reconstructable by the cell 'type'.
+        _.each(attrs, function(attr, selector) {
+
+            var defaultAttr = defaultAttrs[selector];
+
+            _.each(attr, function(value, name) {
+                
+                // attr is mainly flat though it might have one more level (consider the `style` attribute).
+                // Check if the `value` is object and if yes, go one level deep.
+                if (_.isObject(value) && !_.isArray(value)) {
+                    
+                    _.each(value, function(value2, name2) {
+
+                        if (!defaultAttr || !defaultAttr[name] || !_.isEqual(defaultAttr[name][name2], value2)) {
+
+                            finalAttrs[selector] = finalAttrs[selector] || {};
+                            (finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2;
+                        }
+                    });
+
+                } else if (!defaultAttr || !_.isEqual(defaultAttr[name], value)) {
+                    // `value` is not an object, default attribute for such a selector does not exist
+                    // or it is different than the attribute value set on the model.
+
+                    finalAttrs[selector] = finalAttrs[selector] || {};
+                    finalAttrs[selector][name] = value;
+                }
+            });
+        });
+
+        var attributes = _.cloneDeep(_.omit(this.attributes, 'attrs'));
+        //var attributes = JSON.parse(JSON.stringify(_.omit(this.attributes, 'attrs')));
+        attributes.attrs = finalAttrs;
+
+        return attributes;
+    },
+
+    initialize: function(options) {
+
+        if (!options || !options.id) {
+
+            this.set('id', joint.util.uuid(), { silent: true });
+        }
+
+       this._transitionIds = {};
+
+        // Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes.
+        this.processPorts();
+        this.on('change:attrs', this.processPorts, this);
+    },
+
+    processPorts: function() {
+
+        // Whenever `attrs` changes, we extract ports from the `attrs` object and store it
+        // in a more accessible way. Also, if any port got removed and there were links that had `target`/`source`
+        // set to that port, we remove those links as well (to follow the same behaviour as
+        // with a removed element).
+
+        var previousPorts = this.ports;
+
+        // Collect ports from the `attrs` object.
+        var ports = {};
+        _.each(this.get('attrs'), function(attrs, selector) {
+
+            if (attrs && attrs.port) {
+
+                // `port` can either be directly an `id` or an object containing an `id` (and potentially other data).
+                if (!_.isUndefined(attrs.port.id)) {
+                    ports[attrs.port.id] = attrs.port;
+                } else {
+                    ports[attrs.port] = { id: attrs.port };
+                }
+            }
+        });
+
+        // Collect ports that have been removed (compared to the previous ports) - if any.
+        // Use hash table for quick lookup.
+        var removedPorts = {};
+        _.each(previousPorts, function(port, id) {
+
+            if (!ports[id]) removedPorts[id] = true;
+        });
+
+        // Remove all the incoming/outgoing links that have source/target port set to any of the removed ports.
+        if (this.collection && !_.isEmpty(removedPorts)) {
+            
+            var inboundLinks = this.collection.getConnectedLinks(this, { inbound: true });
+            _.each(inboundLinks, function(link) {
+
+                if (removedPorts[link.get('target').port]) link.remove();
+            });
+
+            var outboundLinks = this.collection.getConnectedLinks(this, { outbound: true });
+            _.each(outboundLinks, function(link) {
+
+                if (removedPorts[link.get('source').port]) link.remove();
+            });
+        }
+
+        // Update the `ports` object.
+        this.ports = ports;
+    },
+
+    remove: function(options) {
+
+       var collection = this.collection;
+
+       if (collection) {
+           collection.trigger('batch:start');
+       }
+
+        // First, unembed this cell from its parent cell if there is one.
+        var parentCellId = this.get('parent');
+        if (parentCellId) {
+            
+            var parentCell = this.collection && this.collection.get(parentCellId);
+            parentCell.unembed(this);
+        }
+        
+        _.invoke(this.getEmbeddedCells(), 'remove', options);
+        
+        this.trigger('remove', this, this.collection, options);
+
+       if (collection) {
+           collection.trigger('batch:stop');
+       }
+    },
+
+    toFront: function() {
+
+        if (this.collection) {
+
+            this.set('z', (this.collection.last().get('z') || 0) + 1);
+        }
+    },
+    
+    toBack: function() {
+
+        if (this.collection) {
+            
+            this.set('z', (this.collection.first().get('z') || 0) - 1);
+        }
+    },
+
+    embed: function(cell) {
+
+       if (this.get('parent') == cell.id) {
+
+           throw new Error('Recursive embedding not allowed.');
+
+       } else {
+
+           this.trigger('batch:start');
+
+           cell.set('parent', this.id);
+           this.set('embeds', _.uniq((this.get('embeds') || []).concat([cell.id])));
+
+           this.trigger('batch:stop');
+       }
+    },
+
+    unembed: function(cell) {
+
+       this.trigger('batch:start');
+
+        var cellId = cell.id;
+        cell.unset('parent');
+
+        this.set('embeds', _.without(this.get('embeds'), cellId));
+
+       this.trigger('batch:stop');
+    },
+
+    getEmbeddedCells: function() {
+
+        // Cell models can only be retrieved when this element is part of a collection.
+        // There is no way this element knows about other cells otherwise.
+        // This also means that calling e.g. `translate()` on an element with embeds before
+        // adding it to a graph does not translate its embeds.
+        if (this.collection) {
+
+            return _.map(this.get('embeds') || [], function(cellId) {
+
+                return this.collection.get(cellId);
+                
+            }, this);
+        }
+        return [];
+    },
+
+    clone: function(opt) {
+
+        opt = opt || {};
+
+        var clone = Backbone.Model.prototype.clone.apply(this, arguments);
+        
+        // We don't want the clone to have the same ID as the original.
+        clone.set('id', joint.util.uuid(), { silent: true });
+        clone.set('embeds', '');
+
+        if (!opt.deep) return clone;
+
+        // The rest of the `clone()` method deals with embeds. If `deep` option is set to `true`,
+        // the return value is an array of all the embedded clones created.
+
+        var embeds = this.getEmbeddedCells();
+
+        var clones = [clone];
+
+        // This mapping stores cloned links under the `id`s of they originals.
+        // This prevents cloning a link more then once. Consider a link 'self loop' for example.
+        var linkCloneMapping = {};
+        
+        _.each(embeds, function(embed) {
+
+            var embedClones = embed.clone({ deep: true });
+
+            // Embed the first clone returned from `clone({ deep: true })` above. The first
+            // cell is always the clone of the cell that called the `clone()` method, i.e. clone of `embed` in this case.
+            clone.embed(embedClones[0]);
+
+            _.each(embedClones, function(embedClone) {
+
+                clones.push(embedClone);
+
+                // Skip links. Inbound/outbound links are not relevant for them.
+                if (embedClone instanceof joint.dia.Link) {
+
+                    return;
+                }
+
+                // Collect all inbound links, clone them (if not done already) and set their target to the `embedClone.id`.
+                var inboundLinks = this.collection.getConnectedLinks(embed, { inbound: true });
+
+                _.each(inboundLinks, function(link) {
+
+                    var linkClone = linkCloneMapping[link.id] || link.clone();
+
+                    // Make sure we don't clone a link more then once.
+                    linkCloneMapping[link.id] = linkClone;
+
+                    var target = _.clone(linkClone.get('target'));
+                    target.id = embedClone.id;
+                    linkClone.set('target', target);
+                });
+
+                // Collect all inbound links, clone them (if not done already) and set their source to the `embedClone.id`.
+                var outboundLinks = this.collection.getConnectedLinks(embed, { outbound: true });
+
+                _.each(outboundLinks, function(link) {
+
+                    var linkClone = linkCloneMapping[link.id] || link.clone();
+
+                    // Make sure we don't clone a link more then once.
+                    linkCloneMapping[link.id] = linkClone;
+
+                    var source = _.clone(linkClone.get('source'));
+                    source.id = embedClone.id;
+                    linkClone.set('source', source);
+                });
+
+            }, this);
+            
+        }, this);
+
+        // Add link clones to the array of all the new clones.
+        clones = clones.concat(_.values(linkCloneMapping));
+
+        return clones;
+    },
+
+    // A convenient way to set nested attributes.
+    attr: function(attrs, value, opt) {
+
+        var currentAttrs = this.get('attrs');
+        var delim = '/';
+        
+        if (_.isString(attrs)) {
+            // Get/set an attribute by a special path syntax that delimits
+            // nested objects by the colon character.
+
+            if (typeof value != 'undefined') {
+
+                var attr = {};
+                joint.util.setByPath(attr, attrs, value, delim);
+                return this.set('attrs', _.merge({}, currentAttrs, attr), opt);
+                
+            } else {
+                
+                return joint.util.getByPath(currentAttrs, attrs, delim);
+            }
+        }
+        
+        return this.set('attrs', _.merge({}, currentAttrs, attrs), value, opt);
+    },
+
+    // A convenient way to unset nested attributes
+    removeAttr: function(path, opt) {
+
+        if (_.isArray(path)) {
+            _.each(path, function(p) { this.removeAttr(p, opt); }, this);
+            return this;
+        }
+        
+        var attrs = joint.util.unsetByPath(_.merge({}, this.get('attrs')), path, '/');
+
+        return this.set('attrs', attrs, _.extend({ dirty: true }, opt));
+    },
+
+    transition: function(path, value, opt, delim) {
+
+       delim = delim || '/';
+
+       var defaults = {
+           duration: 100,
+           delay: 10,
+           timingFunction: joint.util.timing.linear,
+           valueFunction: joint.util.interpolate.number
+       };
+
+       opt = _.extend(defaults, opt);
+
+       var pathArray = path.split(delim);
+        var property = pathArray[0];
+       var isPropertyNested = pathArray.length > 1;
+       var firstFrameTime = 0;
+       var interpolatingFunction;
+
+       var setter = _.bind(function(runtime) {
+
+           var id, progress, propertyValue, status;
+
+           firstFrameTime = firstFrameTime || runtime;
+           runtime -= firstFrameTime;
+           progress = runtime / opt.duration;
+
+           if (progress < 1) {
+               this._transitionIds[path] = id = joint.util.nextFrame(setter);
+           } else {
+               progress = 1;
+               delete this._transitionIds[path];
+           }
+
+           propertyValue = interpolatingFunction(opt.timingFunction(progress));
+
+           if (isPropertyNested) {
+               var nestedPropertyValue = joint.util.setByPath({}, path, propertyValue, delim)[property];
+               propertyValue = _.merge({}, this.get(property), nestedPropertyValue);
+           }
+
+           opt.transitionId = id;
+
+           this.set(property, propertyValue, opt);
+
+           if (!id) this.trigger('transition:end', this, path);
+
+       }, this);
+
+       var initiator =_.bind(function(callback) {
+
+           this.stopTransitions(path);
+
+           interpolatingFunction = opt.valueFunction(joint.util.getByPath(this.attributes, path, delim), value);
+
+           this._transitionIds[path] = joint.util.nextFrame(callback);
+
+           this.trigger('transition:start', this, path);
+
+       }, this);
+
+       return _.delay(initiator, opt.delay, setter);
+    },
+
+    getTransitions: function() {
+       return _.keys(this._transitionIds);
+    },
+
+    stopTransitions: function(path, delim) {
+
+       delim = delim || '/';
+
+       var pathArray = path && path.split(delim);
+
+       _(this._transitionIds).keys().filter(pathArray && function(key) {
+
+           return _.isEqual(pathArray, key.split(delim).slice(0, pathArray.length));
+
+       }).each(function(key) {
+
+           joint.util.cancelFrame(this._transitionIds[key]);
+
+           delete this._transitionIds[key];
+
+           this.trigger('transition:end', this, key);
+
+       }, this);
+    }
+});
+
+// joint.dia.CellView base view and controller.
+// --------------------------------------------
+
+// This is the base view and controller for `joint.dia.ElementView` and `joint.dia.LinkView`.
+
+joint.dia.CellView = Backbone.View.extend({
+
+    tagName: 'g',
+
+    attributes: function() {
+
+        return { 'model-id': this.model.id }
+    },
+
+    initialize: function() {
+
+        _.bindAll(this, 'remove', 'update');
+
+        // Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree.
+        this.$el.data('view', this);
+
+       this.listenTo(this.model, 'remove', this.remove);
+       this.listenTo(this.model, 'change:attrs', this.onChangeAttrs);
+    },
+
+    onChangeAttrs: function(cell, attrs, opt) {
+
+        if (opt.dirty) {
+
+            // dirty flag could be set when a model attribute was removed and it needs to be cleared
+            // also from the DOM element. See cell.removeAttr().
+            return this.render();
+        }
+
+        return this.update();
+    },
+
+    _configure: function(options) {
+
+        // Make sure a global unique id is assigned to this view. Store this id also to the properties object.
+        // The global unique id makes sure that the same view can be rendered on e.g. different machines and
+        // still be associated to the same object among all those clients. This is necessary for real-time
+        // collaboration mechanism.
+        options.id = options.id || joint.util.guid(this);
+        
+        Backbone.View.prototype._configure.apply(this, arguments);
+    },
+
+    // Override the Backbone `_ensureElement()` method in order to create a `<g>` node that wraps
+    // all the nodes of the Cell view.
+    _ensureElement: function() {
+
+        var el;
+
+        if (!this.el) {
+
+            var attrs = _.extend({ id: this.id }, _.result(this, 'attributes'));
+            if (this.className) attrs['class'] = _.result(this, 'className');
+            el = V(_.result(this, 'tagName'), attrs).node;
+
+        } else {
+
+            el = _.result(this, 'el')
+        }
+
+        this.setElement(el, false);
+    },
+    
+    findBySelector: function(selector) {
+
+        // These are either descendants of `this.$el` of `this.$el` itself. 
+       // `.` is a special selector used to select the wrapping `<g>` element.
+        var $selected = selector === '.' ? this.$el : this.$el.find(selector);
+        return $selected;
+    },
+
+    notify: function(evt) {
+
+        if (this.paper) {
+
+            var args = Array.prototype.slice.call(arguments, 1);
+
+            // Trigger the event on both the element itself and also on the paper.
+            this.trigger.apply(this, [evt].concat(args));
+            
+            // Paper event handlers receive the view object as the first argument.
+            this.paper.trigger.apply(this.paper, [evt, this].concat(args));
+        }
+    },
+
+    getStrokeBBox: function(el) {
+        // Return a bounding box rectangle that takes into account stroke.
+        // Note that this is a naive and ad-hoc implementation that does not
+        // works only in certain cases and should be replaced as soon as browsers will
+        // start supporting the getStrokeBBox() SVG method.
+        // @TODO any better solution is very welcome!
+
+        var isMagnet = !!el;
+        
+        el = el || this.el;
+        var bbox = V(el).bbox(false, this.paper.viewport);
+
+        var strokeWidth;
+        if (isMagnet) {
+
+            strokeWidth = V(el).attr('stroke-width');
+            
+        } else {
+
+            strokeWidth = this.model.attr('rect/stroke-width') || this.model.attr('circle/stroke-width') || this.model.attr('ellipse/stroke-width') || this.model.attr('path/stroke-width');
+        }
+
+        strokeWidth = parseFloat(strokeWidth) || 0;
+
+        return g.rect(bbox).moveAndExpand({ x: -strokeWidth/2, y: -strokeWidth/2, width: strokeWidth, height: strokeWidth });
+    },
+    
+    getBBox: function() {
+
+        return V(this.el).bbox();
+    },
+
+    highlight: function(el) {
+
+        el = !el ? this.el : this.$(el)[0] || this.el;
+
+        V(el).addClass('highlighted');
+    },
+
+    unhighlight: function(el) {
+
+        el = !el ? this.el : this.$(el)[0] || this.el;
+
+        V(el).removeClass('highlighted');
+    },
+
+    // Find the closest element that has the `magnet` attribute set to `true`. If there was not such
+    // an element found, return the root element of the cell view.
+    findMagnet: function(el) {
+
+        var $el = this.$(el);
+
+        if ($el.length === 0 || $el[0] === this.el) {
+
+            // If the overall cell has set `magnet === false`, then return `undefined` to
+            // announce there is no magnet found for this cell.
+            // This is especially useful to set on cells that have 'ports'. In this case,
+            // only the ports have set `magnet === true` and the overall element has `magnet === false`.
+            var attrs = this.model.get('attrs') || {};
+            if (attrs['.'] && attrs['.']['magnet'] === false) {
+                return undefined;
+            }
+
+            return this.el;
+        }
+
+        if ($el.attr('magnet')) {
+
+            return $el[0];
+        }
+
+        return this.findMagnet($el.parent());
+    },
+
+    // `selector` is a CSS selector or `'.'`. `filter` must be in the special JointJS filter format:
+    // `{ name: <name of the filter>, args: { <arguments>, ... }`.
+    // An example is: `{ filter: { name: 'blur', args: { radius: 5 } } }`.
+    applyFilter: function(selector, filter) {
+
+        var $selected = this.findBySelector(selector);
+
+        // Generate a hash code from the stringified filter definition. This gives us
+        // a unique filter ID for different definitions.
+        var filterId = filter.name + this.paper.svg.id + joint.util.hashCode(JSON.stringify(filter));
+
+        // If the filter already exists in the document,
+        // we're done and we can just use it (reference it using `url()`).
+        // If not, create one.
+        if (!this.paper.svg.getElementById(filterId)) {
+
+            var filterSVGString = joint.util.filter[filter.name] && joint.util.filter[filter.name](filter.args || {});
+            if (!filterSVGString) {
+                throw new Error('Non-existing filter ' + filter.name);
+            }
+            var filterElement = V(filterSVGString);
+            filterElement.attr('filterUnits', 'userSpaceOnUse');
+            if (filter.attrs) filterElement.attr(filter.attrs);
+            filterElement.node.id = filterId;
+            V(this.paper.svg).defs().append(filterElement);
+        }
+
+        $selected.each(function() {
+            
+            V(this).attr('filter', 'url(#' + filterId + ')');
+        });
+    },
+
+    // `selector` is a CSS selector or `'.'`. `attr` is either a `'fill'` or `'stroke'`.
+    // `gradient` must be in the special JointJS gradient format:
+    // `{ type: <linearGradient|radialGradient>, stops: [ { offset: <offset>, color: <color> }, ... ]`.
+    // An example is: `{ fill: { type: 'linearGradient', stops: [ { offset: '10%', color: 'green' }, { offset: '50%', color: 'blue' } ] } }`.
+    applyGradient: function(selector, attr, gradient) {
+
+        var $selected = this.findBySelector(selector);
+
+        // Generate a hash code from the stringified filter definition. This gives us
+        // a unique filter ID for different definitions.
+        var gradientId = gradient.type + this.paper.svg.id + joint.util.hashCode(JSON.stringify(gradient));
+
+        // If the gradient already exists in the document,
+        // we're done and we can just use it (reference it using `url()`).
+        // If not, create one.
+        if (!this.paper.svg.getElementById(gradientId)) {
+
+            var gradientSVGString = [
+                '<' + gradient.type + '>',
+                _.map(gradient.stops, function(stop) {
+                    return '<stop offset="' + stop.offset + '" stop-color="' + stop.color + '" stop-opacity="' + (_.isFinite(stop.opacity) ? stop.opacity : 1) + '" />'
+                }).join(''),
+                '</' + gradient.type + '>'
+            ].join('');
+            
+            var gradientElement = V(gradientSVGString);
+            if (gradient.attrs) { gradientElement.attr(gradient.attrs); }
+            gradientElement.node.id = gradientId;
+            V(this.paper.svg).defs().append(gradientElement);
+        }
+
+        $selected.each(function() {
+            
+            V(this).attr(attr, 'url(#' + gradientId + ')');
+        });
+    },
+
+    // Construct a unique selector for the `el` element within this view.
+    // `selector` is being collected through the recursive call. No value for `selector` is expected when using this method.
+    getSelector: function(el, selector) {
+
+        if (el === this.el) {
+
+            return selector;
+        }
+
+        var index = $(el).index();
+
+        selector = el.tagName + ':nth-child(' + (index + 1) + ')' + ' ' + (selector || '');
+
+        return this.getSelector($(el).parent()[0], selector + ' ');
+    },
+
+    // Interaction. The controller part.
+    // ---------------------------------
+
+    // Interaction is handled by the paper and delegated to the view in interest.
+    // `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid.
+    // If necessary, real coordinates can be obtained from the `evt` event object.
+
+    // These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`,
+    // i.e. `joint.dia.Element` and `joint.dia.Link`.
+
+    pointerdblclick: function(evt, x, y) {
+
+        this.notify('cell:pointerdblclick', evt, x, y);
+    },
+
+    pointerclick: function(evt, x, y) {
+
+        this.notify('cell:pointerclick', evt, x, y);
+    },
+    
+    pointerdown: function(evt, x, y) {
+
+       if (this.model.collection) {
+           this.model.trigger('batch:start');
+           this._collection = this.model.collection;
+       }
+
+        this.notify('cell:pointerdown', evt, x, y);
+    },
+    
+    pointermove: function(evt, x, y) {
+
+        this.notify('cell:pointermove', evt, x, y);
+    },
+    
+    pointerup: function(evt, x, y) {
+
+        this.notify('cell:pointerup', evt, x, y);
+
+       if (this._collection) {
+           // we don't want to trigger event on model as model doesn't
+           // need to be member of collection anymore (remove)
+           this._collection.trigger('batch:stop');
+           delete this._collection;
+       }
+
+    }
+});
+
+
+if (typeof exports === 'object') {
+
+    module.exports.Cell = joint.dia.Cell;
+    module.exports.CellView = joint.dia.CellView;
+}
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('./core').util,
+        dia: {
+            Cell: require('./joint.dia.cell').Cell,
+            CellView: require('./joint.dia.cell').CellView
+        }
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+}
+
+
+// joint.dia.Element base model.
+// -----------------------------
+
+joint.dia.Element = joint.dia.Cell.extend({
+
+    defaults: {
+        position: { x: 0, y: 0 },
+       size: { width: 1, height: 1 },
+        angle: 0
+    },
+
+    position: function(x, y) {
+
+        this.set('position', { x: x, y: y });
+    },
+    
+    translate: function(tx, ty, opt) {
+
+        ty = ty || 0;
+
+        if (tx === 0 && ty === 0) {
+            // Like nothing has happened.
+            return this;
+        }
+
+        var position = this.get('position') || { x: 0, y: 0 };
+       var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 };
+
+       if (opt && opt.transition) {
+
+           if (!_.isObject(opt.transition)) opt.transition = {};
+
+           this.transition('position', translatedPosition, _.extend({}, opt.transition, {
+               valueFunction: joint.util.interpolate.object
+           }));
+
+       } else {
+
+            this.set('position', translatedPosition, opt);
+
+            // Recursively call `translate()` on all the embeds cells.
+            _.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt);
+       }
+
+        return this;
+    },
+
+    resize: function(width, height) {
+
+       this.trigger('batch:start');
+        this.set('size', { width: width, height: height });
+       this.trigger('batch:stop');
+
+       return this;
+    },
+
+    rotate: function(angle, absolute) {
+
+        return this.set('angle', absolute ? angle : ((this.get('angle') || 0) + angle) % 360);
+    },
+
+    getBBox: function() {
+
+       var position = this.get('position');
+       var size = this.get('size');
+
+       return g.rect(position.x, position.y, size.width, size.height);
+    }
+});
+
+// joint.dia.Element base view and controller.
+// -------------------------------------------
+
+joint.dia.ElementView = joint.dia.CellView.extend({
+
+    className: function() {
+        return 'element ' + this.model.get('type').split('.').join(' ');
+    },
+
+    initialize: function() {
+
+        _.bindAll(this, 'translate', 'resize', 'rotate');
+
+        joint.dia.CellView.prototype.initialize.apply(this, arguments);
+        
+       this.listenTo(this.model, 'change:position', this.translate);
+       this.listenTo(this.model, 'change:size', this.resize);
+       this.listenTo(this.model, 'change:angle', this.rotate);
+    },
+
+    // Default is to process the `attrs` object and set attributes on subelements based on the selectors.
+    update: function(cell, renderingOnlyAttrs) {
+
+        var allAttrs = this.model.get('attrs');
+
+        var rotatable = V(this.$('.rotatable')[0]);
+        if (rotatable) {
+
+            var rotation = rotatable.attr('transform');
+            rotatable.attr('transform', '');
+        }
+        
+        var relativelyPositioned = [];
+
+        _.each(renderingOnlyAttrs || allAttrs, function(attrs, selector) {
+
+            // Elements that should be updated.
+            var $selected = this.findBySelector(selector);
+
+            // No element matched by the `selector` was found. We're done then.
+            if ($selected.length === 0) return;
+
+            // Special attributes are treated by JointJS, not by SVG.
+            var specialAttributes = ['style', 'text', 'html', 'ref-x', 'ref-y', 'ref-dx', 'ref-dy', 'ref-width', 'ref-height', 'ref', 'x-alignment', 'y-alignment', 'port'];
+
+            // If the `filter` attribute is an object, it is in the special JointJS filter format and so
+            // it becomes a special attribute and is treated separately.
+            if (_.isObject(attrs.filter)) {
+
+                specialAttributes.push('filter');
+                this.applyFilter(selector, attrs.filter);
+            }
+
+            // If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so
+            // it becomes a special attribute and is treated separately.
+            if (_.isObject(attrs.fill)) {
+
+                specialAttributes.push('fill');
+                this.applyGradient(selector, 'fill', attrs.fill);
+            }
+            if (_.isObject(attrs.stroke)) {
+
+                specialAttributes.push('stroke');
+                this.applyGradient(selector, 'stroke', attrs.stroke);
+            }
+
+            // Make special case for `text` attribute. So that we can set text content of the `<text>` element
+            // via the `attrs` object as well.
+            // Note that it's important to set text before applying the rest of the final attributes.
+            // Vectorizer `text()` method sets on the element its own attributes and it has to be possible
+            // to rewrite them, if needed. (i.e display: 'none')
+            if (!_.isUndefined(attrs.text)) {
+
+                $selected.each(function() {
+
+                    V(this).text(attrs.text + '');
+                });
+            }
+
+            // Set regular attributes on the `$selected` subelement. Note that we cannot use the jQuery attr()
+            // method as some of the attributes might be namespaced (e.g. xlink:href) which fails with jQuery attr().
+            var finalAttributes = _.omit(attrs, specialAttributes);
+            
+            $selected.each(function() {
+                
+                V(this).attr(finalAttributes);
+            });
+
+            // `port` attribute contains the `id` of the port that the underlying magnet represents.
+            if (attrs.port) {
+
+                $selected.attr('port', _.isUndefined(attrs.port.id) ? attrs.port : attrs.port.id);
+            }
+
+            // `style` attribute is special in the sense that it sets the CSS style of the subelement.
+            if (attrs.style) {
+
+                $selected.css(attrs.style);
+            }
+            
+            if (!_.isUndefined(attrs.html)) {
+
+                $selected.each(function() {
+
+                    $(this).html(attrs.html + '');
+                });
+            }
+            
+            // Special `ref-x` and `ref-y` attributes make it possible to set both absolute or
+            // relative positioning of subelements.
+            if (!_.isUndefined(attrs['ref-x']) ||
+                !_.isUndefined(attrs['ref-y']) ||
+                !_.isUndefined(attrs['ref-dx']) ||
+                !_.isUndefined(attrs['ref-dy']) ||
+               !_.isUndefined(attrs['x-alignment']) ||
+               !_.isUndefined(attrs['y-alignment']) ||
+                !_.isUndefined(attrs['ref-width']) ||
+                !_.isUndefined(attrs['ref-height'])
+               ) {
+
+                   _.each($selected, function(el, index, list) {
+                       var $el = $(el);
+                       // copy original list selector to the element
+                       $el.selector = list.selector;
+                       relativelyPositioned.push($el);
+                   });
+            }
+            
+        }, this);
+
+        // We don't want the sub elements to affect the bounding box of the root element when
+        // positioning the sub elements relatively to the bounding box.
+        //_.invoke(relativelyPositioned, 'hide');
+        //_.invoke(relativelyPositioned, 'show');
+
+        // Note that we're using the bounding box without transformation because we are already inside
+        // a transformed coordinate system.
+        var bbox = this.el.getBBox();        
+
+        renderingOnlyAttrs = renderingOnlyAttrs || {};
+
+        _.each(relativelyPositioned, function($el) {
+
+            // if there was a special attribute affecting the position amongst renderingOnlyAttributes
+            // we have to merge it with rest of the element's attributes as they are necessary
+            // to update the position relatively (i.e `ref`)
+            var renderingOnlyElAttrs = renderingOnlyAttrs[$el.selector];
+            var elAttrs = renderingOnlyElAttrs
+                ? _.merge({}, allAttrs[$el.selector], renderingOnlyElAttrs)
+                : allAttrs[$el.selector];
+
+            this.positionRelative($el, bbox, elAttrs);
+            
+        }, this);
+
+        if (rotatable) {
+
+            rotatable.attr('transform', rotation || '');
+        }
+    },
+
+    positionRelative: function($el, bbox, elAttrs) {
+
+        var ref = elAttrs['ref'];
+        var refX = parseFloat(elAttrs['ref-x']);
+        var refY = parseFloat(elAttrs['ref-y']);
+        var refDx = parseFloat(elAttrs['ref-dx']);
+        var refDy = parseFloat(elAttrs['ref-dy']);
+        var yAlignment = elAttrs['y-alignment'];
+        var xAlignment = elAttrs['x-alignment'];
+        var refWidth = parseFloat(elAttrs['ref-width']);
+        var refHeight = parseFloat(elAttrs['ref-height']);
+
+        // `ref` is the selector of the reference element. If no `ref` is passed, reference
+        // element is the root element.
+
+        var isScalable = _.contains(_.pluck(_.pluck($el.parents('g'), 'className'), 'baseVal'), 'scalable');
+
+        if (ref) {
+
+            // Get the bounding box of the reference element relative to the root `<g>` element.
+            bbox = V(this.findBySelector(ref)[0]).bbox(false, this.el);
+        }
+
+        var vel = V($el[0]);
+
+        // Remove the previous translate() from the transform attribute and translate the element
+        // relative to the root bounding box following the `ref-x` and `ref-y` attributes.
+        if (vel.attr('transform')) {
+
+            vel.attr('transform', vel.attr('transform').replace(/translate\([^)]*\)/g, '') || '');
+        }
+
+        function isDefined(x) {
+            return _.isNumber(x) && !_.isNaN(x);
+        }
+
+        // The final translation of the subelement.
+        var tx = 0;
+        var ty = 0;
+
+        // 'ref-width'/'ref-height' defines the width/height of the subelement relatively to
+        // the reference element size
+        // val in 0..1         ref-width = 0.75 sets the width to 75% of the ref. el. width
+        // val < 0 || val > 1  ref-height = -20 sets the height to the the ref. el. height shorter by 20
+
+        if (isDefined(refWidth)) {
+
+            if (refWidth >= 0 && refWidth <= 1) {
+
+                vel.attr('width', refWidth * bbox.width);
+
+            } else {
+
+                vel.attr('width', Math.max(refWidth + bbox.width, 0));
+            }
+        }
+
+        if (isDefined(refHeight)) {
+
+            if (refHeight >= 0 && refHeight <= 1) {
+
+                vel.attr('height', refHeight * bbox.height);
+
+            } else {
+
+                vel.attr('height', Math.max(refHeight + bbox.height, 0));
+            }
+        }
+
+        // `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom
+        // coordinate of the reference element.
+        if (isDefined(refDx)) {
+
+            if (isScalable) {
+
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                tx = bbox.x + bbox.width + refDx / scale.sx;
+                
+            } else {
+                
+                tx = bbox.x + bbox.width + refDx;
+            }
+        }
+        if (isDefined(refDy)) {
+
+            if (isScalable) {
+                
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                ty = bbox.y + bbox.height + refDy / scale.sy;
+            } else {
+                
+                ty = bbox.y + bbox.height + refDy;
+            }
+        }
+
+        // if `refX` is in [0, 1] then `refX` is a fraction of bounding box width
+        // if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box
+        // otherwise, `refX` is the left coordinate of the bounding box
+        // Analogical rules apply for `refY`.
+        if (isDefined(refX)) {
+
+            if (refX > 0 && refX < 1) {
+
+                tx = bbox.x + bbox.width * refX;
+
+            } else if (isScalable) {
+
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                tx = bbox.x + refX / scale.sx;
+                
+            } else {
+
+                tx = bbox.x + refX;
+            }
+        }
+        if (isDefined(refY)) {
+
+            if (refY > 0 && refY < 1) {
+                
+                ty = bbox.y + bbox.height * refY;
+                
+            } else if (isScalable) {
+
+                // Compensate for the scale grid in case the elemnt is in the scalable group.
+                var scale = V(this.$('.scalable')[0]).scale();
+                ty = bbox.y + refY / scale.sy;
+                
+            } else {
+
+                ty = bbox.y + refY;
+            }
+        }
+
+       var velbbox = vel.bbox(false, this.paper.viewport);
+        // `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate.
+        if (yAlignment === 'middle') {
+
+            ty -= velbbox.height/2;
+            
+        } else if (isDefined(yAlignment)) {
+
+            ty += (yAlignment > -1 && yAlignment < 1) ?  velbbox.height * yAlignment : yAlignment;
+        }
+
+        // `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate.
+        if (xAlignment === 'middle') {
+            
+            tx -= velbbox.width/2;
+            
+        } else if (isDefined(xAlignment)) {
+
+            tx += (xAlignment > -1 && xAlignment < 1) ?  velbbox.width * xAlignment : xAlignment;
+        }
+
+        vel.translate(tx, ty);
+    },
+
+    // `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the
+    // default markup is not desirable.
+    renderMarkup: function() {
+        
+        var markup = this.model.markup || this.model.get('markup');
+        
+        if (markup) {
+
+            var nodes = V(markup);
+            V(this.el).append(nodes);
+            
+        } else {
+
+            throw new Error('properties.markup is missing while the default render() implementation is used.');
+        }
+    },
+
+    render: function() {
+
+        this.$el.empty();
+
+        this.renderMarkup();
+
+        this.update();
+
+        this.resize();
+        this.rotate();
+        this.translate();        
+
+        return this;
+    },
+
+    // Scale the whole `<g>` group. Note the difference between `scale()` and `resize()` here.
+    // `resize()` doesn't scale the whole `<g>` group but rather adjusts the `box.sx`/`box.sy` only.
+    // `update()` is then responsible for scaling only those elements that have the `follow-scale`
+    // attribute set to `true`. This is desirable in elements that have e.g. a `<text>` subelement
+    // that is not supposed to be scaled together with a surrounding `<rect>` element that IS supposed
+    // be be scaled.
+    scale: function(sx, sy) {
+
+        // TODO: take into account the origin coordinates `ox` and `oy`.
+        V(this.el).scale(sx, sy);
+    },
+
+    resize: function() {
+
+        var size = this.model.get('size') || { width: 1, height: 1 };
+        var angle = this.model.get('angle') || 0;
+        
+        var scalable = V(this.$('.scalable')[0]);
+        if (!scalable) {
+            // If there is no scalable elements, than there is nothing to resize.
+            return;
+        }
+        var scalableBbox = scalable.bbox(true);
+        
+        scalable.attr('transform', 'scale(' + (size.width / scalableBbox.width) + ',' + (size.height / scalableBbox.height) + ')');
+
+        // Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height`
+        // Order of transformations is significant but we want to reconstruct the object always in the order:
+        // resize(), rotate(), translate() no matter of how the object was transformed. For that to work,
+        // we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the
+        // rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation
+        // around the center of the resized object (which is a different origin then the origin of the previous rotation)
+        // and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was.
+        
+        // Cancel the rotation but now around a different origin, which is the center of the scaled object.
+        var rotatable = V(this.$('.rotatable')[0]);
+        var rotation = rotatable && rotatable.attr('transform');
+        if (rotation && rotation !== 'null') {
+
+            rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width/2) + ',' + (size.height/2) + ')');
+            var rotatableBbox = scalable.bbox(false, this.paper.viewport);
+            
+            // Store new x, y and perform rotate() again against the new rotation origin.
+            this.model.set('position', { x: rotatableBbox.x, y: rotatableBbox.y });
+            this.rotate();
+        }
+
+        // Update must always be called on non-rotated element. Otherwise, relative positioning
+        // would work with wrong (rotated) bounding boxes.
+        this.update();
+    },
+
+    translate: function(model, changes, opt) {
+
+        var position = this.model.get('position') || { x: 0, y: 0 };
+
+        V(this.el).attr('transform', 'translate(' + position.x + ',' + position.y + ')');
+    },
+
+    rotate: function() {
+
+        var rotatable = V(this.$('.rotatable')[0]);
+        if (!rotatable) {
+            // If there is no rotatable elements, then there is nothing to rotate.
+            return;
+        }
+        
+        var angle = this.model.get('angle') || 0;
+        var size = this.model.get('size') || { width: 1, height: 1 };
+
+        var ox = size.width/2;
+        var oy = size.height/2;
+        
+
+        rotatable.attr('transform', 'rotate(' + angle + ',' + ox + ',' + oy + ')');
+    },
+
+    // Interaction. The controller part.
+    // ---------------------------------
+
+    
+    pointerdown: function(evt, x, y) {
+
+        if ( // target is a valid magnet start linking
+            evt.target.getAttribute('magnet') &&
+            this.paper.options.validateMagnet.call(this.paper, this, evt.target)
+        ) {
+                this.model.trigger('batch:start');
+
+                var link = this.paper.getDefaultLink(this, evt.target);
+                link.set({
+                    source: {
+                        id: this.model.id,
+                        selector: this.getSelector(evt.target),
+                        port: $(evt.target).attr('port')
+                    },
+                    target: { x: x, y: y }
+                });
+
+                this.paper.model.addCell(link);
+
+               this._linkView = this.paper.findViewByModel(link);
+                this._linkView.startArrowheadMove('target');
+
+        } else {
+
+            this._dx = x;
+            this._dy = y;
+
+            joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
+        }
+    },
+
+    pointermove: function(evt, x, y) {
+
+        if (this._linkView) {
+
+            // let the linkview deal with this event
+            this._linkView.pointermove(evt, x, y);
+
+        } else {
+
+           var grid = this.paper.options.gridSize;
+
+            if (this.options.interactive !== false) {
+
+               var position = this.model.get('position');
+
+               // Make sure the new element's position always snaps to the current grid after
+               // translate as the previous one could be calculated with a different grid size.
+               this.model.translate(
+                   g.snapToGrid(position.x, grid) - position.x + g.snapToGrid(x - this._dx, grid),
+                   g.snapToGrid(position.y, grid) - position.y + g.snapToGrid(y - this._dy, grid)
+               );
+            }
+
+            this._dx = g.snapToGrid(x, grid);
+            this._dy = g.snapToGrid(y, grid);
+
+            joint.dia.CellView.prototype.pointermove.apply(this, arguments);
+        }
+    },
+
+    pointerup: function(evt, x, y) {
+
+        if (this._linkView) {
+
+            // let the linkview deal with this event
+            this._linkView.pointerup(evt, x, y);
+
+            delete this._linkView;
+
+            this.model.trigger('batch:stop');
+
+        } else {
+
+            joint.dia.CellView.prototype.pointerup.apply(this, arguments);
+        }
+    }
+
+});
+
+if (typeof exports === 'object') {
+
+    module.exports.Element = joint.dia.Element;
+    module.exports.ElementView = joint.dia.ElementView;
+}
+
+//      JointJS diagramming library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        dia: {
+            Cell: require('./joint.dia.cell').Cell,
+            CellView: require('./joint.dia.cell').CellView
+        }
+    };
+    var Backbone = require('backbone');
+    var _ = require('lodash');
+    var g = require('./geometry');
+}
+
+
+
+// joint.dia.Link base model.
+// --------------------------
+joint.dia.Link = joint.dia.Cell.extend({
+
+    // The default markup for links.
+    markup: [
+        '<path class="connection" stroke="black"/>',
+        '<path class="marker-source" fill="black" stroke="black" />',
+        '<path class="marker-target" fill="black" stroke="black" />',
+        '<path class="connection-wrap"/>',
+        '<g class="labels"/>',
+        '<g class="marker-vertices"/>',
+        '<g class="marker-arrowheads"/>',
+        '<g class="link-tools"/>'
+    ].join(''),
+
+    labelMarkup: [
+        '<g class="label">',
+        '<rect />',
+        '<text />',
+        '</g>'
+    ].join(''),
+
+    toolMarkup: [
+        '<g class="link-tool">',
+        '<g class="tool-remove" event="remove">',
+        '<circle r="11" />',
+        '<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>',
+        '<title>Remove link.</title>',
+        '</g>',
+        '<g class="tool-options" event="link:options">',
+        '<circle r="11" transform="translate(25)"/>',
+        '<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>',
+        '<title>Link options.</title>',
+        '</g>',
+        '</g>'
+    ].join(''),
+
+    // The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`).
+    // Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for
+    // dragging vertices (changin their position). The latter is used for removing vertices.
+    vertexMarkup: [
+        '<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">',
+        '<circle class="marker-vertex" idx="<%= idx %>" r="10" />',
+        '<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>',
+        '<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',
+        '<title>Remove vertex.</title>',
+        '</path>',
+        '</g>'
+    ].join(''),
+
+    arrowheadMarkup: [
+        '<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">',
+        '<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />',
+        '</g>'
+    ].join(''),
+
+    defaults: {
+
+        type: 'link'
+    },
+
+    disconnect: function() {
+
+        return this.set({ source: g.point(0, 0), target: g.point(0, 0) });
+    },
+
+    // A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter.
+    label: function(idx, value) {
+
+        idx = idx || 0;
+        
+        var labels = this.get('labels') || [];
+        
+        // Is it a getter?
+        if (arguments.length === 0 || arguments.length === 1) {
+            
+            return labels[idx];
+        }
+
+        var newValue = _.merge({}, labels[idx], value);
+
+        var newLabels = labels.slice();
+        newLabels[idx] = newValue;
+        
+        return this.set({ labels: newLabels });
+    }
+});
+
+
+// joint.dia.Link base view and controller.
+// ----------------------------------------
+
+joint.dia.LinkView = joint.dia.CellView.extend({
+
+    className: function() {
+        return _.unique(this.model.get('type').split('.').concat('link')).join(' ');
+    },
+
+    options: {
+
+        shortLinkLength: 100
+    },
+    
+    initialize: function() {
+
+        joint.dia.CellView.prototype.initialize.apply(this, arguments);
+
+        // create methods in prototype, so they can be accessed from any instance and
+        // don't need to be create over and over
+        if (typeof this.constructor.prototype.watchSource !== 'function') {
+            this.constructor.prototype.watchSource = this._createWatcher('source');
+            this.constructor.prototype.watchTarget = this._createWatcher('target');
+        }
+
+        // `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to
+        // `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the
+        // nodes in `updateLabelPosition()` in order to update the label positions.
+        this._labelCache = {};
+
+        // keeps markers bboxes and positions again for quicker access
+        this._markerCache = {};
+
+        // bind events
+        this.startListening();
+    },
+
+    startListening: function() {
+
+       this.listenTo(this.model, 'change:markup', this.render);
+       this.listenTo(this.model, 'change:smooth change:manhattan change:router change:connector', this.update);
+        this.listenTo(this.model, 'change:toolMarkup', function() {
+            this.renderTools().updateToolsPosition();
+        });
+       this.listenTo(this.model, 'change:labels change:labelMarkup', function() {
+            this.renderLabels().updateLabelPositions();
+        });
+        this.listenTo(this.model, 'change:vertices change:vertexMarkup', function() {
+            this.renderVertexMarkers().update();
+        });
+       this.listenTo(this.model, 'change:source', function(cell, source) {
+            this.watchSource(cell, source).update();
+        });
+       this.listenTo(this.model, 'change:target', function(cell, target) {
+            this.watchTarget(cell, target).update();
+        });
+    },
+
+    // Rendering
+    //----------
+
+    render: function() {
+
+       this.$el.empty();
+
+        // A special markup can be given in the `properties.markup` property. This might be handy
+        // if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s.
+        // `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors
+        // of elements with special meaning though. Therefore, those classes should be preserved in any
+        // special markup passed in `properties.markup`.
+        var children = V(this.model.get('markup') || this.model.markup);
+
+        // custom markup may contain only one children
+        if (!_.isArray(children)) children = [children];
+
+        // Cache all children elements for quicker access.
+        this._V = {}; // vectorized markup;
+        _.each(children, function(child) {
+            var c = child.attr('class');
+            c && (this._V[$.camelCase(c)] = child);
+        }, this);
+
+        // Only the connection path is mandatory
+        if (!this._V.connection) throw new Error('link: no connection path in the markup');
+
+        // partial rendering
+        this.renderTools();
+        this.renderVertexMarkers();
+        this.renderArrowheadMarkers();
+
+        V(this.el).append(children);
+
+        // rendering labels has to be run after the link is appended to DOM tree. (otherwise <Text> bbox
+        // returns zero values)
+        this.renderLabels();
+
+        // start watching the ends of the link for changes
+        this.watchSource(this.model, this.model.get('source'))
+            .watchTarget(this.model, this.model.get('target'))
+            .update();
+
+        return this;
+    },
+
+    renderLabels: function() {
+
+        if (!this._V.labels) return this;
+
+        this._labelCache = {};
+        var $labels = $(this._V.labels.node).empty();
+
+        var labels = this.model.get('labels') || [];
+        if (!labels.length) return this;
+        
+        var labelTemplate = _.template(this.model.get('labelMarkup') || this.model.labelMarkup);
+        // This is a prepared instance of a vectorized SVGDOM node for the label element resulting from
+        // compilation of the labelTemplate. The purpose is that all labels will just `clone()` this
+        // node to create a duplicate.
+        var labelNodeInstance = V(labelTemplate());
+
+        _.each(labels, function(label, idx) {
+
+            var labelNode = labelNodeInstance.clone().node;
+            // Cache label nodes so that the `updateLabels()` can just update the label node positions.
+            this._labelCache[idx] = V(labelNode);
+
+            var $text = $(labelNode).find('text');
+            var $rect = $(labelNode).find('rect');
+
+            // Text attributes with the default `text-anchor` and font-size set.
+            var textAttributes = _.extend({ 'text-anchor': 'middle', 'font-size': 14 }, joint.util.getByPath(label, 'attrs/text', '/'));
+            
+            $text.attr(_.omit(textAttributes, 'text'));
+                
+            if (!_.isUndefined(textAttributes.text)) {
+
+                V($text[0]).text(textAttributes.text + '');
+            }
+
+            // Note that we first need to append the `<text>` element to the DOM in order to
+            // get its bounding box.
+            $labels.append(labelNode);
+
+            // `y-alignment` - center the text element around its y coordinate.
+            var textBbox = V($text[0]).bbox(true, $labels[0]);
+            V($text[0]).translate(0, -textBbox.height/2);
+
+            // Add default values.
+            var rectAttributes = _.extend({
+
+                fill: 'white',
+                rx: 3,
+                ry: 3
+                
+            }, joint.util.getByPath(label, 'attrs/rect', '/'));
+            
+            $rect.attr(_.extend(rectAttributes, {
+
+                x: textBbox.x,
+                y: textBbox.y - textBbox.height/2,  // Take into account the y-alignment translation.
+                width: textBbox.width,
+                height: textBbox.height
+            }));
+            
+        }, this);
+
+        return this;
+    },
+
+    renderTools: function() {
+
+        if (!this._V.linkTools) return this;
+
+        // Tools are a group of clickable elements that manipulate the whole link.
+        // A good example of this is the remove tool that removes the whole link.
+        // Tools appear after hovering the link close to the `source` element/point of the link
+        // but are offset a bit so that they don't cover the `marker-arrowhead`.
+
+        var $tools = $(this._V.linkTools.node).empty();
+        var toolTemplate = _.template(this.model.get('toolMarkup') || this.model.toolMarkup);
+        var tool = V(toolTemplate());
+
+        $tools.append(tool.node);
+        
+        // Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly.
+        this._toolCache = tool;
+
+        return this;
+    },
+
+    renderVertexMarkers: function() {
+
+        if (!this._V.markerVertices) return this;
+
+        var $markerVertices = $(this._V.markerVertices.node).empty();
+
+        // A special markup can be given in the `properties.vertexMarkup` property. This might be handy
+        // if default styling (elements) are not desired. This makes it possible to use any
+        // SVG elements for .marker-vertex and .marker-vertex-remove tools.
+        var markupTemplate = _.template(this.model.get('vertexMarkup') || this.model.vertexMarkup);
+        
+        _.each(this.model.get('vertices'), function(vertex, idx) {
+
+            $markerVertices.append(V(markupTemplate(_.extend({ idx: idx }, vertex))).node);
+        });
+        
+        return this;
+    },
+
+    renderArrowheadMarkers: function() {
+
+        // Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case.
+        if (!this._V.markerArrowheads) return this;
+
+        var $markerArrowheads = $(this._V.markerArrowheads.node);
+
+        $markerArrowheads.empty();
+
+        // A special markup can be given in the `properties.vertexMarkup` property. This might be handy
+        // if default styling (elements) are not desired. This makes it possible to use any
+        // SVG elements for .marker-vertex and .marker-vertex-remove tools.
+        var markupTemplate = _.template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup);
+
+        this._V.sourceArrowhead = V(markupTemplate({ end: 'source' }));
+        this._V.targetArrowhead = V(markupTemplate({ end: 'target' }));
+
+        $markerArrowheads.append(this._V.sourceArrowhead.node, this._V.targetArrowhead.node);
+
+        return this;
+    },
+
+    // Updating
+    //---------
+
+    // Default is to process the `attrs` object and set attributes on subelements based on the selectors.
+    update: function() {
+
+        // Update attributes.
+        _.each(this.model.get('attrs'), function(attrs, selector) {
+            
+            // If the `filter` attribute is an object, it is in the special JointJS filter format and so
+            // it becomes a special attribute and is treated separately.
+            if (_.isObject(attrs.filter)) {
+                
+                this.findBySelector(selector).attr(_.omit(attrs, 'filter'));
+                this.applyFilter(selector, attrs.filter);
+                
+            } else {
+                
+                this.findBySelector(selector).attr(attrs);
+            }
+        }, this);
+
+        // Path finding
+        var vertices = this.route = this.findRoute(this.model.get('vertices') || []);
+
+        // finds all the connection points taking new vertices into account
+        this._findConnectionPoints(vertices);
+
+        var pathData = this.getPathData(vertices);
+
+        // The markup needs to contain a `.connection`
+        this._V.connection.attr('d', pathData);
+        this._V.connectionWrap && this._V.connectionWrap.attr('d', pathData);
+
+        this._translateAndAutoOrientArrows(this._V.markerSource, this._V.markerTarget);
+
+        //partials updates
+        this.updateLabelPositions();
+        this.updateToolsPosition();
+        this.updateArrowheadMarkers();
+
+        delete this.options.perpendicular;
+
+        return this;
+    },
+
+    _findConnectionPoints: function(vertices) {
+
+        // cache source and target points
+        var sourcePoint, targetPoint, sourceMarkerPoint, targetMarkerPoint;
+
+        var firstVertex = _.first(vertices);
+
+        sourcePoint = this.getConnectionPoint(
+            'source', this.model.get('source'), firstVertex || this.model.get('target')
+        ).round();
+
+        var lastVertex = _.last(vertices);
+
+        targetPoint = this.getConnectionPoint(
+            'target', this.model.get('target'), lastVertex || sourcePoint
+        ).round();
+
+        // Move the source point by the width of the marker taking into account
+        // its scale around x-axis. Note that scale is the only transform that
+        // makes sense to be set in `.marker-source` attributes object
+        // as all other transforms (translate/rotate) will be replaced
+        // by the `translateAndAutoOrient()` function.
+        var cache = this._markerCache;
+
+        if (this._V.markerSource) {
+
+            cache.sourceBBox = cache.sourceBBox || this._V.markerSource.bbox(true);
+
+            sourceMarkerPoint = g.point(sourcePoint).move(
+                firstVertex || targetPoint,
+                cache.sourceBBox.width * this._V.markerSource.scale().sx * -1
+            ).round();
+        }
+
+        if (this._V.markerTarget) {
+
+            cache.targetBBox = cache.targetBBox || this._V.markerTarget.bbox(true);
+
+            targetMarkerPoint = g.point(targetPoint).move(
+                lastVertex || sourcePoint,
+                cache.targetBBox.width * this._V.markerTarget.scale().sx * -1
+            ).round();
+        }
+
+        // if there was no markup for the marker, use the connection point.
+        cache.sourcePoint = sourceMarkerPoint || sourcePoint;
+        cache.targetPoint = targetMarkerPoint || targetPoint;
+
+        // make connection points public
+        this.sourcePoint = sourcePoint;
+        this.targetPoint = targetPoint;
+    },
+
+    updateLabelPositions: function() {
+
+        if (!this._V.labels) return this;
+
+        // This method assumes all the label nodes are stored in the `this._labelCache` hash table
+        // by their indexes in the `this.get('labels')` array. This is done in the `renderLabels()` method.
+
+        var labels = this.model.get('labels') || [];
+        if (!labels.length) return this;
+
+        var connectionElement = this._V.connection.node;
+        var connectionLength = connectionElement.getTotalLength();
+
+        _.each(labels, function(label, idx) {
+
+            var position = label.position;
+            position = (position > connectionLength) ? connectionLength : position; // sanity check
+            position = (position < 0) ? connectionLength + position : position;
+            position = position > 1 ? position : connectionLength * position;
+
+            var labelCoordinates = connectionElement.getPointAtLength(position);
+
+            this._labelCache[idx].attr('transform', 'translate(' + labelCoordinates.x + ', ' + labelCoordinates.y + ')');
+
+        }, this);
+
+        return this;
+    },
+
+
+    updateToolsPosition: function() {
+
+        if (!this._V.linkTools) return this;
+
+        // Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker.
+        // Note that the offset is hardcoded here. The offset should be always
+        // more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking
+        // this up all the time would be slow.
+
+        var scale = '';
+        var offset = 40;
+
+        // If the link is too short, make the tools half the size and the offset twice as low.
+        if (this.getConnectionLength() < this.options.shortLinkLength) {
+            scale = 'scale(.5)';
+            offset /= 2;
+        }
+
+        var toolPosition = this.getPointAtLength(offset);
+        
+        this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale);
+
+        return this;
+    },
+
+
+    updateArrowheadMarkers: function() {
+
+        if (!this._V.markerArrowheads) return this;
+
+        // getting bbox of an element with `display="none"` in IE9 ends up with access violation
+        if ($.css(this._V.markerArrowheads.node, 'display') === 'none') return this;
+
+        var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1;
+        this._V.sourceArrowhead.scale(sx);
+        this._V.targetArrowhead.scale(sx);
+
+        this._translateAndAutoOrientArrows(this._V.sourceArrowhead, this._V.targetArrowhead);
+
+        return this;
+    },
+
+    // Returns a function observing changes on an end of the link. If a change happens and new end is a new model,
+    // it stops listening on the previous one and starts listening to the new one.
+    _createWatcher: function(endType) {
+
+        function watchEnd(link, end) {
+
+            end = end || {};
+
+            var previousEnd = link.previous(endType) || {};
+
+            // Pick updateMethod this._sourceBboxUpdate or this._targetBboxUpdate.
+            var updateEndFunction = this['_' + endType + 'BBoxUpdate'];
+
+            if (this._isModel(previousEnd)) {
+                this.stopListening(this.paper.getModelById(previousEnd.id), 'change', updateEndFunction);
+            }
+
+            if (this._isModel(end)) {
+                // If the observed model changes, it caches a new bbox and do the link update.
+                this.listenTo(this.paper.getModelById(end.id), 'change', updateEndFunction);
+            }
+
+            _.bind(updateEndFunction, this)({ cacheOnly: true });
+
+            return this;
+        }
+
+        return watchEnd;
+    },
+
+    // It's important to keep both methods (sourceBboxUpdate and targetBboxUpdate) as unique methods
+    // because of loop links. We have to be able to determine, which method we want to stop listen to.
+    // ListenTo(model, event, handler) as model and event will be identical.
+    _sourceBBoxUpdate: function(update) {
+
+        // keep track which end had been changed very last
+        this.lastEndChange = 'source';
+
+        update = update || {};
+        var end = this.model.get('source');
+
+        if (this._isModel(end)) {
+
+            var selector = this._makeSelector(end);
+            var view = this.paper.findViewByModel(end.id);
+            var magnetElement = this.paper.viewport.querySelector(selector);
+
+            this.sourceBBox = view.getStrokeBBox(magnetElement);
+
+        } else {
+            // the link end is a point ~ rect 1x1
+            this.sourceBBox = g.rect(end.x, end.y, 1, 1);
+        }
+
+        if (!update.cacheOnly) this.update();
+    },
+
+    _targetBBoxUpdate: function(update) {
+
+        // keep track which end had been changed very last
+        this.lastEndChange = 'target';
+
+        update = update || {};
+        var end = this.model.get('target');
+
+        if (this._isModel(end)) {
+
+            var selector = this._makeSelector(end);
+            var view = this.paper.findViewByModel(end.id);
+            var magnetElement = this.paper.viewport.querySelector(selector);
+
+            this.targetBBox = view.getStrokeBBox(magnetElement);
+
+        } else {
+            // the link end is a point ~ rect 1x1
+            this.targetBBox = g.rect(end.x, end.y, 1, 1);
+        }
+
+        if (!update.cacheOnly) this.update();
+    },
+
+    _translateAndAutoOrientArrows: function(sourceArrow, targetArrow) {
+
+        // Make the markers "point" to their sticky points being auto-oriented towards
+        // `targetPosition`/`sourcePosition`. And do so only if there is a markup for them.
+        if (sourceArrow) {
+            sourceArrow.translateAndAutoOrient(
+                this.sourcePoint,
+                _.first(this.route) || this.targetPoint,
+                this.paper.viewport
+            );
+        }
+
+        if (targetArrow) {
+            targetArrow.translateAndAutoOrient(
+                this.targetPoint,
+                _.last(this.route) || this.sourcePoint,
+                this.paper.viewport
+            );
+        }
+    },
+
+    removeVertex: function(idx) {
+
+        var vertices = _.clone(this.model.get('vertices'));
+        
+        if (vertices && vertices.length) {
+
+            vertices.splice(idx, 1);
+            this.model.set('vertices', vertices);
+        }
+
+        return this;
+    },
+
+    // This method ads a new vertex to the `vertices` array of `.connection`. This method
+    // uses a heuristic to find the index at which the new `vertex` should be placed at assuming
+    // the new vertex is somewhere on the path.
+    addVertex: function(vertex) {
+
+        this.model.set('attrs', this.model.get('attrs') || {});
+        var attrs = this.model.get('attrs');
+        
+        // As it is very hard to find a correct index of the newly created vertex,
+        // a little heuristics is taking place here.
+        // The heuristics checks if length of the newly created
+        // path is lot more than length of the old path. If this is the case,
+        // new vertex was probably put into a wrong index.
+        // Try to put it into another index and repeat the heuristics again.
+
+        var vertices = (this.model.get('vertices') || []).slice();
+        // Store the original vertices for a later revert if needed.
+        var originalVertices = vertices.slice();
+
+        // A `<path>` element used to compute the length of the path during heuristics.
+        var path = this._V.connection.node.cloneNode(false);
+        
+        // Length of the original path.        
+        var originalPathLength = path.getTotalLength();
+        // Current path length.
+        var pathLength;
+        // Tolerance determines the highest possible difference between the length
+        // of the old and new path. The number has been chosen heuristically.
+        var pathLengthTolerance = 20;
+        // Total number of vertices including source and target points.
+        var idx = vertices.length + 1;
+
+        // Loop through all possible indexes and check if the difference between
+        // path lengths changes significantly. If not, the found index is
+        // most probably the right one.
+        while (idx--) {
+
+            vertices.splice(idx, 0, vertex);
+            V(path).attr('d', this.getPathData(this.findRoute(vertices)));
+
+            pathLength = path.getTotalLength();
+
+            // Check if the path lengths changed significantly.
+            if (pathLength - originalPathLength > pathLengthTolerance) {
+
+                // Revert vertices to the original array. The path length has changed too much
+                // so that the index was not found yet.
+                vertices = originalVertices.slice();
+                
+            } else {
+
+                break;
+            }
+        }
+
+        this.model.set('vertices', vertices);
+
+        // In manhattan routing, if there are no vertices, the path length changes significantly
+        // with the first vertex added. Shall we check vertices.length === 0? at beginning of addVertex()
+        // in order to avoid the temporary path construction and other operations?
+        return Math.max(idx, 0);
+    },
+
+
+    findRoute: function(oldVertices) {
+
+        var router = this.model.get('router');
+
+        if (!router) {
+
+            if (this.model.get('manhattan')) {
+                // backwards compability
+                router = { name: 'orthogonal' };
+            } else {
+
+                return oldVertices;
+            }
+        }
+
+        var fn = joint.routers[router.name];
+
+        if (!_.isFunction(fn)) {
+
+            throw 'unknown router: ' + router.name;
+        }
+
+        var newVertices = fn.call(this, oldVertices || [], router.args || {}, this);
+
+        return newVertices;
+    },
+
+    // Return the `d` attribute value of the `<path>` element representing the link
+    // between `source` and `target`.
+    getPathData: function(vertices) {
+
+        var connector = this.model.get('connector');
+
+        if (!connector) {
+
+            // backwards compability
+            connector = this.model.get('smooth') ? { name: 'smooth' } : { name: 'normal' };
+        }
+
+        if (!_.isFunction(joint.connectors[connector.name])) {
+
+            throw 'unknown connector: ' + connector.name;
+        }
+
+        var pathData = joint.connectors[connector.name].call(
+            this,
+            this._markerCache.sourcePoint, // Note that the value is translated by the size
+            this._markerCache.targetPoint, // of the marker. (We'r not using this.sourcePoint)
+            vertices || (this.model.get('vertices') || {}),
+            connector.args || {}, // options
+            this
+        );
+
+        return pathData;
+    },
+
+    // Find a point that is the start of the connection.
+    // If `selectorOrPoint` is a point, then we're done and that point is the start of the connection.
+    // If the `selectorOrPoint` is an element however, we need to know a reference point (or element)
+    // that the link leads to in order to determine the start of the connection on the original element.
+    getConnectionPoint: function(end, selectorOrPoint, referenceSelectorOrPoint) {
+
+        var spot;
+
+        if (this._isPoint(selectorOrPoint)) {
+
+            // If the source is a point, we don't need a reference point to find the sticky point of connection.
+            spot = g.point(selectorOrPoint);
+
+        } else {
+
+            // If the source is an element, we need to find a point on the element boundary that is closest
+            // to the reference point (or reference element).
+            // Get the bounding box of the spot relative to the paper viewport. This is necessary
+            // in order to follow paper viewport transformations (scale/rotate).
+            // `_sourceBbox` (`_targetBbox`) comes from `_sourceBboxUpdate` (`_sourceBboxUpdate`)
+            // method, it exists since first render and are automatically updated
+            var spotBbox = end === 'source' ? this.sourceBBox : this.targetBBox;
+            
+            var reference;
+            
+            if (this._isPoint(referenceSelectorOrPoint)) {
+
+                // Reference was passed as a point, therefore, we're ready to find the sticky point of connection on the source element.
+                reference = g.point(referenceSelectorOrPoint);
+
+            } else {
+
+                // Reference was passed as an element, therefore we need to find a point on the reference
+                // element boundary closest to the source element.
+                // Get the bounding box of the spot relative to the paper viewport. This is necessary
+                // in order to follow paper viewport transformations (scale/rotate).
+                var referenceBbox = end === 'source' ? this.targetBBox : this.sourceBBox;
+
+                reference = g.rect(referenceBbox).intersectionWithLineFromCenterToPoint(g.rect(spotBbox).center());
+                reference = reference || g.rect(referenceBbox).center();
+            }
+
+            // If `perpendicularLinks` flag is set on the paper and there are vertices
+            // on the link, then try to find a connection point that makes the link perpendicular
+            // even though the link won't point to the center of the targeted object.
+            if (this.paper.options.perpendicularLinks || this.options.perpendicular) {
+
+                var horizontalLineRect = g.rect(0, reference.y, this.paper.options.width, 1);
+                var verticalLineRect = g.rect(reference.x, 0, 1, this.paper.options.height);
+                var nearestSide;
+
+                if (horizontalLineRect.intersect(g.rect(spotBbox))) {
+
+                    nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
+                    switch (nearestSide) {
+                      case 'left':
+                        spot = g.point(spotBbox.x, reference.y);
+                        break;
+                      case 'right':
+                        spot = g.point(spotBbox.x + spotBbox.width, reference.y);
+                        break;
+                    default:
+                        spot = g.rect(spotBbox).center();
+                        break;
+                    }
+                    
+                } else if (verticalLineRect.intersect(g.rect(spotBbox))) {
+
+                    nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
+                    switch (nearestSide) {
+                      case 'top':
+                        spot = g.point(reference.x, spotBbox.y);
+                        break;
+                      case 'bottom':
+                        spot = g.point(reference.x, spotBbox.y + spotBbox.height);
+                        break;
+                    default:
+                        spot = g.rect(spotBbox).center();
+                        break;
+                    }
+                    
+                } else {
+
+                    // If there is no intersection horizontally or vertically with the object bounding box,
+                    // then we fall back to the regular situation finding straight line (not perpendicular)
+                    // between the object and the reference point.
+
+                    spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
+                    spot = spot || g.rect(spotBbox).center();
+                }
+                
+            } else {
+            
+                spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
+                spot = spot || g.rect(spotBbox).center();
+            }
+        }
+
+        return spot;
+    },
+
+    _isModel: function(end) {
+
+        return end && end.id;
+    },
+
+    _isPoint: function(end) {
+
+        return !this._isModel(end);
+    },
+
+    _makeSelector: function(end) {
+
+        var selector = '[model-id="' + end.id + '"]';
+        // `port` has a higher precendence over `selector`. This is because the selector to the magnet
+        // might change while the name of the port can stay the same.
+        if (end.port) {
+            selector += ' [port="' + end.port + '"]';
+        } else if (end.selector) {
+            selector += ' ' + end.selector;
+        }
+
+        return selector;
+    },
+
+    // Public API
+    // ----------
+
+    getConnectionLength: function() {
+
+        return this._V.connection.node.getTotalLength();
+    },
+
+    getPointAtLength: function(length) {
+
+        return this._V.connection.node.getPointAtLength(length);
+    },
+
+    // Interaction. The controller part.
+    // ---------------------------------
+
+    _beforeArrowheadMove: function() {
+
+        this.model.trigger('batch:start');
+
+        this._z = this.model.get('z');
+        this.model.set('z', Number.MAX_VALUE);
+
+        // Let the pointer propagate throught the link view elements so that
+        // the `evt.target` is another element under the pointer, not the link itself.
+        this.el.style.pointerEvents = 'none';
+    },
+
+    _afterArrowheadMove: function() {
+
+        if (this._z) {
+            this.model.set('z', this._z);
+            delete this._z;
+        }
+
+        // Put `pointer-events` back to its original value. See `startArrowheadMove()` for explanation.
+       // Value `auto` doesn't work in IE9. We force to use `visiblePainted` instead.
+       // See `https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events`.
+        this.el.style.pointerEvents = 'visiblePainted';
+
+        this.model.trigger('batch:stop');
+    },
+
+    _createValidateConnectionArgs: function(arrowhead) {
+        // It makes sure the arguments for validateConnection have the following form:
+        // (source view, source magnet, target view, target magnet and link view)
+        var args = [];
+
+        args[4] = arrowhead;
+        args[5] = this;
+
+        var oppositeArrowhead, i = 0, j = 0;
+
+        if (arrowhead === 'source') {
+            i = 2;
+            oppositeArrowhead = 'target';
+        } else {
+            j = 2;
+            oppositeArrowhead = 'source';
+        }
+
+        var end = this.model.get(oppositeArrowhead);
+
+        if (end.id) {
+            args[i] = this.paper.findViewByModel(end.id);
+            args[i+1] = end.selector && args[i].el.querySelector(end.selector);
+        }
+
+        function validateConnectionArgs(cellView, magnet) {
+            args[j] = cellView;
+            args[j+1] = cellView.el === magnet ? undefined : magnet;
+            return args;
+        }
+
+        return validateConnectionArgs;
+    },
+
+    startArrowheadMove: function(end) {
+        // Allow to delegate events from an another view to this linkView in order to trigger arrowhead
+        // move without need to click on the actual arrowhead dom element.
+        this._action = 'arrowhead-move';
+        this._arrowhead = end;
+        this._beforeArrowheadMove();
+        this._validateConnectionArgs = this._createValidateConnectionArgs(this._arrowhead);
+    },
+
+    pointerdown: function(evt, x, y) {
+
+        joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
+
+       this._dx = x;
+        this._dy = y;
+
+        if (this.options.interactive === false) return;
+
+        var className = evt.target.getAttribute('class');
+
+        switch (className) {
+
+        case 'marker-vertex':
+            this._action = 'vertex-move';
+            this._vertexIdx = evt.target.getAttribute('idx');
+            break;
+
+        case 'marker-vertex-remove':
+        case 'marker-vertex-remove-area':
+            this.removeVertex(evt.target.getAttribute('idx'));
+            break;
+
+        case 'marker-arrowhead':
+            this.startArrowheadMove(evt.target.getAttribute('end'));
+            break;
+
+        default:
+
+            var targetParentEvent = evt.target.parentNode.getAttribute('event');
+
+            if (targetParentEvent) {
+
+                // `remove` event is built-in. Other custom events are triggered on the paper.
+                if (targetParentEvent === 'remove') {
+                    this.model.remove();
+                } else {
+                    this.paper.trigger(targetParentEvent, evt, this, x, y);
+                }
+
+            } else {
+
+                // Store the index at which the new vertex has just been placed.
+                // We'll be update the very same vertex position in `pointermove()`.
+                this._vertexIdx = this.addVertex({ x: x, y: y });
+                this._action = 'vertex-move';
+            }
+        }
+    },
+
+    pointermove: function(evt, x, y) {
+
+        joint.dia.CellView.prototype.pointermove.apply(this, arguments);
+
+        switch (this._action) {
+
+          case 'vertex-move':
+
+            var vertices = _.clone(this.model.get('vertices'));
+            vertices[this._vertexIdx] = { x: x, y: y };
+            this.model.set('vertices', vertices);
+            break;
+
+          case 'arrowhead-move':
+
+            if (this.paper.options.snapLinks) {
+
+                // checking view in close area of the pointer
+
+                var r = this.paper.options.snapLinks.radius || 50;
+                var viewsInArea = this.paper.findViewsInArea({ x: x - r, y: y - r, width: 2 * r, height: 2 * r });
+
+                this._closestView && this._closestView.unhighlight(this._closestEnd.selector);
+                this._closestView = this._closestEnd = null;
+
+                var pointer = g.point(x,y);
+                var distance, minDistance = Number.MAX_VALUE;
+
+                _.each(viewsInArea, function(view) {
+
+                    // skip connecting to the element in case '.': { magnet: false } attribute present
+                    if (view.el.getAttribute('magnet') !== 'false') {
+
+                        // find distance from the center of the model to pointer coordinates
+                        distance = view.model.getBBox().center().distance(pointer);
+
+                        // the connection is looked up in a circle area by `distance < r`
+                        if (distance < r && distance < minDistance) {
+
+                            if (this.paper.options.validateConnection.apply(
+                                this.paper, this._validateConnectionArgs(view, null)
+                            )) {
+                                minDistance = distance;
+                                this._closestView = view;
+                                this._closestEnd = { id: view.model.id };
+                            }
+                        }
+                    }
+
+                    view.$('[magnet]').each(_.bind(function(index, magnet) {
+
+                        var bbox = V(magnet).bbox(false, this.paper.viewport);
+
+                        distance = pointer.distance({
+                            x: bbox.x + bbox.width / 2,
+                            y: bbox.y + bbox.height / 2
+                        });
+
+                        if (distance < r && distance < minDistance) {
+
+                            if (this.paper.options.validateConnection.apply(
+                                this.paper, this._validateConnectionArgs(view, magnet)
+                            )) {
+                                minDistance = distance;
+                                this._closestView = view;
+                                this._closestEnd = {
+                                    id: view.model.id,
+                                    selector: view.getSelector(magnet),
+                                    port: magnet.getAttribute('port')
+                                };
+                            }
+                        }
+
+                    }, this));
+
+                }, this);
+
+                this._closestView && this._closestView.highlight(this._closestEnd.selector);
+
+                this.model.set(this._arrowhead, this._closestEnd || { x: x, y: y });
+
+            } else {
+
+                // checking views right under the pointer
+
+                // Touchmove event's target is not reflecting the element under the coordinates as mousemove does.
+                // It holds the element when a touchstart triggered.
+                var target = (evt.type === 'mousemove')
+                    ? evt.target
+                    : document.elementFromPoint(evt.clientX, evt.clientY);
+
+                if (this._targetEvent !== target) {
+                    // Unhighlight the previous view under pointer if there was one.
+                    this._magnetUnderPointer && this._viewUnderPointer.unhighlight(this._magnetUnderPointer);
+                    this._viewUnderPointer = this.paper.findView(target);
+                    if (this._viewUnderPointer) {
+                        // If we found a view that is under the pointer, we need to find the closest
+                        // magnet based on the real target element of the event.
+                        this._magnetUnderPointer = this._viewUnderPointer.findMagnet(target);
+
+                        if (this._magnetUnderPointer && this.paper.options.validateConnection.apply(
+                            this.paper,
+                            this._validateConnectionArgs(this._viewUnderPointer, this._magnetUnderPointer)
+                        )) {
+                            // If there was no magnet found, do not highlight anything and assume there
+                            // is no view under pointer we're interested in reconnecting to.
+                            // This can only happen if the overall element has the attribute `'.': { magnet: false }`.
+                            this._magnetUnderPointer && this._viewUnderPointer.highlight(this._magnetUnderPointer);
+                        } else {
+                            // This type of connection is not valid. Disregard this magnet.
+                            this._magnetUnderPointer = null;
+                        }
+                    } else {
+                        // Make sure we'll delete previous magnet
+                        this._magnetUnderPointer = null;
+                    }
+                }
+
+               this._targetEvent = target;
+
+                this.model.set(this._arrowhead, { x: x, y: y });
+            }
+
+            break;
+        }
+
+        this._dx = x;
+        this._dy = y;
+    },
+
+    pointerup: function(evt) {
+
+        joint.dia.CellView.prototype.pointerup.apply(this, arguments);
+
+        if (this._action === 'arrowhead-move') {
+
+            if (this.paper.options.snapLinks) {
+
+                this._closestView && this._closestView.unhighlight(this._closestEnd.selector);
+                this._closestView = this._closestEnd = null;
+
+            } else {
+
+                if (this._magnetUnderPointer) {
+                    this._viewUnderPointer.unhighlight(this._magnetUnderPointer);
+                    // Find a unique `selector` of the element under pointer that is a magnet. If the
+                    // `this._magnetUnderPointer` is the root element of the `this._viewUnderPointer` itself,
+                    // the returned `selector` will be `undefined`. That means we can directly pass it to the
+                    // `source`/`target` attribute of the link model below.
+                   this.model.set(this._arrowhead, {
+                        id: this._viewUnderPointer.model.id,
+                        selector: this._viewUnderPointer.getSelector(this._magnetUnderPointer),
+                        port: $(this._magnetUnderPointer).attr('port')
+                    });
+                }
+
+                delete this._viewUnderPointer;
+                delete this._magnetUnderPointer;
+                delete this._staticView;
+                delete this._staticMagnet;
+            }
+
+            this._afterArrowheadMove();
+        }
+
+        delete this._action;
+    }
+});
+
+
+if (typeof exports === 'object') {
+
+    module.exports.Link = joint.dia.Link;
+    module.exports.LinkView = joint.dia.LinkView;
+}
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+
+joint.dia.Paper = Backbone.View.extend({
+
+    options: {
+
+        width: 800,
+        height: 600,
+        gridSize: 50,
+        perpendicularLinks: false,
+        elementView: joint.dia.ElementView,
+        linkView: joint.dia.LinkView,
+        snapLinks: false, // false, true, { radius: value }
+
+        // Defines what link model is added to the graph after an user clicks on an active magnet.
+        // Value could be the Backbone.model or a function returning the Backbone.model
+        // defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() }
+        defaultLink: new joint.dia.Link,
+
+        // Check whether to add a new link to the graph when user clicks on an a magnet.
+        validateMagnet: function(cellView, magnet) {
+            return magnet.getAttribute('magnet') !== 'passive';
+        },
+
+        // Check whether to allow or disallow the link connection while an arrowhead end (source/target)
+        // being changed.
+        validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
+            return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView;
+        }
+    },
+
+    events: {
+
+        'mousedown': 'pointerdown',
+        'dblclick': 'mousedblclick',
+        'click': 'mouseclick',
+        'touchstart': 'pointerdown',
+        'mousemove': 'pointermove',
+        'touchmove': 'pointermove'
+    },
+
+    initialize: function() {
+
+        _.bindAll(this, 'addCell', 'sortCells', 'resetCells', 'pointerup');
+
+        this.svg = V('svg').node;
+        this.viewport = V('g').node;
+
+        // Append `<defs>` element to the SVG document. This is useful for filters and gradients.
+        V(this.svg).append(V('defs').node);
+
+        V(this.viewport).attr({ 'class': 'viewport' });
+        
+        V(this.svg).append(this.viewport);
+
+        this.$el.append(this.svg);
+
+        this.setDimensions();
+
+       this.listenTo(this.model, 'add', this.addCell);
+       this.listenTo(this.model, 'reset', this.resetCells);
+       this.listenTo(this.model, 'sort', this.sortCells);
+
+       $(document).on('mouseup touchend', this.pointerup);
+
+        // Hold the value when mouse has been moved: when mouse moved, no click event will be triggered.
+        this._mousemoved = false;
+    },
+
+    remove: function() {
+
+       $(document).off('mouseup touchend', this.pointerup);
+
+       Backbone.View.prototype.remove.call(this);
+    },
+
+    setDimensions: function(width, height) {
+
+        if (width) this.options.width = width;
+        if (height) this.options.height = height;
+        
+        V(this.svg).attr('width', this.options.width);
+        V(this.svg).attr('height', this.options.height);
+
+       this.trigger('resize');
+    },
+
+    // Expand/shrink the paper to fit the content. Snap the width/height to the grid
+    // defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper.
+    fitToContent: function(gridWidth, gridHeight, padding) {
+
+       gridWidth = gridWidth || 1;
+       gridHeight = gridHeight || 1;
+        padding = padding || 0;
+
+       // Calculate the paper size to accomodate all the graph's elements.
+       var bbox = V(this.viewport).bbox(true, this.svg);
+
+       var calcWidth = Math.ceil((bbox.width + bbox.x) / gridWidth) * gridWidth;
+       var calcHeight = Math.ceil((bbox.height + bbox.y) / gridHeight) * gridHeight;
+
+        calcWidth += padding;
+        calcHeight += padding;
+        
+       // Change the dimensions only if there is a size discrepency
+       if (calcWidth != this.options.width || calcHeight != this.options.height) {
+           this.setDimensions(calcWidth || this.options.width , calcHeight || this.options.height);
+       }
+    },
+
+    getContentBBox: function() {
+
+        var crect = this.viewport.getBoundingClientRect();
+
+        // Using Screen CTM was the only way to get the real viewport bounding box working in both
+        // Google Chrome and Firefox.
+        var ctm = this.viewport.getScreenCTM();
+
+        var bbox = g.rect(Math.abs(crect.left - ctm.e), Math.abs(crect.top - ctm.f), crect.width, crect.height);
+
+        return bbox;
+    },
+
+    createViewForModel: function(cell) {
+
+        var view;
+        
+        var type = cell.get('type');
+        var module = type.split('.')[0];
+        var entity = type.split('.')[1];
+
+        // If there is a special view defined for this model, use that one instead of the default `elementView`/`linkView`.
+        if (joint.shapes[module] && joint.shapes[module][entity + 'View']) {
+
+            view = new joint.shapes[module][entity + 'View']({ model: cell, interactive: this.options.interactive });
+            
+        } else if (cell instanceof joint.dia.Element) {
+                
+            view = new this.options.elementView({ model: cell, interactive: this.options.interactive });
+
+        } else {
+
+            view = new this.options.linkView({ model: cell, interactive: this.options.interactive });
+        }
+
+        return view;
+    },
+    
+    addCell: function(cell) {
+
+        var view = this.createViewForModel(cell);
+
+        V(this.viewport).append(view.el);
+        view.paper = this;
+        view.render();
+
+        // This is the only way to prevent image dragging in Firefox that works.
+        // Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help.
+        $(view.el).find('image').on('dragstart', function() { return false; });
+    },
+
+    resetCells: function(cellsCollection) {
+
+        $(this.viewport).empty();
+
+        var cells = cellsCollection.models.slice();
+
+        // Make sure links are always added AFTER elements.
+        // They wouldn't find their sources/targets in the DOM otherwise.
+        cells.sort(function(a, b) { return a instanceof joint.dia.Link ? 1 : -1; });
+        
+        _.each(cells, this.addCell, this);
+
+        // Sort the cells in the DOM manually as we might have changed the order they
+        // were added to the DOM (see above).
+        this.sortCells();
+    },
+
+    sortCells: function() {
+
+        // Run insertion sort algorithm in order to efficiently sort DOM elements according to their
+        // associated model `z` attribute.
+
+        var $cells = $(this.viewport).children('[model-id]');
+        var cells = this.model.get('cells');
+
+        this.sortElements($cells, function(a, b) {
+
+            var cellA = cells.get($(a).attr('model-id'));
+            var cellB = cells.get($(b).attr('model-id'));
+            
+            return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1;
+        });
+    },
+
+    // Highly inspired by the jquery.sortElements plugin by Padolsey.
+    // See http://james.padolsey.com/javascript/sorting-elements-with-jquery/.
+    sortElements: function(elements, comparator) {
+
+        var $elements = $(elements);
+        
+        var placements = $elements.map(function() {
+
+            var sortElement = this;
+            var parentNode = sortElement.parentNode;
+
+            // Since the element itself will change position, we have
+            // to have some way of storing it's original position in
+            // the DOM. The easiest way is to have a 'flag' node:
+            var nextSibling = parentNode.insertBefore(
+                document.createTextNode(''),
+                sortElement.nextSibling
+            );
+
+            return function() {
+                
+                if (parentNode === this) {
+                    throw new Error(
+                        "You can't sort elements if any one is a descendant of another."
+                    );
+                }
+                
+                // Insert before flag:
+                parentNode.insertBefore(this, nextSibling);
+                // Remove flag:
+                parentNode.removeChild(nextSibling);
+                
+            };
+        });
+
+        return Array.prototype.sort.call($elements, comparator).each(function(i) {
+            placements[i].call(this);
+        });
+    },
+
+    scale: function(sx, sy, ox, oy) {
+
+        if (!ox) {
+
+            ox = 0;
+            oy = 0;
+        }
+
+        // Remove previous transform so that the new scale is not affected by previous scales, especially
+        // the old translate() does not affect the new translate if an origin is specified.
+        V(this.viewport).attr('transform', '');
+        
+        // TODO: V.scale() doesn't support setting scale origin. #Fix        
+        if (ox || oy) {
+            V(this.viewport).translate(-ox * (sx - 1), -oy * (sy - 1));
+        }
+        
+        V(this.viewport).scale(sx, sy);
+
+       this.trigger('scale', ox, oy);
+
+        return this;
+    },
+
+    rotate: function(deg, ox, oy) {
+        
+        // If the origin is not set explicitely, rotate around the center. Note that
+        // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us
+        // the real bounding box (`bbox()`) including transformations).
+        if (_.isUndefined(ox)) {
+
+            var bbox = this.viewport.getBBox();
+            ox = bbox.width/2;
+            oy = bbox.height/2;
+        }
+
+        V(this.viewport).rotate(deg, ox, oy);
+    },
+
+    // Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also
+    // be a selector or a jQuery object.
+    findView: function(el) {
+
+        var $el = this.$(el);
+
+        if ($el.length === 0 || $el[0] === this.el) {
+
+            return undefined;
+        }
+
+        if ($el.data('view')) {
+
+            return $el.data('view');
+        }
+
+        return this.findView($el.parent());
+    },
+
+    // Find a view for a model `cell`. `cell` can also be a string representing a model `id`.
+    findViewByModel: function(cell) {
+
+        var id = _.isString(cell) ? cell : cell.id;
+        
+        var $view = this.$('[model-id="' + id + '"]');
+        if ($view.length) {
+
+            return $view.data('view');
+        }
+        return undefined;
+    },
+
+    // Find all views at given point
+    findViewsFromPoint: function(p) {
+
+       p = g.point(p);
+
+        var views = _.map(this.model.getElements(), this.findViewByModel);
+
+       return _.filter(views, function(view) {
+           return g.rect(V(view.el).bbox(false, this.viewport)).containsPoint(p);
+       }, this);
+    },
+
+    // Find all views in given area
+    findViewsInArea: function(r) {
+
+       r = g.rect(r);
+
+        var views = _.map(this.model.getElements(), this.findViewByModel);
+
+       return _.filter(views, function(view) {
+           return r.intersect(g.rect(V(view.el).bbox(false, this.viewport)));
+       }, this);
+    },
+
+    getModelById: function(id) {
+
+        return this.model.getCell(id);
+    },
+
+    snapToGrid: function(p) {
+
+        // Convert global coordinates to the local ones of the `viewport`. Otherwise,
+        // improper transformation would be applied when the viewport gets transformed (scaled/rotated). 
+        var localPoint = V(this.viewport).toLocalPoint(p.x, p.y);
+
+        return {
+            x: g.snapToGrid(localPoint.x, this.options.gridSize),
+            y: g.snapToGrid(localPoint.y, this.options.gridSize)
+        };
+    },
+
+    getDefaultLink: function(cellView, magnet) {
+
+        return _.isFunction(this.options.defaultLink)
+        // default link is a function producing link model
+            ? this.options.defaultLink.call(this, cellView, magnet)
+        // default link is the Backbone model
+            : this.options.defaultLink.clone();
+    },
+
+    // Interaction.
+    // ------------
+
+    mousedblclick: function(evt) {
+        
+        evt.preventDefault();
+        evt = joint.util.normalizeEvent(evt);
+        
+        var view = this.findView(evt.target);
+        var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+
+        if (view) {
+            
+            view.pointerdblclick(evt, localPoint.x, localPoint.y);
+            
+        } else {
+            
+            this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y);
+        }
+    },
+
+    mouseclick: function(evt) {
+
+        // Trigger event when mouse not moved.
+        if (!this._mousemoved) {
+            
+            evt.preventDefault();
+            evt = joint.util.normalizeEvent(evt);
+
+            var view = this.findView(evt.target);
+            var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+
+            if (view) {
+
+                view.pointerclick(evt, localPoint.x, localPoint.y);
+                
+            } else {
+
+                this.trigger('blank:pointerclick', evt, localPoint.x, localPoint.y);
+            }
+        }
+
+        this._mousemoved = false;
+    },
+
+    pointerdown: function(evt) {
+
+        evt.preventDefault();
+        evt = joint.util.normalizeEvent(evt);
+        
+        var view = this.findView(evt.target);
+
+        var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+        
+        if (view) {
+
+            this.sourceView = view;
+
+            view.pointerdown(evt, localPoint.x, localPoint.y);
+            
+        } else {
+
+            this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y);
+        }
+    },
+
+    pointermove: function(evt) {
+
+        evt.preventDefault();
+        evt = joint.util.normalizeEvent(evt);
+
+        if (this.sourceView) {
+
+            // Mouse moved.
+            this._mousemoved = true;
+
+            var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+
+            this.sourceView.pointermove(evt, localPoint.x, localPoint.y);
+        }
+    },
+
+    pointerup: function(evt) {
+
+        evt = joint.util.normalizeEvent(evt);
+
+        var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
+        
+        if (this.sourceView) {
+
+            this.sourceView.pointerup(evt, localPoint.x, localPoint.y);
+
+            //"delete sourceView" occasionally throws an error in chrome (illegal access exception)
+           this.sourceView = null;
+
+        } else {
+
+            this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y);
+        }
+    }
+});
+
+
+//      JointJS library.
+//      (c) 2011-2013 client IO
+
+
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {},
+        dia: {
+            Element: require('../src/joint.dia.element').Element,
+            ElementView: require('../src/joint.dia.element').ElementView
+        }
+    };
+    var _ = require('lodash');
+}
+
+
+joint.shapes.basic = {};
+
+
+joint.shapes.basic.Generic = joint.dia.Element.extend({
+
+    defaults: joint.util.deepSupplement({
+        
+        type: 'basic.Generic',
+        attrs: {
+            '.': { fill: '#FFFFFF', stroke: 'none' }
+        }
+        
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.basic.Rect = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+    
+        type: 'basic.Rect',
+        attrs: {
+            'rect': { fill: '#FFFFFF', stroke: 'black', width: 100, height: 60 },
+            'text': { 'font-size': 14, text: '', 'ref-x': .5, 'ref-y': .5, ref: 'rect', 'y-alignment': 'middle', 'x-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+        
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Text = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><text/></g></g>',
+    
+    defaults: joint.util.deepSupplement({
+        
+        type: 'basic.Text',
+        attrs: {
+            'text': { 'font-size': 18, fill: 'black' }
+        }
+        
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Circle = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.Circle',
+        size: { width: 60, height: 60 },
+        attrs: {
+            'circle': { fill: '#FFFFFF', stroke: 'black', r: 30, transform: 'translate(30, 30)' },
+            'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, ref: 'circle', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Image = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.Image',
+        attrs: {
+            'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'image', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+joint.shapes.basic.Path = joint.shapes.basic.Generic.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.Path',
+        size: { width: 60, height: 60 },
+        attrs: {
+            'path': { fill: '#FFFFFF', stroke: 'black' },
+            'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'path', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
+        }
+    }, joint.shapes.basic.Generic.prototype.defaults)
+});
+
+// PortsModelInterface is a common interface for shapes that have ports. This interface makes it easy
+// to create new shapes with ports functionality. It is assumed that the new shapes have
+// `inPorts` and `outPorts` array properties. Only these properties should be used to set ports.
+// In other words, using this interface, it is no longer recommended to set ports directly through the
+// `attrs` object.
+
+// Usage:
+// joint.shapes.custom.MyElementWithPorts = joint.shapes.basic.Path.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
+//     getPortAttrs: function(portName, index, total, selector, type) {
+//         var attrs = {};
+//         var portClass = 'port' + index;
+//         var portSelector = selector + '>.' + portClass;
+//         var portTextSelector = portSelector + '>text';
+//         var portCircleSelector = portSelector + '>circle';
+//
+//         attrs[portTextSelector] = { text: portName };
+//         attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type) , type: type } };
+//         attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) };
+//
+//         if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; }
+//
+//         return attrs;
+//     }
+//}));
+joint.shapes.basic.PortsModelInterface = {
+
+    initialize: function() {
+
+        this.updatePortsAttrs();
+        this.on('change:inPorts change:outPorts', this.updatePortsAttrs, this);
+
+        // Call the `initialize()` of the parent.
+        this.constructor.__super__.constructor.__super__.initialize.apply(this, arguments);
+    },
+    
+    updatePortsAttrs: function(eventName) {
+
+        // Delete previously set attributes for ports.
+        var currAttrs = this.get('attrs');
+        _.each(this._portSelectors, function(selector) {
+            if (currAttrs[selector]) delete currAttrs[selector];
+        });
+        
+        // This holds keys to the `attrs` object for all the port specific attribute that
+        // we set in this method. This is necessary in order to remove previously set
+        // attributes for previous ports.
+        this._portSelectors = [];
+        
+        var attrs = {};
+        
+        _.each(this.get('inPorts'), function(portName, index, ports) {
+            var portAttributes = this.getPortAttrs(portName, index, ports.length, '.inPorts', 'in');
+            this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
+            _.extend(attrs, portAttributes);
+        }, this);
+        
+        _.each(this.get('outPorts'), function(portName, index, ports) {
+            var portAttributes = this.getPortAttrs(portName, index, ports.length, '.outPorts', 'out');
+            this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
+            _.extend(attrs, portAttributes);
+        }, this);
+
+        // Silently set `attrs` on the cell so that noone knows the attrs have changed. This makes sure
+        // that, for example, command manager does not register `change:attrs` command but only
+        // the important `change:inPorts`/`change:outPorts` command.
+        this.attr(attrs, { silent: true });
+        // Manually call the `processPorts()` method that is normally called on `change:attrs` (that we just made silent).
+        this.processPorts();
+        // Let the outside world (mainly the `ModelView`) know that we're done configuring the `attrs` object.
+        this.trigger('process:ports');
+    },
+
+    getPortSelector: function(name) {
+
+        var selector = '.inPorts';
+        var index = this.get('inPorts').indexOf(name);
+
+        if (index < 0) {
+            selector = '.outPorts';
+            index = this.get('outPorts').indexOf(name);
+
+            if (index < 0) throw new Error("getPortSelector(): Port doesn't exist.");
+        }
+
+        return selector + '>g:nth-child(' + (index + 1) + ')>circle';
+    }
+};
+
+joint.shapes.basic.PortsViewInterface = {
+    
+    initialize: function() {
+
+        // `Model` emits the `process:ports` whenever it's done configuring the `attrs` object for ports.
+        this.listenTo(this.model, 'process:ports', this.update);
+        
+        joint.dia.ElementView.prototype.initialize.apply(this, arguments);
+    },
+
+    update: function() {
+
+        // First render ports so that `attrs` can be applied to those newly created DOM elements
+        // in `ElementView.prototype.update()`.
+        this.renderPorts();
+        joint.dia.ElementView.prototype.update.apply(this, arguments);
+    },
+
+    renderPorts: function() {
+
+        var $inPorts = this.$('.inPorts').empty();
+        var $outPorts = this.$('.outPorts').empty();
+
+        var portTemplate = _.template(this.model.portMarkup);
+
+        _.each(_.filter(this.model.ports, function(p) { return p.type === 'in' }), function(port, index) {
+
+            $inPorts.append(V(portTemplate({ id: index, port: port })).node);
+        });
+        _.each(_.filter(this.model.ports, function(p) { return p.type === 'out' }), function(port, index) {
+
+            $outPorts.append(V(portTemplate({ id: index, port: port })).node);
+        });
+    }
+};
+
+joint.shapes.basic.TextBlock = joint.shapes.basic.Generic.extend({
+
+    markup: ['<g class="rotatable"><g class="scalable"><rect/></g><switch>',
+
+             // if foreignObject supported
+
+             '<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">',
+             '<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',
+             '</foreignObject>',
+
+             // else foreignObject is not supported (fallback for IE)
+             '<text class="content"/>',
+
+             '</switch></g>'].join(''),
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'basic.TextBlock',
+
+        // see joint.css for more element styles
+        attrs: {
+            rect: {
+                fill: '#ffffff',
+                stroke: '#000000',
+                width: 80,
+                height: 100
+            },
+            text: {
+                fill: '#000000',
+                'font-size': 14,
+                'font-family': 'Arial, helvetica, sans-serif'
+            },
+            '.content': {
+                text: '',
+                ref: 'rect',
+                'ref-x': .5,
+                'ref-y': .5,
+                'y-alignment': 'middle',
+                'x-alignment': 'middle'
+            }
+        },
+
+        content: ''
+
+    }, joint.shapes.basic.Generic.prototype.defaults),
+
+    initialize: function() {
+
+        if (typeof SVGForeignObjectElement !== 'undefined') {
+
+            // foreignObject supported
+            this.setForeignObjectSize(this, this.get('size'));
+            this.setDivContent(this, this.get('content'));
+            this.listenTo(this, 'change:size', this.setForeignObjectSize);
+            this.listenTo(this, 'change:content', this.setDivContent);
+
+        }
+
+        joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
+    },
+
+    setForeignObjectSize: function(cell, size) {
+
+        // Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead.
+        // We have to clone size as we don't want attributes.div.style to be same object as attributes.size.
+        cell.attr({
+            '.fobj': _.clone(size),
+            div: { style: _.clone(size) }
+        });
+    },
+
+    setDivContent: function(cell, content) {
+
+        // Append the content to div as html.
+        cell.attr({ div : {
+            html: content
+        }});
+    }
+
+});
+
+// TextBlockView implements the fallback for IE when no foreignObject exists and
+// the text needs to be manually broken.
+joint.shapes.basic.TextBlockView = joint.dia.ElementView.extend({
+
+    initialize: function() {
+
+        joint.dia.ElementView.prototype.initialize.apply(this, arguments);
+
+        if (typeof SVGForeignObjectElement === 'undefined') {
+
+            this.noSVGForeignObjectElement = true;
+
+            this.listenTo(this.model, 'change:content', function(cell) {
+                // avoiding pass of extra paramters
+                this.updateContent(cell);
+            });
+        }
+    },
+
+    update: function(cell, renderingOnlyAttrs) {
+
+        if (this.noSVGForeignObjectElement) {
+
+            var model = this.model;
+
+            // Update everything but the content first.
+            var noTextAttrs = _.omit(renderingOnlyAttrs || model.get('attrs'), '.content');
+            joint.dia.ElementView.prototype.update.call(this, model, noTextAttrs);
+
+            if (!renderingOnlyAttrs || _.has(renderingOnlyAttrs, '.content')) {
+                // Update the content itself.
+                this.updateContent(model, renderingOnlyAttrs);
+            }
+
+        } else {
+
+            joint.dia.ElementView.prototype.update.call(this, model, renderingOnlyAttrs);
+        }
+    },
+
+    updateContent: function(cell, renderingOnlyAttrs) {
+
+        // Create copy of the text attributes
+        var textAttrs = _.merge({}, (renderingOnlyAttrs || cell.get('attrs'))['.content']);
+
+        delete textAttrs.text;
+
+        // Break the content to fit the element size taking into account the attributes
+        // set on the model.
+        var text = joint.util.breakText(cell.get('content'), cell.get('size'), textAttrs, {
+            // measuring sandbox svg document
+            svgDocument: this.paper.svg
+        });
+
+        // Create a new attrs with same structure as the model attrs { text: { *textAttributes* }}
+        var attrs = joint.util.setByPath({}, '.content', textAttrs,'/');
+
+        // Replace text attribute with the one we just processed.
+        attrs['.content'].text = text;
+
+        // Update the view using renderingOnlyAttributes parameter.
+        joint.dia.ElementView.prototype.update.call(this, cell, attrs);
+    }
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.basic;
+}
+
+joint.routers.orthogonal = function() {
+
+    var sourceBBox, targetBBox;
+
+    // Return the direction that one would have to take traveling from `p1` to `p2`.
+    // This function assumes the line between `p1` and `p2` is orthogonal.
+    function direction(p1, p2) {
+        
+        if (p1.y < p2.y && p1.x === p2.x) {
+            return 'down';
+        } else if (p1.y > p2.y && p1.x === p2.x) {
+            return 'up';
+        } else if (p1.x < p2.x && p1.y === p2.y) {
+            return 'right';
+        }
+        return 'left';
+    }
+
+    function bestDirection(p1, p2, preferredDirection) {
+
+        var directions;
+
+        // This branching determines possible directions that one can take to travel
+        // from `p1` to `p2`.
+        if (p1.x < p2.x) {
+
+            if (p1.y > p2.y) { directions = ['up', 'right']; }
+            else if (p1.y < p2.y) { directions = ['down', 'right']; }
+            else { directions = ['right']; }
+
+        } else if (p1.x > p2.x) {
+
+            if (p1.y > p2.y) { directions = ['up', 'left']; }
+            else if (p1.y < p2.y) { directions = ['down', 'left']; }
+            else { directions = ['left']; }
+
+        } else {
+
+            if (p1.y > p2.y) { directions = ['up']; }
+            else { directions = ['down']; }
+        }
+
+        if (_.contains(directions, preferredDirection)) {
+            return preferredDirection;
+        }
+
+        var direction = _.first(directions);
+
+        // Should the direction be the exact opposite of the preferred direction,
+        // try another one if such direction exists.
+        switch (preferredDirection) {
+        case 'down': if (direction === 'up') return _.last(directions); break;
+        case 'up': if (direction === 'down') return _.last(directions); break;
+        case 'left': if (direction === 'right') return _.last(directions); break;
+        case 'right': if (direction === 'left') return _.last(directions); break;
+        }
+        return direction;
+    };
+
+    // Find a vertex in between the vertices `p1` and `p2` so that the route between those vertices
+    // is orthogonal. Prefer going the direction determined by `preferredDirection`.
+    function findMiddleVertex(p1, p2, preferredDirection) {
+        
+        var direction = bestDirection(p1, p2, preferredDirection);
+        if (direction === 'down' || direction === 'up') {
+            return { x: p1.x, y: p2.y, d: direction };
+        }
+        return { x: p2.x, y: p1.y, d: direction };
+    }
+
+    // Return points that one needs to draw a connection through in order to have a orthogonal link
+    // routing from source to target going through `vertices`.
+    function findOrthogonalRoute(vertices) {
+
+        vertices = (vertices || []).slice();
+        var orthogonalVertices = [];
+
+        var sourceCenter = sourceBBox.center();
+        var targetCenter = targetBBox.center();
+
+        if (!vertices.length) {
+
+            if (Math.abs(sourceCenter.x - targetCenter.x) < (sourceBBox.width / 2) ||
+                Math.abs(sourceCenter.y - targetCenter.y) < (sourceBBox.height / 2)
+            ) {
+
+                vertices = [{
+                    x: Math.min(sourceCenter.x, targetCenter.x) +
+                        Math.abs(sourceCenter.x - targetCenter.x) / 2,
+                    y: Math.min(sourceCenter.y, targetCenter.y) +
+                        Math.abs(sourceCenter.y - targetCenter.y) / 2
+                }];
+            }
+        }
+
+        vertices.unshift(sourceCenter);
+        vertices.push(targetCenter);
+
+        var orthogonalVertex;
+        var lastOrthogonalVertex;
+        var vertex;
+        var nextVertex;
+
+        // For all the pairs of link model vertices...
+        for (var i = 0; i < vertices.length - 1; i++) {
+
+            vertex = vertices[i];
+            nextVertex = vertices[i + 1];
+            lastOrthogonalVertex = _.last(orthogonalVertices);
+            
+            if (i > 0) {
+                // Push all the link vertices to the orthogonal route.
+                orthogonalVertex = vertex;
+                // Determine a direction between the last vertex and the new one.
+                // Therefore, each vertex contains the `d` property describing the direction that one
+                // would have to take to travel to that vertex.
+                orthogonalVertex.d = lastOrthogonalVertex
+                    ? direction(lastOrthogonalVertex, vertex)
+                    : 'top';
+
+                orthogonalVertices.push(orthogonalVertex);
+                lastOrthogonalVertex = orthogonalVertex;
+            }
+
+            // Make sure that we don't create a vertex that would go the opposite direction then
+            // that of the previous one.
+            // Othwerwise, a 'spike' segment would be created which is not desirable.
+            // Find a dummy vertex to keep the link orthogonal. Preferably, take the same direction
+            // as the previous one.
+            var d = lastOrthogonalVertex && lastOrthogonalVertex.d;
+            orthogonalVertex = findMiddleVertex(vertex, nextVertex, d);
+
+            // Do not add a new vertex that is the same as one of the vertices already added.
+            if (!g.point(orthogonalVertex).equals(g.point(vertex)) &&
+                !g.point(orthogonalVertex).equals(g.point(nextVertex))) {
+
+                orthogonalVertices.push(orthogonalVertex);
+            }
+        }
+        return orthogonalVertices;
+    };
+
+    return function(vertices) {
+
+        sourceBBox = this.sourceBBox;
+        targetBBox = this.targetBBox;
+
+        return findOrthogonalRoute(vertices);
+    };
+
+}();
+
+joint.routers.manhattan = (function() {
+
+    'use strict';
+
+    var config = {
+
+        // size of the step to find a route
+        step: 10,
+
+        // use of the perpendicular linkView option to connect center of element with first vertex
+        perpendicular: true,
+
+        // tells how to divide the paper when creating the elements map
+        mapGridSize: 100,
+
+        // should be source or target not to be consider as an obstacle
+        excludeEnds: [], // 'source', 'target'
+
+        // should be any element with a certain type not to be consider as an obstacle
+        excludeTypes: ['basic.Text'],
+
+        // if number of route finding loops exceed the maximum, stops searching and returns
+        // fallback route
+        maximumLoops: 500,
+
+        // possible starting directions from an element
+        startDirections: ['left','right','top','bottom'],
+
+        // possible ending directions to an element
+        endDirections: ['left','right','top','bottom'],
+
+        // specify directions above
+        directionMap: {
+            right: { x: 1, y: 0 },
+            bottom: { x: 0, y: 1 },
+            left: { x: -1, y: 0 },
+            top: { x: 0, y: -1 }
+        },
+
+        // maximum change of the direction
+        maxAllowedDirectionChange: 1,
+
+        // padding applied on the element bounding boxes
+        paddingBox: function() {
+
+            var step = this.step;
+
+            return {
+                x: -step,
+                y: -step,
+                width: 2*step,
+                height: 2*step
+            }
+        },
+
+        // an array of directions to find next points on the route
+        directions: function() {
+
+            var step = this.step;
+
+            return [
+                { offsetX: step  , offsetY: 0     , cost: step },
+                { offsetX: 0     , offsetY: step  , cost: step },
+                { offsetX: -step , offsetY: 0     , cost: step },
+                { offsetX: 0     , offsetY: -step , cost: step }
+            ];
+        },
+
+        // a penalty received for direction change
+        penalties: function() {
+
+            return [0, this.step / 2, this.step];
+        },
+
+        // heurestic method to determine the distance between two points
+        estimateCost: function(from, to) {
+
+            return from.manhattanDistance(to);
+        },
+
+        // a simple route used in situations, when main routing method fails
+        // (exceed loops, inaccessible).
+        fallbackRoute: function(from, to, opts) {
+
+            // Find an orthogonal route ignoring obstacles.
+
+            var prevDirIndexes = opts.prevDirIndexes || {};
+
+            var point = (prevDirIndexes[from] || 0) % 2
+                    ? g.point(from.x, to.y)
+                    : g.point(to.x, from.y);
+
+            return [point, to];
+        },
+
+        // if a function is provided, it's used to route the link while dragging an end
+        // i.e. function(from, to, opts) { return []; }
+        draggingRoute: null
+    };
+
+    // reconstructs a route by concating points with their parents
+    function reconstructRoute(parents, point) {
+
+        var route = [];
+        var prevDiff = { x: 0, y: 0 };
+        var current = point;
+        var parent;
+
+        while ((parent = parents[current])) {
+
+            var diff = parent.difference(current);
+
+            if (!diff.equals(prevDiff)) {
+
+                route.unshift(current);
+                prevDiff = diff;
+            }
+
+            current = parent;
+        }
+
+        route.unshift(current);
+
+        return route;
+    };
+
+    // find points around the rectangle taking given directions in the account
+    function getRectPoints(bbox, directionList, opts) {
+
+        var step = opts.step;
+
+        var center = bbox.center();
+
+        var startPoints = _.chain(opts.directionMap).pick(directionList).map(function(direction) {
+
+            var x = direction.x * bbox.width / 2;
+            var y = direction.y * bbox.height / 2;
+
+            var point = g.point(center).offset(x,y).snapToGrid(step);
+
+            if (bbox.containsPoint(point)) {
+
+                point.offset(direction.x * step, direction.y * step);
+            }
+
+            return point;
+
+        }).value();
+
+        return startPoints;
+    };
+
+    // returns a direction index from start point to end point
+    function getDirection(start, end, dirLen) {
+
+        var dirAngle = 360 / dirLen;
+
+        var q = Math.floor(start.theta(end) / dirAngle);
+
+        return dirLen - q;
+    }
+
+    // finds the route between to points/rectangles implementing A* alghoritm
+    function findRoute(start, end, map, opt) {
+
+        var startDirections = opt.reversed ? opt.endDirections : opt.startDirections;
+        var endDirections = opt.reversed ? opt.startDirections : opt.endDirections;
+
+        // set of points we start pathfinding from
+        var startSet = start instanceof g.rect
+                ? getRectPoints(start, startDirections, opt)
+                : [start];
+
+        // set of points we want the pathfinding to finish at
+        var endSet = end instanceof g.rect
+                ? getRectPoints(end, endDirections, opt)
+                : [end];
+
+        var startCenter = startSet.length > 1 ? start.center() : startSet[0];
+        var endCenter = endSet.length > 1 ? end.center() : endSet[0];
+
+        // take into account  only accessible end points
+        var endPoints = _.filter(endSet, function(point) {
+
+            var mapKey = g.point(point).snapToGrid(opt.mapGridSize).toString();
+
+            var accesible = _.every(map[mapKey], function(obstacle) {
+                return !obstacle.containsPoint(point);
+            });
+
+            return accesible;
+        });
+
+
+        if (endPoints.length) {
+
+            var step = opt.step;
+            var penalties = opt.penalties;
+
+            // choose the end point with the shortest estimated path cost
+            var endPoint = _.chain(endPoints).invoke('snapToGrid', step).min(function(point) {
+
+                return opt.estimateCost(startCenter, point);
+
+            }).value();
+
+            var parents = {};
+            var costFromStart = {};
+            var totalCost = {};
+
+            // directions
+            var dirs = opt.directions;
+            var dirLen = dirs.length;
+            var dirHalfLen = dirLen / 2;
+            var dirIndexes = opt.previousDirIndexes || {};
+
+            // The set of point already evaluated.
+            var closeHash = {}; // keeps only information whether a point was evaluated'
+
+            // The set of tentative points to be evaluated, initially containing the start points
+            var openHash = {}; // keeps only information whether a point is to be evaluated'
+            var openSet = _.chain(startSet).invoke('snapToGrid', step).each(function(point) {
+
+                var key = point.toString();
+
+                costFromStart[key] = 0; // Cost from start along best known path.
+                totalCost[key] = opt.estimateCost(point, endPoint);
+                dirIndexes[key] = dirIndexes[key] || getDirection(startCenter, point, dirLen);
+                openHash[key] = true;
+
+            }).map(function(point) {
+
+                return point.toString();
+
+            }).sortBy(function(pointKey) {
+
+                return totalCost[pointKey];
+
+            }).value();
+
+            var loopCounter = opt.maximumLoops;
+
+            var maxAllowedDirectionChange = opt.maxAllowedDirectionChange;
+
+            // main route finding loop
+            while (openSet.length && loopCounter--) {
+
+                var currentKey = openSet[0];
+                var currentPoint = g.point(currentKey);
+
+                if (endPoint.equals(currentPoint)) {
+
+                    opt.previousDirIndexes = _.pick(dirIndexes, currentKey);
+                    return reconstructRoute(parents, currentPoint);
+                }
+
+                // remove current from the open list
+                openSet.splice(0, 1);
+                openHash[neighborKey] = null;
+
+                // add current to the close list
+                closeHash[neighborKey] = true;
+
+                var currentDirIndex = dirIndexes[currentKey];
+                var currentDist = costFromStart[currentKey];
+
+                for (var dirIndex = 0; dirIndex < dirLen; dirIndex++) {
+
+                    var dirChange = Math.abs(dirIndex - currentDirIndex);
+
+                    if (dirChange > dirHalfLen) {
+
+                        dirChange = dirLen - dirChange;
+                    }
+
+                    // if the direction changed rapidly don't use this point
+                    if (dirChange > maxAllowedDirectionChange) {
+
+                        continue;
+                    }
+
+                    var dir = dirs[dirIndex];
+
+                    var neighborPoint = g.point(currentPoint).offset(dir.offsetX, dir.offsetY);
+                    var neighborKey = neighborPoint.toString();
+
+                    if (closeHash[neighborKey]) {
+
+                        continue;
+                    }
+
+                    // is point accesible - no obstacle in the way
+
+                    var mapKey = g.point(neighborPoint).snapToGrid(opt.mapGridSize).toString();
+
+                    var isAccesible = _.every(map[mapKey], function(obstacle) {
+                        return !obstacle.containsPoint(neighborPoint);
+                    });
+
+                    if (!isAccesible) {
+
+                        continue;
+                    }
+
+                    var inOpenSet = _.has(openHash, neighborKey);
+
+                    var costToNeighbor = currentDist + dir.cost;
+
+                    if (!inOpenSet || costToNeighbor < costFromStart[neighborKey]) {
+
+                        parents[neighborKey] = currentPoint;
+                        dirIndexes[neighborKey] = dirIndex;
+                        costFromStart[neighborKey] = costToNeighbor;
+
+                        totalCost[neighborKey] = costToNeighbor +
+                            opt.estimateCost(neighborPoint, endPoint) +
+                            penalties[dirChange];
+
+                        if (!inOpenSet) {
+
+                            var openIndex = _.sortedIndex(openSet, neighborKey, function(openKey) {
+
+                                return totalCost[openKey];
+                            });
+
+                            openSet.splice(openIndex, 0, neighborKey);
+                            openHash[neighborKey] = true;
+                        }
+                    };
+                };
+            }
+        }
+
+        // no route found ('to' point wasn't either accessible or finding route took
+        // way to much calculations)
+        return opt.fallbackRoute(startCenter, endCenter, opt);
+    };
+
+    // initiation of the route finding
+    function router(oldVertices, opt) {
+
+        // resolve some of the options
+        opt.directions = _.result(opt, 'directions');
+        opt.penalties = _.result(opt, 'penalties');
+        opt.paddingBox = _.result(opt, 'paddingBox');
+
+        // enable/disable linkView perpendicular option
+        this.options.perpendicular = !!opt.perpendicular;
+
+        // As route changes its shape rapidly when we start finding route from different point
+        // it's necessary to start from the element that was not interacted with
+        // (the position was changed) at very last.
+        var reverseRouting = opt.reversed = (this.lastEndChange === 'source');
+
+        var sourceBBox = reverseRouting ? g.rect(this.targetBBox) : g.rect(this.sourceBBox);
+        var targetBBox = reverseRouting ? g.rect(this.sourceBBox) : g.rect(this.targetBBox);
+
+        // expand boxes by specific padding
+        sourceBBox.moveAndExpand(opt.paddingBox);
+        targetBBox.moveAndExpand(opt.paddingBox);
+
+        // building an elements map
+
+        var link = this.model;
+        var graph = this.paper.model;
+
+        // source or target element could be excluded from set of obstacles
+        var excludedEnds = _.chain(opt.excludeEnds)
+                .map(link.get, link)
+                .pluck('id')
+                .map(graph.getCell, graph).value();
+
+        var mapGridSize = opt.mapGridSize;
+
+        // builds a map of all elements for quicker obstacle queries (i.e. is a point contained
+        // in any obstacle?) (a simplified grid search)
+        // The paper is divided to smaller cells, where each of them holds an information which
+        // elements belong to it. When we query whether a point is in an obstacle we don't need
+        // to go through all obstacles, we check only those in a particular cell.
+        var map = _.chain(graph.getElements())
+            // remove source and target element if required
+            .difference(excludedEnds)
+            // remove all elements whose type is listed in excludedTypes array
+            .reject(function(element) {
+                return _.contains(opt.excludeTypes, element.get('type'));
+            })
+            // change elements (models) to their bounding boxes
+            .invoke('getBBox')
+            // expand their boxes by specific padding
+            .invoke('moveAndExpand', opt.paddingBox)
+            // build the map
+            .foldl(function(res, bbox) {
+
+                var origin = bbox.origin().snapToGrid(mapGridSize);
+                var corner = bbox.corner().snapToGrid(mapGridSize);
+
+                for (var x = origin.x; x <= corner.x; x += mapGridSize) {
+                    for (var y = origin.y; y <= corner.y; y += mapGridSize) {
+
+                        var gridKey = x + '@' + y;
+
+                        res[gridKey] = res[gridKey] || [];
+                        res[gridKey].push(bbox);
+                    }
+                }
+
+                return res;
+
+            }, {}).value();
+
+        // pathfinding
+
+        var newVertices = [];
+
+        var points = _.map(oldVertices, g.point);
+
+        var tailPoint = sourceBBox.center();
+
+        // find a route by concating all partial routes (routes need to go through the vertices)
+        // startElement -> vertex[1] -> ... -> vertex[n] -> endElement
+        for (var i = 0, len = points.length; i <= len; i++) {
+
+            var partialRoute = null;
+
+            var from = to || sourceBBox;
+            var to = points[i];
+
+            if (!to) {
+
+                to = targetBBox;
+
+                // 'to' is not a vertex. If the target is a point (i.e. it's not an element), we
+                // might use dragging route instead of main routing method if that is enabled.
+                var endingAtPoint = !this.model.get('source').id || !this.model.get('target').id;
+
+                if (endingAtPoint && _.isFunction(opt.draggingRoute)) {
+                    // Make sure we passing points only (not rects).
+                    var dragFrom = from instanceof g.rect ? from.center() : from;
+                    partialRoute = opt.draggingRoute(dragFrom, to.origin(), opt);
+                }
+            }
+
+            // if partial route has not been calculated yet use the main routing method to find one
+            partialRoute = partialRoute || findRoute(from, to, map, opt);
+
+            var leadPoint = _.first(partialRoute);
+
+            if (leadPoint && leadPoint.equals(tailPoint)) {
+
+                // remove the first point if the previous partial route had the same point as last
+                partialRoute.shift();
+            }
+
+            tailPoint = _.last(partialRoute) || tailPoint;
+
+            newVertices = newVertices.concat(partialRoute);
+        };
+
+        // we might have to reverse the result if we swapped source and target at the beginning
+        return reverseRouting ? newVertices.reverse() : newVertices;
+    };
+
+    // public function
+    return function(vertices, opt, linkView) {
+
+        return router.call(linkView, vertices, _.extend({}, config, opt));
+    };
+
+})();
+
+joint.routers.metro = (function() {
+
+    if (!_.isFunction(joint.routers.manhattan)) {
+
+        throw('Metro requires the manhattan router.');
+    }
+
+    var config = {
+
+        // cost of a diagonal step (calculated if not defined).
+        diagonalCost: null,
+
+        // an array of directions to find next points on the route
+        directions: function() {
+
+            var step = this.step;
+            var diagonalCost = this.diagonalCost || Math.ceil(Math.sqrt(step * step << 1));
+
+            return [
+                { offsetX: step  , offsetY: 0     , cost: step         },
+                { offsetX: step  , offsetY: step  , cost: diagonalCost },
+                { offsetX: 0     , offsetY: step  , cost: step         },
+                { offsetX: -step , offsetY: step  , cost: diagonalCost },
+                { offsetX: -step , offsetY: 0     , cost: step         },
+                { offsetX: -step , offsetY: -step , cost: diagonalCost },
+                { offsetX: 0     , offsetY: -step , cost: step         },
+                { offsetX: step  , offsetY: -step , cost: diagonalCost }
+            ];
+        },
+
+        // a simple route used in situations, when main routing method fails
+        // (exceed loops, inaccessible).
+        fallbackRoute: function(from, to, opts) {
+
+            // Find a route which breaks by 45 degrees ignoring all obstacles.
+
+            var theta = from.theta(to);
+
+            var a = { x: to.x, y: from.y };
+            var b = { x: from.x, y: to.y };
+
+            if (theta % 180 > 90) {
+                var t = a;
+                a = b;
+                b = t;
+            }
+
+            var p1 = (theta % 90) < 45 ? a : b;
+
+            var l1 = g.line(from, p1);
+
+            var alpha = 90 * Math.ceil(theta / 90);
+
+            var p2 = g.point.fromPolar(l1.squaredLength(), g.toRad(alpha + 135), p1);
+
+            var l2 = g.line(to, p2);
+
+            var point = l1.intersection(l2);
+
+            return point ? [point.round(), to] : [to];
+        }
+    };
+
+    // public function
+    return function(vertices, opts, linkView) {
+
+        return joint.routers.manhattan(vertices, _.extend({}, config, opts), linkView);
+    };
+
+})();
+
+joint.connectors.normal = function(sourcePoint, targetPoint, vertices) {
+
+    // Construct the `d` attribute of the `<path>` element.
+    var d = ['M', sourcePoint.x, sourcePoint.y];
+
+    _.each(vertices, function(vertex) {
+
+        d.push(vertex.x, vertex.y);
+    });
+
+    d.push(targetPoint.x, targetPoint.y);
+
+    return d.join(' ');
+};
+
+joint.connectors.rounded = function(sourcePoint, targetPoint, vertices, opts) {
+
+    var offset = opts.radius || 10;
+
+    var c1, c2, d1, d2, prev, next;
+
+    // Construct the `d` attribute of the `<path>` element.
+    var d = ['M', sourcePoint.x, sourcePoint.y];
+
+    _.each(vertices, function(vertex, index) {
+
+        // the closest vertices
+        prev = vertices[index-1] || sourcePoint;
+        next = vertices[index+1] || targetPoint;
+
+        // a half distance to the closest vertex
+        d1 = d2 || g.point(vertex).distance(prev) / 2;
+        d2 = g.point(vertex).distance(next) / 2;
+
+        // control points
+        c1 = g.point(vertex).move(prev, -Math.min(offset, d1)).round();
+        c2 = g.point(vertex).move(next, -Math.min(offset, d2)).round();
+
+        d.push(c1.x, c1.y, 'S', vertex.x, vertex.y, c2.x, c2.y, 'L');
+    });
+
+    d.push(targetPoint.x, targetPoint.y);
+
+    return d.join(' ');
+};
+
+joint.connectors.smooth = function(sourcePoint, targetPoint, vertices) {
+
+    var d;
+
+    if (vertices.length) {
+
+        d = g.bezier.curveThroughPoints([sourcePoint].concat(vertices).concat([targetPoint]));
+
+    } else {
+        // if we have no vertices use a default cubic bezier curve, cubic bezier requires
+        // two control points. The two control points are both defined with X as mid way
+        // between the source and target points. SourceControlPoint Y is equal to sourcePoint Y
+        // and targetControlPointY being equal to targetPointY. Handle situation were
+        // sourcePointX is greater or less then targetPointX.
+        var controlPointX = (sourcePoint.x < targetPoint.x) 
+                ? targetPoint.x - ((targetPoint.x - sourcePoint.x) / 2)
+                : sourcePoint.x - ((sourcePoint.x - targetPoint.x) / 2);
+
+        d = [
+            'M', sourcePoint.x, sourcePoint.y,
+            'C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y,
+            targetPoint.x, targetPoint.y
+        ];
+    }
+
+    return d.join(' ');
+};
diff --git a/js/joint.layout.DirectedGraph.js b/js/joint.layout.DirectedGraph.js
new file mode 100644 (file)
index 0000000..d9dfec8
--- /dev/null
@@ -0,0 +1,4111 @@
+/*! JointJS v0.9.0 - JavaScript diagramming library  2014-05-13
+
+
+This Source Code Form is subject to the terms of the Mozilla Public
+License, v. 2.0. If a copy of the MPL was not distributed with this
+file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+;(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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 global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
+ * @license
+ * Copyright (c) 2012-2013 Chris Pettitt
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+global.dagre = require("./index");
+
+},{"./index":2}],2:[function(require,module,exports){
+/*
+Copyright (c) 2012-2013 Chris Pettitt
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+exports.Digraph = require("graphlib").Digraph;
+exports.Graph = require("graphlib").Graph;
+exports.layout = require("./lib/layout");
+exports.version = require("./lib/version");
+
+},{"./lib/layout":3,"./lib/version":18,"graphlib":24}],3:[function(require,module,exports){
+var util = require('./util'),
+    rank = require('./rank'),
+    order = require('./order'),
+    CGraph = require('graphlib').CGraph,
+    CDigraph = require('graphlib').CDigraph;
+
+module.exports = function() {
+  // External configuration
+  var config = {
+    // How much debug information to include?
+    debugLevel: 2,
+    // Max number of sweeps to perform in order phase
+    orderMaxSweeps: order.DEFAULT_MAX_SWEEPS,
+    // Use network simplex algorithm in ranking
+    rankSimplex: false,
+    // Rank direction. Valid values are (TB, LR)
+    rankDir: 'TB'
+  };
+
+  // Phase functions
+  var position = require('./position')();
+
+  // This layout object
+  var self = {};
+
+  self.orderIters = util.propertyAccessor(self, config, 'orderMaxSweeps');
+
+  self.rankSimplex = util.propertyAccessor(self, config, 'rankSimplex');
+
+  self.nodeSep = delegateProperty(position.nodeSep);
+  self.edgeSep = delegateProperty(position.edgeSep);
+  self.universalSep = delegateProperty(position.universalSep);
+  self.rankSep = delegateProperty(position.rankSep);
+  self.rankDir = util.propertyAccessor(self, config, 'rankDir');
+  self.debugAlignment = delegateProperty(position.debugAlignment);
+
+  self.debugLevel = util.propertyAccessor(self, config, 'debugLevel', function(x) {
+    util.log.level = x;
+    position.debugLevel(x);
+  });
+
+  self.run = util.time('Total layout', run);
+
+  self._normalize = normalize;
+
+  return self;
+
+  /*
+   * Constructs an adjacency graph using the nodes and edges specified through
+   * config. For each node and edge we add a property `dagre` that contains an
+   * object that will hold intermediate and final layout information. Some of
+   * the contents include:
+   *
+   *  1) A generated ID that uniquely identifies the object.
+   *  2) Dimension information for nodes (copied from the source node).
+   *  3) Optional dimension information for edges.
+   *
+   * After the adjacency graph is constructed the code no longer needs to use
+   * the original nodes and edges passed in via config.
+   */
+  function initLayoutGraph(inputGraph) {
+    var g = new CDigraph();
+
+    inputGraph.eachNode(function(u, value) {
+      if (value === undefined) value = {};
+      g.addNode(u, {
+        width: value.width,
+        height: value.height
+      });
+      if (value.hasOwnProperty('rank')) {
+        g.node(u).prefRank = value.rank;
+      }
+    });
+
+    // Set up subgraphs
+    if (inputGraph.parent) {
+      inputGraph.nodes().forEach(function(u) {
+        g.parent(u, inputGraph.parent(u));
+      });
+    }
+
+    inputGraph.eachEdge(function(e, u, v, value) {
+      if (value === undefined) value = {};
+      var newValue = {
+        e: e,
+        minLen: value.minLen || 1,
+        width: value.width || 0,
+        height: value.height || 0,
+        points: []
+      };
+
+      g.addEdge(null, u, v, newValue);
+    });
+
+    // Initial graph attributes
+    var graphValue = inputGraph.graph() || {};
+    g.graph({
+      rankDir: graphValue.rankDir || config.rankDir,
+      orderRestarts: graphValue.orderRestarts
+    });
+
+    return g;
+  }
+
+  function run(inputGraph) {
+    var rankSep = self.rankSep();
+    var g;
+    try {
+      // Build internal graph
+      g = util.time('initLayoutGraph', initLayoutGraph)(inputGraph);
+
+      if (g.order() === 0) {
+        return g;
+      }
+
+      // Make space for edge labels
+      g.eachEdge(function(e, s, t, a) {
+        a.minLen *= 2;
+      });
+      self.rankSep(rankSep / 2);
+
+      // Determine the rank for each node. Nodes with a lower rank will appear
+      // above nodes of higher rank.
+      util.time('rank.run', rank.run)(g, config.rankSimplex);
+
+      // Normalize the graph by ensuring that every edge is proper (each edge has
+      // a length of 1). We achieve this by adding dummy nodes to long edges,
+      // thus shortening them.
+      util.time('normalize', normalize)(g);
+
+      // Order the nodes so that edge crossings are minimized.
+      util.time('order', order)(g, config.orderMaxSweeps);
+
+      // Find the x and y coordinates for every node in the graph.
+      util.time('position', position.run)(g);
+
+      // De-normalize the graph by removing dummy nodes and augmenting the
+      // original long edges with coordinate information.
+      util.time('undoNormalize', undoNormalize)(g);
+
+      // Reverses points for edges that are in a reversed state.
+      util.time('fixupEdgePoints', fixupEdgePoints)(g);
+
+      // Restore delete edges and reverse edges that were reversed in the rank
+      // phase.
+      util.time('rank.restoreEdges', rank.restoreEdges)(g);
+
+      // Construct final result graph and return it
+      return util.time('createFinalGraph', createFinalGraph)(g, inputGraph.isDirected());
+    } finally {
+      self.rankSep(rankSep);
+    }
+  }
+
+  /*
+   * This function is responsible for 'normalizing' the graph. The process of
+   * normalization ensures that no edge in the graph has spans more than one
+   * rank. To do this it inserts dummy nodes as needed and links them by adding
+   * dummy edges. This function keeps enough information in the dummy nodes and
+   * edges to ensure that the original graph can be reconstructed later.
+   *
+   * This method assumes that the input graph is cycle free.
+   */
+  function normalize(g) {
+    var dummyCount = 0;
+    g.eachEdge(function(e, s, t, a) {
+      var sourceRank = g.node(s).rank;
+      var targetRank = g.node(t).rank;
+      if (sourceRank + 1 < targetRank) {
+        for (var u = s, rank = sourceRank + 1, i = 0; rank < targetRank; ++rank, ++i) {
+          var v = '_D' + (++dummyCount);
+          var node = {
+            width: a.width,
+            height: a.height,
+            edge: { id: e, source: s, target: t, attrs: a },
+            rank: rank,
+            dummy: true
+          };
+
+          // If this node represents a bend then we will use it as a control
+          // point. For edges with 2 segments this will be the center dummy
+          // node. For edges with more than two segments, this will be the
+          // first and last dummy node.
+          if (i === 0) node.index = 0;
+          else if (rank + 1 === targetRank) node.index = 1;
+
+          g.addNode(v, node);
+          g.addEdge(null, u, v, {});
+          u = v;
+        }
+        g.addEdge(null, u, t, {});
+        g.delEdge(e);
+      }
+    });
+  }
+
+  /*
+   * Reconstructs the graph as it was before normalization. The positions of
+   * dummy nodes are used to build an array of points for the original 'long'
+   * edge. Dummy nodes and edges are removed.
+   */
+  function undoNormalize(g) {
+    g.eachNode(function(u, a) {
+      if (a.dummy) {
+        if ('index' in a) {
+          var edge = a.edge;
+          if (!g.hasEdge(edge.id)) {
+            g.addEdge(edge.id, edge.source, edge.target, edge.attrs);
+          }
+          var points = g.edge(edge.id).points;
+          points[a.index] = { x: a.x, y: a.y, ul: a.ul, ur: a.ur, dl: a.dl, dr: a.dr };
+        }
+        g.delNode(u);
+      }
+    });
+  }
+
+  /*
+   * For each edge that was reversed during the `acyclic` step, reverse its
+   * array of points.
+   */
+  function fixupEdgePoints(g) {
+    g.eachEdge(function(e, s, t, a) { if (a.reversed) a.points.reverse(); });
+  }
+
+  function createFinalGraph(g, isDirected) {
+    var out = isDirected ? new CDigraph() : new CGraph();
+    out.graph(g.graph());
+    g.eachNode(function(u, value) { out.addNode(u, value); });
+    g.eachNode(function(u) { out.parent(u, g.parent(u)); });
+    g.eachEdge(function(e, u, v, value) {
+      out.addEdge(value.e, u, v, value);
+    });
+
+    // Attach bounding box information
+    var maxX = 0, maxY = 0;
+    g.eachNode(function(u, value) {
+      if (!g.children(u).length) {
+        maxX = Math.max(maxX, value.x + value.width / 2);
+        maxY = Math.max(maxY, value.y + value.height / 2);
+      }
+    });
+    g.eachEdge(function(e, u, v, value) {
+      var maxXPoints = Math.max.apply(Math, value.points.map(function(p) { return p.x; }));
+      var maxYPoints = Math.max.apply(Math, value.points.map(function(p) { return p.y; }));
+      maxX = Math.max(maxX, maxXPoints + value.width / 2);
+      maxY = Math.max(maxY, maxYPoints + value.height / 2);
+    });
+    out.graph().width = maxX;
+    out.graph().height = maxY;
+
+    return out;
+  }
+
+  /*
+   * Given a function, a new function is returned that invokes the given
+   * function. The return value from the function is always the `self` object.
+   */
+  function delegateProperty(f) {
+    return function() {
+      if (!arguments.length) return f();
+      f.apply(null, arguments);
+      return self;
+    };
+  }
+};
+
+
+},{"./order":4,"./position":9,"./rank":10,"./util":17,"graphlib":24}],4:[function(require,module,exports){
+var util = require('./util'),
+    crossCount = require('./order/crossCount'),
+    initLayerGraphs = require('./order/initLayerGraphs'),
+    initOrder = require('./order/initOrder'),
+    sortLayer = require('./order/sortLayer');
+
+module.exports = order;
+
+// The maximum number of sweeps to perform before finishing the order phase.
+var DEFAULT_MAX_SWEEPS = 24;
+order.DEFAULT_MAX_SWEEPS = DEFAULT_MAX_SWEEPS;
+
+/*
+ * Runs the order phase with the specified `graph, `maxSweeps`, and
+ * `debugLevel`. If `maxSweeps` is not specified we use `DEFAULT_MAX_SWEEPS`.
+ * If `debugLevel` is not set we assume 0.
+ */
+function order(g, maxSweeps) {
+  if (arguments.length < 2) {
+    maxSweeps = DEFAULT_MAX_SWEEPS;
+  }
+
+  var restarts = g.graph().orderRestarts || 0;
+
+  var layerGraphs = initLayerGraphs(g);
+  // TODO: remove this when we add back support for ordering clusters
+  layerGraphs.forEach(function(lg) {
+    lg = lg.filterNodes(function(u) { return !g.children(u).length; });
+  });
+
+  var iters = 0,
+      currentBestCC,
+      allTimeBestCC = Number.MAX_VALUE,
+      allTimeBest = {};
+
+  function saveAllTimeBest() {
+    g.eachNode(function(u, value) { allTimeBest[u] = value.order; });
+  }
+
+  for (var j = 0; j < Number(restarts) + 1 && allTimeBestCC !== 0; ++j) {
+    currentBestCC = Number.MAX_VALUE;
+    initOrder(g, restarts > 0);
+
+    util.log(2, 'Order phase start cross count: ' + g.graph().orderInitCC);
+
+    var i, lastBest, cc;
+    for (i = 0, lastBest = 0; lastBest < 4 && i < maxSweeps && currentBestCC > 0; ++i, ++lastBest, ++iters) {
+      sweep(g, layerGraphs, i);
+      cc = crossCount(g);
+      if (cc < currentBestCC) {
+        lastBest = 0;
+        currentBestCC = cc;
+        if (cc < allTimeBestCC) {
+          saveAllTimeBest();
+          allTimeBestCC = cc;
+        }
+      }
+      util.log(3, 'Order phase start ' + j + ' iter ' + i + ' cross count: ' + cc);
+    }
+  }
+
+  Object.keys(allTimeBest).forEach(function(u) {
+    if (!g.children || !g.children(u).length) {
+      g.node(u).order = allTimeBest[u];
+    }
+  });
+  g.graph().orderCC = allTimeBestCC;
+
+  util.log(2, 'Order iterations: ' + iters);
+  util.log(2, 'Order phase best cross count: ' + g.graph().orderCC);
+}
+
+function predecessorWeights(g, nodes) {
+  var weights = {};
+  nodes.forEach(function(u) {
+    weights[u] = g.inEdges(u).map(function(e) {
+      return g.node(g.source(e)).order;
+    });
+  });
+  return weights;
+}
+
+function successorWeights(g, nodes) {
+  var weights = {};
+  nodes.forEach(function(u) {
+    weights[u] = g.outEdges(u).map(function(e) {
+      return g.node(g.target(e)).order;
+    });
+  });
+  return weights;
+}
+
+function sweep(g, layerGraphs, iter) {
+  if (iter % 2 === 0) {
+    sweepDown(g, layerGraphs, iter);
+  } else {
+    sweepUp(g, layerGraphs, iter);
+  }
+}
+
+function sweepDown(g, layerGraphs) {
+  var cg;
+  for (i = 1; i < layerGraphs.length; ++i) {
+    cg = sortLayer(layerGraphs[i], cg, predecessorWeights(g, layerGraphs[i].nodes()));
+  }
+}
+
+function sweepUp(g, layerGraphs) {
+  var cg;
+  for (i = layerGraphs.length - 2; i >= 0; --i) {
+    sortLayer(layerGraphs[i], cg, successorWeights(g, layerGraphs[i].nodes()));
+  }
+}
+
+},{"./order/crossCount":5,"./order/initLayerGraphs":6,"./order/initOrder":7,"./order/sortLayer":8,"./util":17}],5:[function(require,module,exports){
+var util = require('../util');
+
+module.exports = crossCount;
+
+/*
+ * Returns the cross count for the given graph.
+ */
+function crossCount(g) {
+  var cc = 0;
+  var ordering = util.ordering(g);
+  for (var i = 1; i < ordering.length; ++i) {
+    cc += twoLayerCrossCount(g, ordering[i-1], ordering[i]);
+  }
+  return cc;
+}
+
+/*
+ * This function searches through a ranked and ordered graph and counts the
+ * number of edges that cross. This algorithm is derived from:
+ *
+ *    W. Barth et al., Bilayer Cross Counting, JGAA, 8(2) 179–194 (2004)
+ */
+function twoLayerCrossCount(g, layer1, layer2) {
+  var indices = [];
+  layer1.forEach(function(u) {
+    var nodeIndices = [];
+    g.outEdges(u).forEach(function(e) { nodeIndices.push(g.node(g.target(e)).order); });
+    nodeIndices.sort(function(x, y) { return x - y; });
+    indices = indices.concat(nodeIndices);
+  });
+
+  var firstIndex = 1;
+  while (firstIndex < layer2.length) firstIndex <<= 1;
+
+  var treeSize = 2 * firstIndex - 1;
+  firstIndex -= 1;
+
+  var tree = [];
+  for (var i = 0; i < treeSize; ++i) { tree[i] = 0; }
+
+  var cc = 0;
+  indices.forEach(function(i) {
+    var treeIndex = i + firstIndex;
+    ++tree[treeIndex];
+    while (treeIndex > 0) {
+      if (treeIndex % 2) {
+        cc += tree[treeIndex + 1];
+      }
+      treeIndex = (treeIndex - 1) >> 1;
+      ++tree[treeIndex];
+    }
+  });
+
+  return cc;
+}
+
+},{"../util":17}],6:[function(require,module,exports){
+var nodesFromList = require('graphlib').filter.nodesFromList,
+    /* jshint -W079 */
+    Set = require('cp-data').Set;
+
+module.exports = initLayerGraphs;
+
+/*
+ * This function takes a compound layered graph, g, and produces an array of
+ * layer graphs. Each entry in the array represents a subgraph of nodes
+ * relevant for performing crossing reduction on that layer.
+ */
+function initLayerGraphs(g) {
+  var ranks = [];
+
+  function dfs(u) {
+    if (u === null) {
+      g.children(u).forEach(function(v) { dfs(v); });
+      return;
+    }
+
+    var value = g.node(u);
+    value.minRank = ('rank' in value) ? value.rank : Number.MAX_VALUE;
+    value.maxRank = ('rank' in value) ? value.rank : Number.MIN_VALUE;
+    var uRanks = new Set();
+    g.children(u).forEach(function(v) {
+      var rs = dfs(v);
+      uRanks = Set.union([uRanks, rs]);
+      value.minRank = Math.min(value.minRank, g.node(v).minRank);
+      value.maxRank = Math.max(value.maxRank, g.node(v).maxRank);
+    });
+
+    if ('rank' in value) uRanks.add(value.rank);
+
+    uRanks.keys().forEach(function(r) {
+      if (!(r in ranks)) ranks[r] = [];
+      ranks[r].push(u);
+    });
+
+    return uRanks;
+  }
+  dfs(null);
+
+  var layerGraphs = [];
+  ranks.forEach(function(us, rank) {
+    layerGraphs[rank] = g.filterNodes(nodesFromList(us));
+  });
+
+  return layerGraphs;
+}
+
+},{"cp-data":19,"graphlib":24}],7:[function(require,module,exports){
+var crossCount = require('./crossCount'),
+    util = require('../util');
+
+module.exports = initOrder;
+
+/*
+ * Given a graph with a set of layered nodes (i.e. nodes that have a `rank`
+ * attribute) this function attaches an `order` attribute that uniquely
+ * arranges each node of each rank. If no constraint graph is provided the
+ * order of the nodes in each rank is entirely arbitrary.
+ */
+function initOrder(g, random) {
+  var layers = [];
+
+  g.eachNode(function(u, value) {
+    var layer = layers[value.rank];
+    if (g.children && g.children(u).length > 0) return;
+    if (!layer) {
+      layer = layers[value.rank] = [];
+    }
+    layer.push(u);
+  });
+
+  layers.forEach(function(layer) {
+    if (random) {
+      util.shuffle(layer);
+    }
+    layer.forEach(function(u, i) {
+      g.node(u).order = i;
+    });
+  });
+
+  var cc = crossCount(g);
+  g.graph().orderInitCC = cc;
+  g.graph().orderCC = Number.MAX_VALUE;
+}
+
+},{"../util":17,"./crossCount":5}],8:[function(require,module,exports){
+var util = require('../util');
+/*
+    Digraph = require('graphlib').Digraph,
+    topsort = require('graphlib').alg.topsort,
+    nodesFromList = require('graphlib').filter.nodesFromList;
+*/
+
+module.exports = sortLayer;
+
+/*
+function sortLayer(g, cg, weights) {
+  var result = sortLayerSubgraph(g, null, cg, weights);
+  result.list.forEach(function(u, i) {
+    g.node(u).order = i;
+  });
+  return result.constraintGraph;
+}
+*/
+
+function sortLayer(g, cg, weights) {
+  var ordering = [];
+  var bs = {};
+  g.eachNode(function(u, value) {
+    ordering[value.order] = u;
+    var ws = weights[u];
+    if (ws.length) {
+      bs[u] = util.sum(ws) / ws.length;
+    }
+  });
+
+  var toSort = g.nodes().filter(function(u) { return bs[u] !== undefined; });
+  toSort.sort(function(x, y) {
+    return bs[x] - bs[y] || g.node(x).order - g.node(y).order;
+  });
+
+  for (var i = 0, j = 0, jl = toSort.length; j < jl; ++i) {
+    if (bs[ordering[i]] !== undefined) {
+      g.node(toSort[j++]).order = i;
+    }
+  }
+}
+
+// TOOD: re-enable constrained sorting once we have a strategy for handling
+// undefined barycenters.
+/*
+function sortLayerSubgraph(g, sg, cg, weights) {
+  cg = cg ? cg.filterNodes(nodesFromList(g.children(sg))) : new Digraph();
+
+  var nodeData = {};
+  g.children(sg).forEach(function(u) {
+    if (g.children(u).length) {
+      nodeData[u] = sortLayerSubgraph(g, u, cg, weights);
+      nodeData[u].firstSG = u;
+      nodeData[u].lastSG = u;
+    } else {
+      var ws = weights[u];
+      nodeData[u] = {
+        degree: ws.length,
+        barycenter: ws.length > 0 ? util.sum(ws) / ws.length : 0,
+        list: [u]
+      };
+    }
+  });
+
+  resolveViolatedConstraints(g, cg, nodeData);
+
+  var keys = Object.keys(nodeData);
+  keys.sort(function(x, y) {
+    return nodeData[x].barycenter - nodeData[y].barycenter;
+  });
+
+  var result =  keys.map(function(u) { return nodeData[u]; })
+                    .reduce(function(lhs, rhs) { return mergeNodeData(g, lhs, rhs); });
+  return result;
+}
+
+/*
+function mergeNodeData(g, lhs, rhs) {
+  var cg = mergeDigraphs(lhs.constraintGraph, rhs.constraintGraph);
+
+  if (lhs.lastSG !== undefined && rhs.firstSG !== undefined) {
+    if (cg === undefined) {
+      cg = new Digraph();
+    }
+    if (!cg.hasNode(lhs.lastSG)) { cg.addNode(lhs.lastSG); }
+    cg.addNode(rhs.firstSG);
+    cg.addEdge(null, lhs.lastSG, rhs.firstSG);
+  }
+
+  return {
+    degree: lhs.degree + rhs.degree,
+    barycenter: (lhs.barycenter * lhs.degree + rhs.barycenter * rhs.degree) /
+                (lhs.degree + rhs.degree),
+    list: lhs.list.concat(rhs.list),
+    firstSG: lhs.firstSG !== undefined ? lhs.firstSG : rhs.firstSG,
+    lastSG: rhs.lastSG !== undefined ? rhs.lastSG : lhs.lastSG,
+    constraintGraph: cg
+  };
+}
+
+function mergeDigraphs(lhs, rhs) {
+  if (lhs === undefined) return rhs;
+  if (rhs === undefined) return lhs;
+
+  lhs = lhs.copy();
+  rhs.nodes().forEach(function(u) { lhs.addNode(u); });
+  rhs.edges().forEach(function(e, u, v) { lhs.addEdge(null, u, v); });
+  return lhs;
+}
+
+function resolveViolatedConstraints(g, cg, nodeData) {
+  // Removes nodes `u` and `v` from `cg` and makes any edges incident on them
+  // incident on `w` instead.
+  function collapseNodes(u, v, w) {
+    // TODO original paper removes self loops, but it is not obvious when this would happen
+    cg.inEdges(u).forEach(function(e) {
+      cg.delEdge(e);
+      cg.addEdge(null, cg.source(e), w);
+    });
+
+    cg.outEdges(v).forEach(function(e) {
+      cg.delEdge(e);
+      cg.addEdge(null, w, cg.target(e));
+    });
+
+    cg.delNode(u);
+    cg.delNode(v);
+  }
+
+  var violated;
+  while ((violated = findViolatedConstraint(cg, nodeData)) !== undefined) {
+    var source = cg.source(violated),
+        target = cg.target(violated);
+
+    var v;
+    while ((v = cg.addNode(null)) && g.hasNode(v)) {
+      cg.delNode(v);
+    }
+
+    // Collapse barycenter and list
+    nodeData[v] = mergeNodeData(g, nodeData[source], nodeData[target]);
+    delete nodeData[source];
+    delete nodeData[target];
+
+    collapseNodes(source, target, v);
+    if (cg.incidentEdges(v).length === 0) { cg.delNode(v); }
+  }
+}
+
+function findViolatedConstraint(cg, nodeData) {
+  var us = topsort(cg);
+  for (var i = 0; i < us.length; ++i) {
+    var u = us[i];
+    var inEdges = cg.inEdges(u);
+    for (var j = 0; j < inEdges.length; ++j) {
+      var e = inEdges[j];
+      if (nodeData[cg.source(e)].barycenter >= nodeData[u].barycenter) {
+        return e;
+      }
+    }
+  }
+}
+*/
+
+},{"../util":17}],9:[function(require,module,exports){
+var util = require('./util');
+
+/*
+ * The algorithms here are based on Brandes and Köpf, "Fast and Simple
+ * Horizontal Coordinate Assignment".
+ */
+module.exports = function() {
+  // External configuration
+  var config = {
+    nodeSep: 50,
+    edgeSep: 10,
+    universalSep: null,
+    rankSep: 30
+  };
+
+  var self = {};
+
+  self.nodeSep = util.propertyAccessor(self, config, 'nodeSep');
+  self.edgeSep = util.propertyAccessor(self, config, 'edgeSep');
+  // If not null this separation value is used for all nodes and edges
+  // regardless of their widths. `nodeSep` and `edgeSep` are ignored with this
+  // option.
+  self.universalSep = util.propertyAccessor(self, config, 'universalSep');
+  self.rankSep = util.propertyAccessor(self, config, 'rankSep');
+  self.debugLevel = util.propertyAccessor(self, config, 'debugLevel');
+
+  self.run = run;
+
+  return self;
+
+  function run(g) {
+    g = g.filterNodes(util.filterNonSubgraphs(g));
+
+    var layering = util.ordering(g);
+
+    var conflicts = findConflicts(g, layering);
+
+    var xss = {};
+    ['u', 'd'].forEach(function(vertDir) {
+      if (vertDir === 'd') layering.reverse();
+
+      ['l', 'r'].forEach(function(horizDir) {
+        if (horizDir === 'r') reverseInnerOrder(layering);
+
+        var dir = vertDir + horizDir;
+        var align = verticalAlignment(g, layering, conflicts, vertDir === 'u' ? 'predecessors' : 'successors');
+        xss[dir]= horizontalCompaction(g, layering, align.pos, align.root, align.align);
+
+        if (config.debugLevel >= 3)
+          debugPositioning(vertDir + horizDir, g, layering, xss[dir]);
+
+        if (horizDir === 'r') flipHorizontally(xss[dir]);
+
+        if (horizDir === 'r') reverseInnerOrder(layering);
+      });
+
+      if (vertDir === 'd') layering.reverse();
+    });
+
+    balance(g, layering, xss);
+
+    g.eachNode(function(v) {
+      var xs = [];
+      for (var alignment in xss) {
+        var alignmentX = xss[alignment][v];
+        posXDebug(alignment, g, v, alignmentX);
+        xs.push(alignmentX);
+      }
+      xs.sort(function(x, y) { return x - y; });
+      posX(g, v, (xs[1] + xs[2]) / 2);
+    });
+
+    // Align y coordinates with ranks
+    var y = 0, reverseY = g.graph().rankDir === 'BT' || g.graph().rankDir === 'RL';
+    layering.forEach(function(layer) {
+      var maxHeight = util.max(layer.map(function(u) { return height(g, u); }));
+      y += maxHeight / 2;
+      layer.forEach(function(u) {
+        posY(g, u, reverseY ? -y : y);
+      });
+      y += maxHeight / 2 + config.rankSep;
+    });
+
+    // Translate layout so that top left corner of bounding rectangle has
+    // coordinate (0, 0).
+    var minX = util.min(g.nodes().map(function(u) { return posX(g, u) - width(g, u) / 2; }));
+    var minY = util.min(g.nodes().map(function(u) { return posY(g, u) - height(g, u) / 2; }));
+    g.eachNode(function(u) {
+      posX(g, u, posX(g, u) - minX);
+      posY(g, u, posY(g, u) - minY);
+    });
+  }
+
+  /*
+   * Generate an ID that can be used to represent any undirected edge that is
+   * incident on `u` and `v`.
+   */
+  function undirEdgeId(u, v) {
+    return u < v
+      ? u.toString().length + ':' + u + '-' + v
+      : v.toString().length + ':' + v + '-' + u;
+  }
+
+  function findConflicts(g, layering) {
+    var conflicts = {}, // Set of conflicting edge ids
+        pos = {},       // Position of node in its layer
+        prevLayer,
+        currLayer,
+        k0,     // Position of the last inner segment in the previous layer
+        l,      // Current position in the current layer (for iteration up to `l1`)
+        k1;     // Position of the next inner segment in the previous layer or
+                // the position of the last element in the previous layer
+
+    if (layering.length <= 2) return conflicts;
+
+    function updateConflicts(v) {
+      var k = pos[v];
+      if (k < k0 || k > k1) {
+        conflicts[undirEdgeId(currLayer[l], v)] = true;
+      }
+    }
+
+    layering[1].forEach(function(u, i) { pos[u] = i; });
+    for (var i = 1; i < layering.length - 1; ++i) {
+      prevLayer = layering[i];
+      currLayer = layering[i+1];
+      k0 = 0;
+      l = 0;
+
+      // Scan current layer for next node that is incident to an inner segement
+      // between layering[i+1] and layering[i].
+      for (var l1 = 0; l1 < currLayer.length; ++l1) {
+        var u = currLayer[l1]; // Next inner segment in the current layer or
+                               // last node in the current layer
+        pos[u] = l1;
+        k1 = undefined;
+
+        if (g.node(u).dummy) {
+          var uPred = g.predecessors(u)[0];
+          // Note: In the case of self loops and sideways edges it is possible
+          // for a dummy not to have a predecessor.
+          if (uPred !== undefined && g.node(uPred).dummy)
+            k1 = pos[uPred];
+        }
+        if (k1 === undefined && l1 === currLayer.length - 1)
+          k1 = prevLayer.length - 1;
+
+        if (k1 !== undefined) {
+          for (; l <= l1; ++l) {
+            g.predecessors(currLayer[l]).forEach(updateConflicts);
+          }
+          k0 = k1;
+        }
+      }
+    }
+
+    return conflicts;
+  }
+
+  function verticalAlignment(g, layering, conflicts, relationship) {
+    var pos = {},   // Position for a node in its layer
+        root = {},  // Root of the block that the node participates in
+        align = {}; // Points to the next node in the block or, if the last
+                    // element in the block, points to the first block's root
+
+    layering.forEach(function(layer) {
+      layer.forEach(function(u, i) {
+        root[u] = u;
+        align[u] = u;
+        pos[u] = i;
+      });
+    });
+
+    layering.forEach(function(layer) {
+      var prevIdx = -1;
+      layer.forEach(function(v) {
+        var related = g[relationship](v), // Adjacent nodes from the previous layer
+            mid;                          // The mid point in the related array
+
+        if (related.length > 0) {
+          related.sort(function(x, y) { return pos[x] - pos[y]; });
+          mid = (related.length - 1) / 2;
+          related.slice(Math.floor(mid), Math.ceil(mid) + 1).forEach(function(u) {
+            if (align[v] === v) {
+              if (!conflicts[undirEdgeId(u, v)] && prevIdx < pos[u]) {
+                align[u] = v;
+                align[v] = root[v] = root[u];
+                prevIdx = pos[u];
+              }
+            }
+          });
+        }
+      });
+    });
+
+    return { pos: pos, root: root, align: align };
+  }
+
+  // This function deviates from the standard BK algorithm in two ways. First
+  // it takes into account the size of the nodes. Second it includes a fix to
+  // the original algorithm that is described in Carstens, "Node and Label
+  // Placement in a Layered Layout Algorithm".
+  function horizontalCompaction(g, layering, pos, root, align) {
+    var sink = {},       // Mapping of node id -> sink node id for class
+        maybeShift = {}, // Mapping of sink node id -> { class node id, min shift }
+        shift = {},      // Mapping of sink node id -> shift
+        pred = {},       // Mapping of node id -> predecessor node (or null)
+        xs = {};         // Calculated X positions
+
+    layering.forEach(function(layer) {
+      layer.forEach(function(u, i) {
+        sink[u] = u;
+        maybeShift[u] = {};
+        if (i > 0)
+          pred[u] = layer[i - 1];
+      });
+    });
+
+    function updateShift(toShift, neighbor, delta) {
+      if (!(neighbor in maybeShift[toShift])) {
+        maybeShift[toShift][neighbor] = delta;
+      } else {
+        maybeShift[toShift][neighbor] = Math.min(maybeShift[toShift][neighbor], delta);
+      }
+    }
+
+    function placeBlock(v) {
+      if (!(v in xs)) {
+        xs[v] = 0;
+        var w = v;
+        do {
+          if (pos[w] > 0) {
+            var u = root[pred[w]];
+            placeBlock(u);
+            if (sink[v] === v) {
+              sink[v] = sink[u];
+            }
+            var delta = sep(g, pred[w]) + sep(g, w);
+            if (sink[v] !== sink[u]) {
+              updateShift(sink[u], sink[v], xs[v] - xs[u] - delta);
+            } else {
+              xs[v] = Math.max(xs[v], xs[u] + delta);
+            }
+          }
+          w = align[w];
+        } while (w !== v);
+      }
+    }
+
+    // Root coordinates relative to sink
+    util.values(root).forEach(function(v) {
+      placeBlock(v);
+    });
+
+    // Absolute coordinates
+    // There is an assumption here that we've resolved shifts for any classes
+    // that begin at an earlier layer. We guarantee this by visiting layers in
+    // order.
+    layering.forEach(function(layer) {
+      layer.forEach(function(v) {
+        xs[v] = xs[root[v]];
+        if (v === root[v] && v === sink[v]) {
+          var minShift = 0;
+          if (v in maybeShift && Object.keys(maybeShift[v]).length > 0) {
+            minShift = util.min(Object.keys(maybeShift[v])
+                                 .map(function(u) {
+                                      return maybeShift[v][u] + (u in shift ? shift[u] : 0);
+                                      }
+                                 ));
+          }
+          shift[v] = minShift;
+        }
+      });
+    });
+
+    layering.forEach(function(layer) {
+      layer.forEach(function(v) {
+        xs[v] += shift[sink[root[v]]] || 0;
+      });
+    });
+
+    return xs;
+  }
+
+  function findMinCoord(g, layering, xs) {
+    return util.min(layering.map(function(layer) {
+      var u = layer[0];
+      return xs[u];
+    }));
+  }
+
+  function findMaxCoord(g, layering, xs) {
+    return util.max(layering.map(function(layer) {
+      var u = layer[layer.length - 1];
+      return xs[u];
+    }));
+  }
+
+  function balance(g, layering, xss) {
+    var min = {},                            // Min coordinate for the alignment
+        max = {},                            // Max coordinate for the alginment
+        smallestAlignment,
+        shift = {};                          // Amount to shift a given alignment
+
+    function updateAlignment(v) {
+      xss[alignment][v] += shift[alignment];
+    }
+
+    var smallest = Number.POSITIVE_INFINITY;
+    for (var alignment in xss) {
+      var xs = xss[alignment];
+      min[alignment] = findMinCoord(g, layering, xs);
+      max[alignment] = findMaxCoord(g, layering, xs);
+      var w = max[alignment] - min[alignment];
+      if (w < smallest) {
+        smallest = w;
+        smallestAlignment = alignment;
+      }
+    }
+
+    // Determine how much to adjust positioning for each alignment
+    ['u', 'd'].forEach(function(vertDir) {
+      ['l', 'r'].forEach(function(horizDir) {
+        var alignment = vertDir + horizDir;
+        shift[alignment] = horizDir === 'l'
+            ? min[smallestAlignment] - min[alignment]
+            : max[smallestAlignment] - max[alignment];
+      });
+    });
+
+    // Find average of medians for xss array
+    for (alignment in xss) {
+      g.eachNode(updateAlignment);
+    }
+  }
+
+  function flipHorizontally(xs) {
+    for (var u in xs) {
+      xs[u] = -xs[u];
+    }
+  }
+
+  function reverseInnerOrder(layering) {
+    layering.forEach(function(layer) {
+      layer.reverse();
+    });
+  }
+
+  function width(g, u) {
+    switch (g.graph().rankDir) {
+      case 'LR': return g.node(u).height;
+      case 'RL': return g.node(u).height;
+      default:   return g.node(u).width;
+    }
+  }
+
+  function height(g, u) {
+    switch(g.graph().rankDir) {
+      case 'LR': return g.node(u).width;
+      case 'RL': return g.node(u).width;
+      default:   return g.node(u).height;
+    }
+  }
+
+  function sep(g, u) {
+    if (config.universalSep !== null) {
+      return config.universalSep;
+    }
+    var w = width(g, u);
+    var s = g.node(u).dummy ? config.edgeSep : config.nodeSep;
+    return (w + s) / 2;
+  }
+
+  function posX(g, u, x) {
+    if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') {
+      if (arguments.length < 3) {
+        return g.node(u).y;
+      } else {
+        g.node(u).y = x;
+      }
+    } else {
+      if (arguments.length < 3) {
+        return g.node(u).x;
+      } else {
+        g.node(u).x = x;
+      }
+    }
+  }
+
+  function posXDebug(name, g, u, x) {
+    if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') {
+      if (arguments.length < 3) {
+        return g.node(u)[name];
+      } else {
+        g.node(u)[name] = x;
+      }
+    } else {
+      if (arguments.length < 3) {
+        return g.node(u)[name];
+      } else {
+        g.node(u)[name] = x;
+      }
+    }
+  }
+
+  function posY(g, u, y) {
+    if (g.graph().rankDir === 'LR' || g.graph().rankDir === 'RL') {
+      if (arguments.length < 3) {
+        return g.node(u).x;
+      } else {
+        g.node(u).x = y;
+      }
+    } else {
+      if (arguments.length < 3) {
+        return g.node(u).y;
+      } else {
+        g.node(u).y = y;
+      }
+    }
+  }
+
+  function debugPositioning(align, g, layering, xs) {
+    layering.forEach(function(l, li) {
+      var u, xU;
+      l.forEach(function(v) {
+        var xV = xs[v];
+        if (u) {
+          var s = sep(g, u) + sep(g, v);
+          if (xV - xU < s)
+            console.log('Position phase: sep violation. Align: ' + align + '. Layer: ' + li + '. ' +
+              'U: ' + u + ' V: ' + v + '. Actual sep: ' + (xV - xU) + ' Expected sep: ' + s);
+        }
+        u = v;
+        xU = xV;
+      });
+    });
+  }
+};
+
+},{"./util":17}],10:[function(require,module,exports){
+var util = require('./util'),
+    acyclic = require('./rank/acyclic'),
+    initRank = require('./rank/initRank'),
+    feasibleTree = require('./rank/feasibleTree'),
+    constraints = require('./rank/constraints'),
+    simplex = require('./rank/simplex'),
+    components = require('graphlib').alg.components,
+    filter = require('graphlib').filter;
+
+exports.run = run;
+exports.restoreEdges = restoreEdges;
+
+/*
+ * Heuristic function that assigns a rank to each node of the input graph with
+ * the intent of minimizing edge lengths, while respecting the `minLen`
+ * attribute of incident edges.
+ *
+ * Prerequisites:
+ *
+ *  * Each edge in the input graph must have an assigned 'minLen' attribute
+ */
+function run(g, useSimplex) {
+  expandSelfLoops(g);
+
+  // If there are rank constraints on nodes, then build a new graph that
+  // encodes the constraints.
+  util.time('constraints.apply', constraints.apply)(g);
+
+  expandSidewaysEdges(g);
+
+  // Reverse edges to get an acyclic graph, we keep the graph in an acyclic
+  // state until the very end.
+  util.time('acyclic', acyclic)(g);
+
+  // Convert the graph into a flat graph for ranking
+  var flatGraph = g.filterNodes(util.filterNonSubgraphs(g));
+
+  // Assign an initial ranking using DFS.
+  initRank(flatGraph);
+
+  // For each component improve the assigned ranks.
+  components(flatGraph).forEach(function(cmpt) {
+    var subgraph = flatGraph.filterNodes(filter.nodesFromList(cmpt));
+    rankComponent(subgraph, useSimplex);
+  });
+
+  // Relax original constraints
+  util.time('constraints.relax', constraints.relax(g));
+
+  // When handling nodes with constrained ranks it is possible to end up with
+  // edges that point to previous ranks. Most of the subsequent algorithms assume
+  // that edges are pointing to successive ranks only. Here we reverse any "back
+  // edges" and mark them as such. The acyclic algorithm will reverse them as a
+  // post processing step.
+  util.time('reorientEdges', reorientEdges)(g);
+}
+
+function restoreEdges(g) {
+  acyclic.undo(g);
+}
+
+/*
+ * Expand self loops into three dummy nodes. One will sit above the incident
+ * node, one will be at the same level, and one below. The result looks like:
+ *
+ *         /--<--x--->--\
+ *     node              y
+ *         \--<--z--->--/
+ *
+ * Dummy nodes x, y, z give us the shape of a loop and node y is where we place
+ * the label.
+ *
+ * TODO: consolidate knowledge of dummy node construction.
+ * TODO: support minLen = 2
+ */
+function expandSelfLoops(g) {
+  g.eachEdge(function(e, u, v, a) {
+    if (u === v) {
+      var x = addDummyNode(g, e, u, v, a, 0, false),
+          y = addDummyNode(g, e, u, v, a, 1, true),
+          z = addDummyNode(g, e, u, v, a, 2, false);
+      g.addEdge(null, x, u, {minLen: 1, selfLoop: true});
+      g.addEdge(null, x, y, {minLen: 1, selfLoop: true});
+      g.addEdge(null, u, z, {minLen: 1, selfLoop: true});
+      g.addEdge(null, y, z, {minLen: 1, selfLoop: true});
+      g.delEdge(e);
+    }
+  });
+}
+
+function expandSidewaysEdges(g) {
+  g.eachEdge(function(e, u, v, a) {
+    if (u === v) {
+      var origEdge = a.originalEdge,
+          dummy = addDummyNode(g, origEdge.e, origEdge.u, origEdge.v, origEdge.value, 0, true);
+      g.addEdge(null, u, dummy, {minLen: 1});
+      g.addEdge(null, dummy, v, {minLen: 1});
+      g.delEdge(e);
+    }
+  });
+}
+
+function addDummyNode(g, e, u, v, a, index, isLabel) {
+  return g.addNode(null, {
+    width: isLabel ? a.width : 0,
+    height: isLabel ? a.height : 0,
+    edge: { id: e, source: u, target: v, attrs: a },
+    dummy: true,
+    index: index
+  });
+}
+
+function reorientEdges(g) {
+  g.eachEdge(function(e, u, v, value) {
+    if (g.node(u).rank > g.node(v).rank) {
+      g.delEdge(e);
+      value.reversed = true;
+      g.addEdge(e, v, u, value);
+    }
+  });
+}
+
+function rankComponent(subgraph, useSimplex) {
+  var spanningTree = feasibleTree(subgraph);
+
+  if (useSimplex) {
+    util.log(1, 'Using network simplex for ranking');
+    simplex(subgraph, spanningTree);
+  }
+  normalize(subgraph);
+}
+
+function normalize(g) {
+  var m = util.min(g.nodes().map(function(u) { return g.node(u).rank; }));
+  g.eachNode(function(u, node) { node.rank -= m; });
+}
+
+},{"./rank/acyclic":11,"./rank/constraints":12,"./rank/feasibleTree":13,"./rank/initRank":14,"./rank/simplex":16,"./util":17,"graphlib":24}],11:[function(require,module,exports){
+var util = require('../util');
+
+module.exports = acyclic;
+module.exports.undo = undo;
+
+/*
+ * This function takes a directed graph that may have cycles and reverses edges
+ * as appropriate to break these cycles. Each reversed edge is assigned a
+ * `reversed` attribute with the value `true`.
+ *
+ * There should be no self loops in the graph.
+ */
+function acyclic(g) {
+  var onStack = {},
+      visited = {},
+      reverseCount = 0;
+
+  function dfs(u) {
+    if (u in visited) return;
+    visited[u] = onStack[u] = true;
+    g.outEdges(u).forEach(function(e) {
+      var t = g.target(e),
+          value;
+
+      if (u === t) {
+        console.error('Warning: found self loop "' + e + '" for node "' + u + '"');
+      } else if (t in onStack) {
+        value = g.edge(e);
+        g.delEdge(e);
+        value.reversed = true;
+        ++reverseCount;
+        g.addEdge(e, t, u, value);
+      } else {
+        dfs(t);
+      }
+    });
+
+    delete onStack[u];
+  }
+
+  g.eachNode(function(u) { dfs(u); });
+
+  util.log(2, 'Acyclic Phase: reversed ' + reverseCount + ' edge(s)');
+
+  return reverseCount;
+}
+
+/*
+ * Given a graph that has had the acyclic operation applied, this function
+ * undoes that operation. More specifically, any edge with the `reversed`
+ * attribute is again reversed to restore the original direction of the edge.
+ */
+function undo(g) {
+  g.eachEdge(function(e, s, t, a) {
+    if (a.reversed) {
+      delete a.reversed;
+      g.delEdge(e);
+      g.addEdge(e, t, s, a);
+    }
+  });
+}
+
+},{"../util":17}],12:[function(require,module,exports){
+exports.apply = function(g) {
+  function dfs(sg) {
+    var rankSets = {};
+    g.children(sg).forEach(function(u) {
+      if (g.children(u).length) {
+        dfs(u);
+        return;
+      }
+
+      var value = g.node(u),
+          prefRank = value.prefRank;
+      if (prefRank !== undefined) {
+        if (!checkSupportedPrefRank(prefRank)) { return; }
+
+        if (!(prefRank in rankSets)) {
+          rankSets.prefRank = [u];
+        } else {
+          rankSets.prefRank.push(u);
+        }
+
+        var newU = rankSets[prefRank];
+        if (newU === undefined) {
+          newU = rankSets[prefRank] = g.addNode(null, { originalNodes: [] });
+          g.parent(newU, sg);
+        }
+
+        redirectInEdges(g, u, newU, prefRank === 'min');
+        redirectOutEdges(g, u, newU, prefRank === 'max');
+
+        // Save original node and remove it from reduced graph
+        g.node(newU).originalNodes.push({ u: u, value: value, parent: sg });
+        g.delNode(u);
+      }
+    });
+
+    addLightEdgesFromMinNode(g, sg, rankSets.min);
+    addLightEdgesToMaxNode(g, sg, rankSets.max);
+  }
+
+  dfs(null);
+};
+
+function checkSupportedPrefRank(prefRank) {
+  if (prefRank !== 'min' && prefRank !== 'max' && prefRank.indexOf('same_') !== 0) {
+    console.error('Unsupported rank type: ' + prefRank);
+    return false;
+  }
+  return true;
+}
+
+function redirectInEdges(g, u, newU, reverse) {
+  g.inEdges(u).forEach(function(e) {
+    var origValue = g.edge(e),
+        value;
+    if (origValue.originalEdge) {
+      value = origValue;
+    } else {
+      value =  {
+        originalEdge: { e: e, u: g.source(e), v: g.target(e), value: origValue },
+        minLen: g.edge(e).minLen
+      };
+    }
+
+    // Do not reverse edges for self-loops.
+    if (origValue.selfLoop) {
+      reverse = false;
+    }
+
+    if (reverse) {
+      // Ensure that all edges to min are reversed
+      g.addEdge(null, newU, g.source(e), value);
+      value.reversed = true;
+    } else {
+      g.addEdge(null, g.source(e), newU, value);
+    }
+  });
+}
+
+function redirectOutEdges(g, u, newU, reverse) {
+  g.outEdges(u).forEach(function(e) {
+    var origValue = g.edge(e),
+        value;
+    if (origValue.originalEdge) {
+      value = origValue;
+    } else {
+      value =  {
+        originalEdge: { e: e, u: g.source(e), v: g.target(e), value: origValue },
+        minLen: g.edge(e).minLen
+      };
+    }
+
+    // Do not reverse edges for self-loops.
+    if (origValue.selfLoop) {
+      reverse = false;
+    }
+
+    if (reverse) {
+      // Ensure that all edges from max are reversed
+      g.addEdge(null, g.target(e), newU, value);
+      value.reversed = true;
+    } else {
+      g.addEdge(null, newU, g.target(e), value);
+    }
+  });
+}
+
+function addLightEdgesFromMinNode(g, sg, minNode) {
+  if (minNode !== undefined) {
+    g.children(sg).forEach(function(u) {
+      // The dummy check ensures we don't add an edge if the node is involved
+      // in a self loop or sideways edge.
+      if (u !== minNode && !g.outEdges(minNode, u).length && !g.node(u).dummy) {
+        g.addEdge(null, minNode, u, { minLen: 0 });
+      }
+    });
+  }
+}
+
+function addLightEdgesToMaxNode(g, sg, maxNode) {
+  if (maxNode !== undefined) {
+    g.children(sg).forEach(function(u) {
+      // The dummy check ensures we don't add an edge if the node is involved
+      // in a self loop or sideways edge.
+      if (u !== maxNode && !g.outEdges(u, maxNode).length && !g.node(u).dummy) {
+        g.addEdge(null, u, maxNode, { minLen: 0 });
+      }
+    });
+  }
+}
+
+/*
+ * This function "relaxes" the constraints applied previously by the "apply"
+ * function. It expands any nodes that were collapsed and assigns the rank of
+ * the collapsed node to each of the expanded nodes. It also restores the
+ * original edges and removes any dummy edges pointing at the collapsed nodes.
+ *
+ * Note that the process of removing collapsed nodes also removes dummy edges
+ * automatically.
+ */
+exports.relax = function(g) {
+  // Save original edges
+  var originalEdges = [];
+  g.eachEdge(function(e, u, v, value) {
+    var originalEdge = value.originalEdge;
+    if (originalEdge) {
+      originalEdges.push(originalEdge);
+    }
+  });
+
+  // Expand collapsed nodes
+  g.eachNode(function(u, value) {
+    var originalNodes = value.originalNodes;
+    if (originalNodes) {
+      originalNodes.forEach(function(originalNode) {
+        originalNode.value.rank = value.rank;
+        g.addNode(originalNode.u, originalNode.value);
+        g.parent(originalNode.u, originalNode.parent);
+      });
+      g.delNode(u);
+    }
+  });
+
+  // Restore original edges
+  originalEdges.forEach(function(edge) {
+    g.addEdge(edge.e, edge.u, edge.v, edge.value);
+  });
+};
+
+},{}],13:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require('cp-data').Set,
+/* jshint +W079 */
+    Digraph = require('graphlib').Digraph,
+    util = require('../util');
+
+module.exports = feasibleTree;
+
+/*
+ * Given an acyclic graph with each node assigned a `rank` attribute, this
+ * function constructs and returns a spanning tree. This function may reduce
+ * the length of some edges from the initial rank assignment while maintaining
+ * the `minLen` specified by each edge.
+ *
+ * Prerequisites:
+ *
+ * * The input graph is acyclic
+ * * Each node in the input graph has an assigned `rank` attribute
+ * * Each edge in the input graph has an assigned `minLen` attribute
+ *
+ * Outputs:
+ *
+ * A feasible spanning tree for the input graph (i.e. a spanning tree that
+ * respects each graph edge's `minLen` attribute) represented as a Digraph with
+ * a `root` attribute on graph.
+ *
+ * Nodes have the same id and value as that in the input graph.
+ *
+ * Edges in the tree have arbitrarily assigned ids. The attributes for edges
+ * include `reversed`. `reversed` indicates that the edge is a
+ * back edge in the input graph.
+ */
+function feasibleTree(g) {
+  var remaining = new Set(g.nodes()),
+      tree = new Digraph();
+
+  if (remaining.size() === 1) {
+    var root = g.nodes()[0];
+    tree.addNode(root, {});
+    tree.graph({ root: root });
+    return tree;
+  }
+
+  function addTightEdges(v) {
+    var continueToScan = true;
+    g.predecessors(v).forEach(function(u) {
+      if (remaining.has(u) && !slack(g, u, v)) {
+        if (remaining.has(v)) {
+          tree.addNode(v, {});
+          remaining.remove(v);
+          tree.graph({ root: v });
+        }
+
+        tree.addNode(u, {});
+        tree.addEdge(null, u, v, { reversed: true });
+        remaining.remove(u);
+        addTightEdges(u);
+        continueToScan = false;
+      }
+    });
+
+    g.successors(v).forEach(function(w)  {
+      if (remaining.has(w) && !slack(g, v, w)) {
+        if (remaining.has(v)) {
+          tree.addNode(v, {});
+          remaining.remove(v);
+          tree.graph({ root: v });
+        }
+
+        tree.addNode(w, {});
+        tree.addEdge(null, v, w, {});
+        remaining.remove(w);
+        addTightEdges(w);
+        continueToScan = false;
+      }
+    });
+    return continueToScan;
+  }
+
+  function createTightEdge() {
+    var minSlack = Number.MAX_VALUE;
+    remaining.keys().forEach(function(v) {
+      g.predecessors(v).forEach(function(u) {
+        if (!remaining.has(u)) {
+          var edgeSlack = slack(g, u, v);
+          if (Math.abs(edgeSlack) < Math.abs(minSlack)) {
+            minSlack = -edgeSlack;
+          }
+        }
+      });
+
+      g.successors(v).forEach(function(w) {
+        if (!remaining.has(w)) {
+          var edgeSlack = slack(g, v, w);
+          if (Math.abs(edgeSlack) < Math.abs(minSlack)) {
+            minSlack = edgeSlack;
+          }
+        }
+      });
+    });
+
+    tree.eachNode(function(u) { g.node(u).rank -= minSlack; });
+  }
+
+  while (remaining.size()) {
+    var nodesToSearch = !tree.order() ? remaining.keys() : tree.nodes();
+    for (var i = 0, il = nodesToSearch.length;
+         i < il && addTightEdges(nodesToSearch[i]);
+         ++i);
+    if (remaining.size()) {
+      createTightEdge();
+    }
+  }
+
+  return tree;
+}
+
+function slack(g, u, v) {
+  var rankDiff = g.node(v).rank - g.node(u).rank;
+  var maxMinLen = util.max(g.outEdges(u, v)
+                            .map(function(e) { return g.edge(e).minLen; }));
+  return rankDiff - maxMinLen;
+}
+
+},{"../util":17,"cp-data":19,"graphlib":24}],14:[function(require,module,exports){
+var util = require('../util'),
+    topsort = require('graphlib').alg.topsort;
+
+module.exports = initRank;
+
+/*
+ * Assigns a `rank` attribute to each node in the input graph and ensures that
+ * this rank respects the `minLen` attribute of incident edges.
+ *
+ * Prerequisites:
+ *
+ *  * The input graph must be acyclic
+ *  * Each edge in the input graph must have an assigned 'minLen' attribute
+ */
+function initRank(g) {
+  var sorted = topsort(g);
+
+  sorted.forEach(function(u) {
+    var inEdges = g.inEdges(u);
+    if (inEdges.length === 0) {
+      g.node(u).rank = 0;
+      return;
+    }
+
+    var minLens = inEdges.map(function(e) {
+      return g.node(g.source(e)).rank + g.edge(e).minLen;
+    });
+    g.node(u).rank = util.max(minLens);
+  });
+}
+
+},{"../util":17,"graphlib":24}],15:[function(require,module,exports){
+module.exports = {
+  slack: slack
+};
+
+/*
+ * A helper to calculate the slack between two nodes (`u` and `v`) given a
+ * `minLen` constraint. The slack represents how much the distance between `u`
+ * and `v` could shrink while maintaining the `minLen` constraint. If the value
+ * is negative then the constraint is currently violated.
+ *
+  This function requires that `u` and `v` are in `graph` and they both have a
+  `rank` attribute.
+ */
+function slack(graph, u, v, minLen) {
+  return Math.abs(graph.node(u).rank - graph.node(v).rank) - minLen;
+}
+
+},{}],16:[function(require,module,exports){
+var util = require('../util'),
+    rankUtil = require('./rankUtil');
+
+module.exports = simplex;
+
+function simplex(graph, spanningTree) {
+  // The network simplex algorithm repeatedly replaces edges of
+  // the spanning tree with negative cut values until no such
+  // edge exists.
+  initCutValues(graph, spanningTree);
+  while (true) {
+    var e = leaveEdge(spanningTree);
+    if (e === null) break;
+    var f = enterEdge(graph, spanningTree, e);
+    exchange(graph, spanningTree, e, f);
+  }
+}
+
+/*
+ * Set the cut values of edges in the spanning tree by a depth-first
+ * postorder traversal.  The cut value corresponds to the cost, in
+ * terms of a ranking's edge length sum, of lengthening an edge.
+ * Negative cut values typically indicate edges that would yield a
+ * smaller edge length sum if they were lengthened.
+ */
+function initCutValues(graph, spanningTree) {
+  computeLowLim(spanningTree);
+
+  spanningTree.eachEdge(function(id, u, v, treeValue) {
+    treeValue.cutValue = 0;
+  });
+
+  // Propagate cut values up the tree.
+  function dfs(n) {
+    var children = spanningTree.successors(n);
+    for (var c in children) {
+      var child = children[c];
+      dfs(child);
+    }
+    if (n !== spanningTree.graph().root) {
+      setCutValue(graph, spanningTree, n);
+    }
+  }
+  dfs(spanningTree.graph().root);
+}
+
+/*
+ * Perform a DFS postorder traversal, labeling each node v with
+ * its traversal order 'lim(v)' and the minimum traversal number
+ * of any of its descendants 'low(v)'.  This provides an efficient
+ * way to test whether u is an ancestor of v since
+ * low(u) <= lim(v) <= lim(u) if and only if u is an ancestor.
+ */
+function computeLowLim(tree) {
+  var postOrderNum = 0;
+
+  function dfs(n) {
+    var children = tree.successors(n);
+    var low = postOrderNum;
+    for (var c in children) {
+      var child = children[c];
+      dfs(child);
+      low = Math.min(low, tree.node(child).low);
+    }
+    tree.node(n).low = low;
+    tree.node(n).lim = postOrderNum++;
+  }
+
+  dfs(tree.graph().root);
+}
+
+/*
+ * To compute the cut value of the edge parent -> child, we consider
+ * it and any other graph edges to or from the child.
+ *          parent
+ *             |
+ *           child
+ *          /      \
+ *         u        v
+ */
+function setCutValue(graph, tree, child) {
+  var parentEdge = tree.inEdges(child)[0];
+
+  // List of child's children in the spanning tree.
+  var grandchildren = [];
+  var grandchildEdges = tree.outEdges(child);
+  for (var gce in grandchildEdges) {
+    grandchildren.push(tree.target(grandchildEdges[gce]));
+  }
+
+  var cutValue = 0;
+
+  // TODO: Replace unit increment/decrement with edge weights.
+  var E = 0;    // Edges from child to grandchild's subtree.
+  var F = 0;    // Edges to child from grandchild's subtree.
+  var G = 0;    // Edges from child to nodes outside of child's subtree.
+  var H = 0;    // Edges from nodes outside of child's subtree to child.
+
+  // Consider all graph edges from child.
+  var outEdges = graph.outEdges(child);
+  var gc;
+  for (var oe in outEdges) {
+    var succ = graph.target(outEdges[oe]);
+    for (gc in grandchildren) {
+      if (inSubtree(tree, succ, grandchildren[gc])) {
+        E++;
+      }
+    }
+    if (!inSubtree(tree, succ, child)) {
+      G++;
+    }
+  }
+
+  // Consider all graph edges to child.
+  var inEdges = graph.inEdges(child);
+  for (var ie in inEdges) {
+    var pred = graph.source(inEdges[ie]);
+    for (gc in grandchildren) {
+      if (inSubtree(tree, pred, grandchildren[gc])) {
+        F++;
+      }
+    }
+    if (!inSubtree(tree, pred, child)) {
+      H++;
+    }
+  }
+
+  // Contributions depend on the alignment of the parent -> child edge
+  // and the child -> u or v edges.
+  var grandchildCutSum = 0;
+  for (gc in grandchildren) {
+    var cv = tree.edge(grandchildEdges[gc]).cutValue;
+    if (!tree.edge(grandchildEdges[gc]).reversed) {
+      grandchildCutSum += cv;
+    } else {
+      grandchildCutSum -= cv;
+    }
+  }
+
+  if (!tree.edge(parentEdge).reversed) {
+    cutValue += grandchildCutSum - E + F - G + H;
+  } else {
+    cutValue -= grandchildCutSum - E + F - G + H;
+  }
+
+  tree.edge(parentEdge).cutValue = cutValue;
+}
+
+/*
+ * Return whether n is a node in the subtree with the given
+ * root.
+ */
+function inSubtree(tree, n, root) {
+  return (tree.node(root).low <= tree.node(n).lim &&
+          tree.node(n).lim <= tree.node(root).lim);
+}
+
+/*
+ * Return an edge from the tree with a negative cut value, or null if there
+ * is none.
+ */
+function leaveEdge(tree) {
+  var edges = tree.edges();
+  for (var n in edges) {
+    var e = edges[n];
+    var treeValue = tree.edge(e);
+    if (treeValue.cutValue < 0) {
+      return e;
+    }
+  }
+  return null;
+}
+
+/*
+ * The edge e should be an edge in the tree, with an underlying edge
+ * in the graph, with a negative cut value.  Of the two nodes incident
+ * on the edge, take the lower one.  enterEdge returns an edge with
+ * minimum slack going from outside of that node's subtree to inside
+ * of that node's subtree.
+ */
+function enterEdge(graph, tree, e) {
+  var source = tree.source(e);
+  var target = tree.target(e);
+  var lower = tree.node(target).lim < tree.node(source).lim ? target : source;
+
+  // Is the tree edge aligned with the graph edge?
+  var aligned = !tree.edge(e).reversed;
+
+  var minSlack = Number.POSITIVE_INFINITY;
+  var minSlackEdge;
+  if (aligned) {
+    graph.eachEdge(function(id, u, v, value) {
+      if (id !== e && inSubtree(tree, u, lower) && !inSubtree(tree, v, lower)) {
+        var slack = rankUtil.slack(graph, u, v, value.minLen);
+        if (slack < minSlack) {
+          minSlack = slack;
+          minSlackEdge = id;
+        }
+      }
+    });
+  } else {
+    graph.eachEdge(function(id, u, v, value) {
+      if (id !== e && !inSubtree(tree, u, lower) && inSubtree(tree, v, lower)) {
+        var slack = rankUtil.slack(graph, u, v, value.minLen);
+        if (slack < minSlack) {
+          minSlack = slack;
+          minSlackEdge = id;
+        }
+      }
+    });
+  }
+
+  if (minSlackEdge === undefined) {
+    var outside = [];
+    var inside = [];
+    graph.eachNode(function(id) {
+      if (!inSubtree(tree, id, lower)) {
+        outside.push(id);
+      } else {
+        inside.push(id);
+      }
+    });
+    throw new Error('No edge found from outside of tree to inside');
+  }
+
+  return minSlackEdge;
+}
+
+/*
+ * Replace edge e with edge f in the tree, recalculating the tree root,
+ * the nodes' low and lim properties and the edges' cut values.
+ */
+function exchange(graph, tree, e, f) {
+  tree.delEdge(e);
+  var source = graph.source(f);
+  var target = graph.target(f);
+
+  // Redirect edges so that target is the root of its subtree.
+  function redirect(v) {
+    var edges = tree.inEdges(v);
+    for (var i in edges) {
+      var e = edges[i];
+      var u = tree.source(e);
+      var value = tree.edge(e);
+      redirect(u);
+      tree.delEdge(e);
+      value.reversed = !value.reversed;
+      tree.addEdge(e, v, u, value);
+    }
+  }
+
+  redirect(target);
+
+  var root = source;
+  var edges = tree.inEdges(root);
+  while (edges.length > 0) {
+    root = tree.source(edges[0]);
+    edges = tree.inEdges(root);
+  }
+
+  tree.graph().root = root;
+
+  tree.addEdge(null, source, target, {cutValue: 0});
+
+  initCutValues(graph, tree);
+
+  adjustRanks(graph, tree);
+}
+
+/*
+ * Reset the ranks of all nodes based on the current spanning tree.
+ * The rank of the tree's root remains unchanged, while all other
+ * nodes are set to the sum of minimum length constraints along
+ * the path from the root.
+ */
+function adjustRanks(graph, tree) {
+  function dfs(p) {
+    var children = tree.successors(p);
+    children.forEach(function(c) {
+      var minLen = minimumLength(graph, p, c);
+      graph.node(c).rank = graph.node(p).rank + minLen;
+      dfs(c);
+    });
+  }
+
+  dfs(tree.graph().root);
+}
+
+/*
+ * If u and v are connected by some edges in the graph, return the
+ * minimum length of those edges, as a positive number if v succeeds
+ * u and as a negative number if v precedes u.
+ */
+function minimumLength(graph, u, v) {
+  var outEdges = graph.outEdges(u, v);
+  if (outEdges.length > 0) {
+    return util.max(outEdges.map(function(e) {
+      return graph.edge(e).minLen;
+    }));
+  }
+
+  var inEdges = graph.inEdges(u, v);
+  if (inEdges.length > 0) {
+    return -util.max(inEdges.map(function(e) {
+      return graph.edge(e).minLen;
+    }));
+  }
+}
+
+},{"../util":17,"./rankUtil":15}],17:[function(require,module,exports){
+/*
+ * Returns the smallest value in the array.
+ */
+exports.min = function(values) {
+  return Math.min.apply(Math, values);
+};
+
+/*
+ * Returns the largest value in the array.
+ */
+exports.max = function(values) {
+  return Math.max.apply(Math, values);
+};
+
+/*
+ * Returns `true` only if `f(x)` is `true` for all `x` in `xs`. Otherwise
+ * returns `false`. This function will return immediately if it finds a
+ * case where `f(x)` does not hold.
+ */
+exports.all = function(xs, f) {
+  for (var i = 0; i < xs.length; ++i) {
+    if (!f(xs[i])) {
+      return false;
+    }
+  }
+  return true;
+};
+
+/*
+ * Accumulates the sum of elements in the given array using the `+` operator.
+ */
+exports.sum = function(values) {
+  return values.reduce(function(acc, x) { return acc + x; }, 0);
+};
+
+/*
+ * Returns an array of all values in the given object.
+ */
+exports.values = function(obj) {
+  return Object.keys(obj).map(function(k) { return obj[k]; });
+};
+
+exports.shuffle = function(array) {
+  for (i = array.length - 1; i > 0; --i) {
+    var j = Math.floor(Math.random() * (i + 1));
+    var aj = array[j];
+    array[j] = array[i];
+    array[i] = aj;
+  }
+};
+
+exports.propertyAccessor = function(self, config, field, setHook) {
+  return function(x) {
+    if (!arguments.length) return config[field];
+    config[field] = x;
+    if (setHook) setHook(x);
+    return self;
+  };
+};
+
+/*
+ * Given a layered, directed graph with `rank` and `order` node attributes,
+ * this function returns an array of ordered ranks. Each rank contains an array
+ * of the ids of the nodes in that rank in the order specified by the `order`
+ * attribute.
+ */
+exports.ordering = function(g) {
+  var ordering = [];
+  g.eachNode(function(u, value) {
+    var rank = ordering[value.rank] || (ordering[value.rank] = []);
+    rank[value.order] = u;
+  });
+  return ordering;
+};
+
+/*
+ * A filter that can be used with `filterNodes` to get a graph that only
+ * includes nodes that do not contain others nodes.
+ */
+exports.filterNonSubgraphs = function(g) {
+  return function(u) {
+    return g.children(u).length === 0;
+  };
+};
+
+/*
+ * Returns a new function that wraps `func` with a timer. The wrapper logs the
+ * time it takes to execute the function.
+ *
+ * The timer will be enabled provided `log.level >= 1`.
+ */
+function time(name, func) {
+  return function() {
+    var start = new Date().getTime();
+    try {
+      return func.apply(null, arguments);
+    } finally {
+      log(1, name + ' time: ' + (new Date().getTime() - start) + 'ms');
+    }
+  };
+}
+time.enabled = false;
+
+exports.time = time;
+
+/*
+ * A global logger with the specification `log(level, message, ...)` that
+ * will log a message to the console if `log.level >= level`.
+ */
+function log(level) {
+  if (log.level >= level) {
+    console.log.apply(console, Array.prototype.slice.call(arguments, 1));
+  }
+}
+log.level = 0;
+
+exports.log = log;
+
+},{}],18:[function(require,module,exports){
+module.exports = '0.4.5';
+
+},{}],19:[function(require,module,exports){
+exports.Set = require('./lib/Set');
+exports.PriorityQueue = require('./lib/PriorityQueue');
+exports.version = require('./lib/version');
+
+},{"./lib/PriorityQueue":20,"./lib/Set":21,"./lib/version":23}],20:[function(require,module,exports){
+module.exports = PriorityQueue;
+
+/**
+ * A min-priority queue data structure. This algorithm is derived from Cormen,
+ * et al., "Introduction to Algorithms". The basic idea of a min-priority
+ * queue is that you can efficiently (in O(1) time) get the smallest key in
+ * the queue. Adding and removing elements takes O(log n) time. A key can
+ * have its priority decreased in O(log n) time.
+ */
+function PriorityQueue() {
+  this._arr = [];
+  this._keyIndices = {};
+}
+
+/**
+ * Returns the number of elements in the queue. Takes `O(1)` time.
+ */
+PriorityQueue.prototype.size = function() {
+  return this._arr.length;
+};
+
+/**
+ * Returns the keys that are in the queue. Takes `O(n)` time.
+ */
+PriorityQueue.prototype.keys = function() {
+  return this._arr.map(function(x) { return x.key; });
+};
+
+/**
+ * Returns `true` if **key** is in the queue and `false` if not.
+ */
+PriorityQueue.prototype.has = function(key) {
+  return key in this._keyIndices;
+};
+
+/**
+ * Returns the priority for **key**. If **key** is not present in the queue
+ * then this function returns `undefined`. Takes `O(1)` time.
+ *
+ * @param {Object} key
+ */
+PriorityQueue.prototype.priority = function(key) {
+  var index = this._keyIndices[key];
+  if (index !== undefined) {
+    return this._arr[index].priority;
+  }
+};
+
+/**
+ * Returns the key for the minimum element in this queue. If the queue is
+ * empty this function throws an Error. Takes `O(1)` time.
+ */
+PriorityQueue.prototype.min = function() {
+  if (this.size() === 0) {
+    throw new Error("Queue underflow");
+  }
+  return this._arr[0].key;
+};
+
+/**
+ * Inserts a new key into the priority queue. If the key already exists in
+ * the queue this function returns `false`; otherwise it will return `true`.
+ * Takes `O(n)` time.
+ *
+ * @param {Object} key the key to add
+ * @param {Number} priority the initial priority for the key
+ */
+PriorityQueue.prototype.add = function(key, priority) {
+  var keyIndices = this._keyIndices;
+  if (!(key in keyIndices)) {
+    var arr = this._arr;
+    var index = arr.length;
+    keyIndices[key] = index;
+    arr.push({key: key, priority: priority});
+    this._decrease(index);
+    return true;
+  }
+  return false;
+};
+
+/**
+ * Removes and returns the smallest key in the queue. Takes `O(log n)` time.
+ */
+PriorityQueue.prototype.removeMin = function() {
+  this._swap(0, this._arr.length - 1);
+  var min = this._arr.pop();
+  delete this._keyIndices[min.key];
+  this._heapify(0);
+  return min.key;
+};
+
+/**
+ * Decreases the priority for **key** to **priority**. If the new priority is
+ * greater than the previous priority, this function will throw an Error.
+ *
+ * @param {Object} key the key for which to raise priority
+ * @param {Number} priority the new priority for the key
+ */
+PriorityQueue.prototype.decrease = function(key, priority) {
+  var index = this._keyIndices[key];
+  if (priority > this._arr[index].priority) {
+    throw new Error("New priority is greater than current priority. " +
+        "Key: " + key + " Old: " + this._arr[index].priority + " New: " + priority);
+  }
+  this._arr[index].priority = priority;
+  this._decrease(index);
+};
+
+PriorityQueue.prototype._heapify = function(i) {
+  var arr = this._arr;
+  var l = 2 * i,
+      r = l + 1,
+      largest = i;
+  if (l < arr.length) {
+    largest = arr[l].priority < arr[largest].priority ? l : largest;
+    if (r < arr.length) {
+      largest = arr[r].priority < arr[largest].priority ? r : largest;
+    }
+    if (largest !== i) {
+      this._swap(i, largest);
+      this._heapify(largest);
+    }
+  }
+};
+
+PriorityQueue.prototype._decrease = function(index) {
+  var arr = this._arr;
+  var priority = arr[index].priority;
+  var parent;
+  while (index !== 0) {
+    parent = index >> 1;
+    if (arr[parent].priority < priority) {
+      break;
+    }
+    this._swap(index, parent);
+    index = parent;
+  }
+};
+
+PriorityQueue.prototype._swap = function(i, j) {
+  var arr = this._arr;
+  var keyIndices = this._keyIndices;
+  var origArrI = arr[i];
+  var origArrJ = arr[j];
+  arr[i] = origArrJ;
+  arr[j] = origArrI;
+  keyIndices[origArrJ.key] = i;
+  keyIndices[origArrI.key] = j;
+};
+
+},{}],21:[function(require,module,exports){
+var util = require('./util');
+
+module.exports = Set;
+
+/**
+ * Constructs a new Set with an optional set of `initialKeys`.
+ *
+ * It is important to note that keys are coerced to String for most purposes
+ * with this object, similar to the behavior of JavaScript's Object. For
+ * example, the following will add only one key:
+ *
+ *     var s = new Set();
+ *     s.add(1);
+ *     s.add("1");
+ *
+ * However, the type of the key is preserved internally so that `keys` returns
+ * the original key set uncoerced. For the above example, `keys` would return
+ * `[1]`.
+ */
+function Set(initialKeys) {
+  this._size = 0;
+  this._keys = {};
+
+  if (initialKeys) {
+    for (var i = 0, il = initialKeys.length; i < il; ++i) {
+      this.add(initialKeys[i]);
+    }
+  }
+}
+
+/**
+ * Returns a new Set that represents the set intersection of the array of given
+ * sets.
+ */
+Set.intersect = function(sets) {
+  if (sets.length === 0) {
+    return new Set();
+  }
+
+  var result = new Set(!util.isArray(sets[0]) ? sets[0].keys() : sets[0]);
+  for (var i = 1, il = sets.length; i < il; ++i) {
+    var resultKeys = result.keys(),
+        other = !util.isArray(sets[i]) ? sets[i] : new Set(sets[i]);
+    for (var j = 0, jl = resultKeys.length; j < jl; ++j) {
+      var key = resultKeys[j];
+      if (!other.has(key)) {
+        result.remove(key);
+      }
+    }
+  }
+
+  return result;
+};
+
+/**
+ * Returns a new Set that represents the set union of the array of given sets.
+ */
+Set.union = function(sets) {
+  var totalElems = util.reduce(sets, function(lhs, rhs) {
+    return lhs + (rhs.size ? rhs.size() : rhs.length);
+  }, 0);
+  var arr = new Array(totalElems);
+
+  var k = 0;
+  for (var i = 0, il = sets.length; i < il; ++i) {
+    var cur = sets[i],
+        keys = !util.isArray(cur) ? cur.keys() : cur;
+    for (var j = 0, jl = keys.length; j < jl; ++j) {
+      arr[k++] = keys[j];
+    }
+  }
+
+  return new Set(arr);
+};
+
+/**
+ * Returns the size of this set in `O(1)` time.
+ */
+Set.prototype.size = function() {
+  return this._size;
+};
+
+/**
+ * Returns the keys in this set. Takes `O(n)` time.
+ */
+Set.prototype.keys = function() {
+  return values(this._keys);
+};
+
+/**
+ * Tests if a key is present in this Set. Returns `true` if it is and `false`
+ * if not. Takes `O(1)` time.
+ */
+Set.prototype.has = function(key) {
+  return key in this._keys;
+};
+
+/**
+ * Adds a new key to this Set if it is not already present. Returns `true` if
+ * the key was added and `false` if it was already present. Takes `O(1)` time.
+ */
+Set.prototype.add = function(key) {
+  if (!(key in this._keys)) {
+    this._keys[key] = key;
+    ++this._size;
+    return true;
+  }
+  return false;
+};
+
+/**
+ * Removes a key from this Set. If the key was removed this function returns
+ * `true`. If not, it returns `false`. Takes `O(1)` time.
+ */
+Set.prototype.remove = function(key) {
+  if (key in this._keys) {
+    delete this._keys[key];
+    --this._size;
+    return true;
+  }
+  return false;
+};
+
+/*
+ * Returns an array of all values for properties of **o**.
+ */
+function values(o) {
+  var ks = Object.keys(o),
+      len = ks.length,
+      result = new Array(len),
+      i;
+  for (i = 0; i < len; ++i) {
+    result[i] = o[ks[i]];
+  }
+  return result;
+}
+
+},{"./util":22}],22:[function(require,module,exports){
+/*
+ * This polyfill comes from
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
+ */
+if(!Array.isArray) {
+  exports.isArray = function (vArg) {
+    return Object.prototype.toString.call(vArg) === '[object Array]';
+  };
+} else {
+  exports.isArray = Array.isArray;
+}
+
+/*
+ * Slightly adapted polyfill from
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
+ */
+if ('function' !== typeof Array.prototype.reduce) {
+  exports.reduce = function(array, callback, opt_initialValue) {
+    'use strict';
+    if (null === array || 'undefined' === typeof array) {
+      // At the moment all modern browsers, that support strict mode, have
+      // native implementation of Array.prototype.reduce. For instance, IE8
+      // does not support strict mode, so this check is actually useless.
+      throw new TypeError(
+          'Array.prototype.reduce called on null or undefined');
+    }
+    if ('function' !== typeof callback) {
+      throw new TypeError(callback + ' is not a function');
+    }
+    var index, value,
+        length = array.length >>> 0,
+        isValueSet = false;
+    if (1 < arguments.length) {
+      value = opt_initialValue;
+      isValueSet = true;
+    }
+    for (index = 0; length > index; ++index) {
+      if (array.hasOwnProperty(index)) {
+        if (isValueSet) {
+          value = callback(value, array[index], index, array);
+        }
+        else {
+          value = array[index];
+          isValueSet = true;
+        }
+      }
+    }
+    if (!isValueSet) {
+      throw new TypeError('Reduce of empty array with no initial value');
+    }
+    return value;
+  };
+} else {
+  exports.reduce = function(array, callback, opt_initialValue) {
+    return array.reduce(callback, opt_initialValue);
+  };
+}
+
+},{}],23:[function(require,module,exports){
+module.exports = '1.1.3';
+
+},{}],24:[function(require,module,exports){
+exports.Graph = require("./lib/Graph");
+exports.Digraph = require("./lib/Digraph");
+exports.CGraph = require("./lib/CGraph");
+exports.CDigraph = require("./lib/CDigraph");
+require("./lib/graph-converters");
+
+exports.alg = {
+  isAcyclic: require("./lib/alg/isAcyclic"),
+  components: require("./lib/alg/components"),
+  dijkstra: require("./lib/alg/dijkstra"),
+  dijkstraAll: require("./lib/alg/dijkstraAll"),
+  findCycles: require("./lib/alg/findCycles"),
+  floydWarshall: require("./lib/alg/floydWarshall"),
+  postorder: require("./lib/alg/postorder"),
+  preorder: require("./lib/alg/preorder"),
+  prim: require("./lib/alg/prim"),
+  tarjan: require("./lib/alg/tarjan"),
+  topsort: require("./lib/alg/topsort")
+};
+
+exports.converter = {
+  json: require("./lib/converter/json.js")
+};
+
+var filter = require("./lib/filter");
+exports.filter = {
+  all: filter.all,
+  nodesFromList: filter.nodesFromList
+};
+
+exports.version = require("./lib/version");
+
+},{"./lib/CDigraph":26,"./lib/CGraph":27,"./lib/Digraph":28,"./lib/Graph":29,"./lib/alg/components":30,"./lib/alg/dijkstra":31,"./lib/alg/dijkstraAll":32,"./lib/alg/findCycles":33,"./lib/alg/floydWarshall":34,"./lib/alg/isAcyclic":35,"./lib/alg/postorder":36,"./lib/alg/preorder":37,"./lib/alg/prim":38,"./lib/alg/tarjan":39,"./lib/alg/topsort":40,"./lib/converter/json.js":42,"./lib/filter":43,"./lib/graph-converters":44,"./lib/version":46}],25:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = BaseGraph;
+
+function BaseGraph() {
+  // The value assigned to the graph itself.
+  this._value = undefined;
+
+  // Map of node id -> { id, value }
+  this._nodes = {};
+
+  // Map of edge id -> { id, u, v, value }
+  this._edges = {};
+
+  // Used to generate a unique id in the graph
+  this._nextId = 0;
+}
+
+// Number of nodes
+BaseGraph.prototype.order = function() {
+  return Object.keys(this._nodes).length;
+};
+
+// Number of edges
+BaseGraph.prototype.size = function() {
+  return Object.keys(this._edges).length;
+};
+
+// Accessor for graph level value
+BaseGraph.prototype.graph = function(value) {
+  if (arguments.length === 0) {
+    return this._value;
+  }
+  this._value = value;
+};
+
+BaseGraph.prototype.hasNode = function(u) {
+  return u in this._nodes;
+};
+
+BaseGraph.prototype.node = function(u, value) {
+  var node = this._strictGetNode(u);
+  if (arguments.length === 1) {
+    return node.value;
+  }
+  node.value = value;
+};
+
+BaseGraph.prototype.nodes = function() {
+  var nodes = [];
+  this.eachNode(function(id) { nodes.push(id); });
+  return nodes;
+};
+
+BaseGraph.prototype.eachNode = function(func) {
+  for (var k in this._nodes) {
+    var node = this._nodes[k];
+    func(node.id, node.value);
+  }
+};
+
+BaseGraph.prototype.hasEdge = function(e) {
+  return e in this._edges;
+};
+
+BaseGraph.prototype.edge = function(e, value) {
+  var edge = this._strictGetEdge(e);
+  if (arguments.length === 1) {
+    return edge.value;
+  }
+  edge.value = value;
+};
+
+BaseGraph.prototype.edges = function() {
+  var es = [];
+  this.eachEdge(function(id) { es.push(id); });
+  return es;
+};
+
+BaseGraph.prototype.eachEdge = function(func) {
+  for (var k in this._edges) {
+    var edge = this._edges[k];
+    func(edge.id, edge.u, edge.v, edge.value);
+  }
+};
+
+BaseGraph.prototype.incidentNodes = function(e) {
+  var edge = this._strictGetEdge(e);
+  return [edge.u, edge.v];
+};
+
+BaseGraph.prototype.addNode = function(u, value) {
+  if (u === undefined || u === null) {
+    do {
+      u = "_" + (++this._nextId);
+    } while (this.hasNode(u));
+  } else if (this.hasNode(u)) {
+    throw new Error("Graph already has node '" + u + "'");
+  }
+  this._nodes[u] = { id: u, value: value };
+  return u;
+};
+
+BaseGraph.prototype.delNode = function(u) {
+  this._strictGetNode(u);
+  this.incidentEdges(u).forEach(function(e) { this.delEdge(e); }, this);
+  delete this._nodes[u];
+};
+
+// inMap and outMap are opposite sides of an incidence map. For example, for
+// Graph these would both come from the _incidentEdges map, while for Digraph
+// they would come from _inEdges and _outEdges.
+BaseGraph.prototype._addEdge = function(e, u, v, value, inMap, outMap) {
+  this._strictGetNode(u);
+  this._strictGetNode(v);
+
+  if (e === undefined || e === null) {
+    do {
+      e = "_" + (++this._nextId);
+    } while (this.hasEdge(e));
+  }
+  else if (this.hasEdge(e)) {
+    throw new Error("Graph already has edge '" + e + "'");
+  }
+
+  this._edges[e] = { id: e, u: u, v: v, value: value };
+  addEdgeToMap(inMap[v], u, e);
+  addEdgeToMap(outMap[u], v, e);
+
+  return e;
+};
+
+// See note for _addEdge regarding inMap and outMap.
+BaseGraph.prototype._delEdge = function(e, inMap, outMap) {
+  var edge = this._strictGetEdge(e);
+  delEdgeFromMap(inMap[edge.v], edge.u, e);
+  delEdgeFromMap(outMap[edge.u], edge.v, e);
+  delete this._edges[e];
+};
+
+BaseGraph.prototype.copy = function() {
+  var copy = new this.constructor();
+  copy.graph(this.graph());
+  this.eachNode(function(u, value) { copy.addNode(u, value); });
+  this.eachEdge(function(e, u, v, value) { copy.addEdge(e, u, v, value); });
+  copy._nextId = this._nextId;
+  return copy;
+};
+
+BaseGraph.prototype.filterNodes = function(filter) {
+  var copy = new this.constructor();
+  copy.graph(this.graph());
+  this.eachNode(function(u, value) {
+    if (filter(u)) {
+      copy.addNode(u, value);
+    }
+  });
+  this.eachEdge(function(e, u, v, value) {
+    if (copy.hasNode(u) && copy.hasNode(v)) {
+      copy.addEdge(e, u, v, value);
+    }
+  });
+  return copy;
+};
+
+BaseGraph.prototype._strictGetNode = function(u) {
+  var node = this._nodes[u];
+  if (node === undefined) {
+    throw new Error("Node '" + u + "' is not in graph");
+  }
+  return node;
+};
+
+BaseGraph.prototype._strictGetEdge = function(e) {
+  var edge = this._edges[e];
+  if (edge === undefined) {
+    throw new Error("Edge '" + e + "' is not in graph");
+  }
+  return edge;
+};
+
+function addEdgeToMap(map, v, e) {
+  (map[v] || (map[v] = new Set())).add(e);
+}
+
+function delEdgeFromMap(map, v, e) {
+  var vEntry = map[v];
+  vEntry.remove(e);
+  if (vEntry.size() === 0) {
+    delete map[v];
+  }
+}
+
+
+},{"cp-data":19}],26:[function(require,module,exports){
+var Digraph = require("./Digraph"),
+    compoundify = require("./compoundify");
+
+var CDigraph = compoundify(Digraph);
+
+module.exports = CDigraph;
+
+CDigraph.fromDigraph = function(src) {
+  var g = new CDigraph(),
+      graphValue = src.graph();
+
+  if (graphValue !== undefined) {
+    g.graph(graphValue);
+  }
+
+  src.eachNode(function(u, value) {
+    if (value === undefined) {
+      g.addNode(u);
+    } else {
+      g.addNode(u, value);
+    }
+  });
+  src.eachEdge(function(e, u, v, value) {
+    if (value === undefined) {
+      g.addEdge(null, u, v);
+    } else {
+      g.addEdge(null, u, v, value);
+    }
+  });
+  return g;
+};
+
+CDigraph.prototype.toString = function() {
+  return "CDigraph " + JSON.stringify(this, null, 2);
+};
+
+},{"./Digraph":28,"./compoundify":41}],27:[function(require,module,exports){
+var Graph = require("./Graph"),
+    compoundify = require("./compoundify");
+
+var CGraph = compoundify(Graph);
+
+module.exports = CGraph;
+
+CGraph.fromGraph = function(src) {
+  var g = new CGraph(),
+      graphValue = src.graph();
+
+  if (graphValue !== undefined) {
+    g.graph(graphValue);
+  }
+
+  src.eachNode(function(u, value) {
+    if (value === undefined) {
+      g.addNode(u);
+    } else {
+      g.addNode(u, value);
+    }
+  });
+  src.eachEdge(function(e, u, v, value) {
+    if (value === undefined) {
+      g.addEdge(null, u, v);
+    } else {
+      g.addEdge(null, u, v, value);
+    }
+  });
+  return g;
+};
+
+CGraph.prototype.toString = function() {
+  return "CGraph " + JSON.stringify(this, null, 2);
+};
+
+},{"./Graph":29,"./compoundify":41}],28:[function(require,module,exports){
+/*
+ * This file is organized with in the following order:
+ *
+ * Exports
+ * Graph constructors
+ * Graph queries (e.g. nodes(), edges()
+ * Graph mutators
+ * Helper functions
+ */
+
+var util = require("./util"),
+    BaseGraph = require("./BaseGraph"),
+/* jshint -W079 */
+    Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = Digraph;
+
+/*
+ * Constructor to create a new directed multi-graph.
+ */
+function Digraph() {
+  BaseGraph.call(this);
+
+  /*! Map of sourceId -> {targetId -> Set of edge ids} */
+  this._inEdges = {};
+
+  /*! Map of targetId -> {sourceId -> Set of edge ids} */
+  this._outEdges = {};
+}
+
+Digraph.prototype = new BaseGraph();
+Digraph.prototype.constructor = Digraph;
+
+/*
+ * Always returns `true`.
+ */
+Digraph.prototype.isDirected = function() {
+  return true;
+};
+
+/*
+ * Returns all successors of the node with the id `u`. That is, all nodes
+ * that have the node `u` as their source are returned.
+ *
+ * If no node `u` exists in the graph this function throws an Error.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.successors = function(u) {
+  this._strictGetNode(u);
+  return Object.keys(this._outEdges[u])
+               .map(function(v) { return this._nodes[v].id; }, this);
+};
+
+/*
+ * Returns all predecessors of the node with the id `u`. That is, all nodes
+ * that have the node `u` as their target are returned.
+ *
+ * If no node `u` exists in the graph this function throws an Error.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.predecessors = function(u) {
+  this._strictGetNode(u);
+  return Object.keys(this._inEdges[u])
+               .map(function(v) { return this._nodes[v].id; }, this);
+};
+
+/*
+ * Returns all nodes that are adjacent to the node with the id `u`. In other
+ * words, this function returns the set of all successors and predecessors of
+ * node `u`.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.neighbors = function(u) {
+  return Set.union([this.successors(u), this.predecessors(u)]).keys();
+};
+
+/*
+ * Returns all nodes in the graph that have no in-edges.
+ */
+Digraph.prototype.sources = function() {
+  var self = this;
+  return this._filterNodes(function(u) {
+    // This could have better space characteristics if we had an inDegree function.
+    return self.inEdges(u).length === 0;
+  });
+};
+
+/*
+ * Returns all nodes in the graph that have no out-edges.
+ */
+Digraph.prototype.sinks = function() {
+  var self = this;
+  return this._filterNodes(function(u) {
+    // This could have better space characteristics if we have an outDegree function.
+    return self.outEdges(u).length === 0;
+  });
+};
+
+/*
+ * Returns the source node incident on the edge identified by the id `e`. If no
+ * such edge exists in the graph this function throws an Error.
+ *
+ * @param {String} e an edge id
+ */
+Digraph.prototype.source = function(e) {
+  return this._strictGetEdge(e).u;
+};
+
+/*
+ * Returns the target node incident on the edge identified by the id `e`. If no
+ * such edge exists in the graph this function throws an Error.
+ *
+ * @param {String} e an edge id
+ */
+Digraph.prototype.target = function(e) {
+  return this._strictGetEdge(e).v;
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that have the node
+ * `target` as their target. If the node `target` is not in the graph this
+ * function raises an Error.
+ *
+ * Optionally a `source` node can also be specified. This causes the results
+ * to be filtered such that only edges from `source` to `target` are included.
+ * If the node `source` is specified but is not in the graph then this function
+ * raises an Error.
+ *
+ * @param {String} target the target node id
+ * @param {String} [source] an optional source node id
+ */
+Digraph.prototype.inEdges = function(target, source) {
+  this._strictGetNode(target);
+  var results = Set.union(util.values(this._inEdges[target])).keys();
+  if (arguments.length > 1) {
+    this._strictGetNode(source);
+    results = results.filter(function(e) { return this.source(e) === source; }, this);
+  }
+  return results;
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that have the node
+ * `source` as their source. If the node `source` is not in the graph this
+ * function raises an Error.
+ *
+ * Optionally a `target` node may also be specified. This causes the results
+ * to be filtered such that only edges from `source` to `target` are included.
+ * If the node `target` is specified but is not in the graph then this function
+ * raises an Error.
+ *
+ * @param {String} source the source node id
+ * @param {String} [target] an optional target node id
+ */
+Digraph.prototype.outEdges = function(source, target) {
+  this._strictGetNode(source);
+  var results = Set.union(util.values(this._outEdges[source])).keys();
+  if (arguments.length > 1) {
+    this._strictGetNode(target);
+    results = results.filter(function(e) { return this.target(e) === target; }, this);
+  }
+  return results;
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that have the `u` as
+ * their source or their target. If the node `u` is not in the graph this
+ * function raises an Error.
+ *
+ * Optionally a `v` node may also be specified. This causes the results to be
+ * filtered such that only edges between `u` and `v` - in either direction -
+ * are included. IF the node `v` is specified but not in the graph then this
+ * function raises an Error.
+ *
+ * @param {String} u the node for which to find incident edges
+ * @param {String} [v] option node that must be adjacent to `u`
+ */
+Digraph.prototype.incidentEdges = function(u, v) {
+  if (arguments.length > 1) {
+    return Set.union([this.outEdges(u, v), this.outEdges(v, u)]).keys();
+  } else {
+    return Set.union([this.inEdges(u), this.outEdges(u)]).keys();
+  }
+};
+
+/*
+ * Returns a string representation of this graph.
+ */
+Digraph.prototype.toString = function() {
+  return "Digraph " + JSON.stringify(this, null, 2);
+};
+
+/*
+ * Adds a new node with the id `u` to the graph and assigns it the value
+ * `value`. If a node with the id is already a part of the graph this function
+ * throws an Error.
+ *
+ * @param {String} u a node id
+ * @param {Object} [value] an optional value to attach to the node
+ */
+Digraph.prototype.addNode = function(u, value) {
+  u = BaseGraph.prototype.addNode.call(this, u, value);
+  this._inEdges[u] = {};
+  this._outEdges[u] = {};
+  return u;
+};
+
+/*
+ * Removes a node from the graph that has the id `u`. Any edges incident on the
+ * node are also removed. If the graph does not contain a node with the id this
+ * function will throw an Error.
+ *
+ * @param {String} u a node id
+ */
+Digraph.prototype.delNode = function(u) {
+  BaseGraph.prototype.delNode.call(this, u);
+  delete this._inEdges[u];
+  delete this._outEdges[u];
+};
+
+/*
+ * Adds a new edge to the graph with the id `e` from a node with the id `source`
+ * to a node with an id `target` and assigns it the value `value`. This graph
+ * allows more than one edge from `source` to `target` as long as the id `e`
+ * is unique in the set of edges. If `e` is `null` the graph will assign a
+ * unique identifier to the edge.
+ *
+ * If `source` or `target` are not present in the graph this function will
+ * throw an Error.
+ *
+ * @param {String} [e] an edge id
+ * @param {String} source the source node id
+ * @param {String} target the target node id
+ * @param {Object} [value] an optional value to attach to the edge
+ */
+Digraph.prototype.addEdge = function(e, source, target, value) {
+  return BaseGraph.prototype._addEdge.call(this, e, source, target, value,
+                                           this._inEdges, this._outEdges);
+};
+
+/*
+ * Removes an edge in the graph with the id `e`. If no edge in the graph has
+ * the id `e` this function will throw an Error.
+ *
+ * @param {String} e an edge id
+ */
+Digraph.prototype.delEdge = function(e) {
+  BaseGraph.prototype._delEdge.call(this, e, this._inEdges, this._outEdges);
+};
+
+// Unlike BaseGraph.filterNodes, this helper just returns nodes that
+// satisfy a predicate.
+Digraph.prototype._filterNodes = function(pred) {
+  var filtered = [];
+  this.eachNode(function(u) {
+    if (pred(u)) {
+      filtered.push(u);
+    }
+  });
+  return filtered;
+};
+
+
+},{"./BaseGraph":25,"./util":45,"cp-data":19}],29:[function(require,module,exports){
+/*
+ * This file is organized with in the following order:
+ *
+ * Exports
+ * Graph constructors
+ * Graph queries (e.g. nodes(), edges()
+ * Graph mutators
+ * Helper functions
+ */
+
+var util = require("./util"),
+    BaseGraph = require("./BaseGraph"),
+/* jshint -W079 */
+    Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = Graph;
+
+/*
+ * Constructor to create a new undirected multi-graph.
+ */
+function Graph() {
+  BaseGraph.call(this);
+
+  /*! Map of nodeId -> { otherNodeId -> Set of edge ids } */
+  this._incidentEdges = {};
+}
+
+Graph.prototype = new BaseGraph();
+Graph.prototype.constructor = Graph;
+
+/*
+ * Always returns `false`.
+ */
+Graph.prototype.isDirected = function() {
+  return false;
+};
+
+/*
+ * Returns all nodes that are adjacent to the node with the id `u`.
+ *
+ * @param {String} u a node id
+ */
+Graph.prototype.neighbors = function(u) {
+  this._strictGetNode(u);
+  return Object.keys(this._incidentEdges[u])
+               .map(function(v) { return this._nodes[v].id; }, this);
+};
+
+/*
+ * Returns an array of ids for all edges in the graph that are incident on `u`.
+ * If the node `u` is not in the graph this function raises an Error.
+ *
+ * Optionally a `v` node may also be specified. This causes the results to be
+ * filtered such that only edges between `u` and `v` are included. If the node
+ * `v` is specified but not in the graph then this function raises an Error.
+ *
+ * @param {String} u the node for which to find incident edges
+ * @param {String} [v] option node that must be adjacent to `u`
+ */
+Graph.prototype.incidentEdges = function(u, v) {
+  this._strictGetNode(u);
+  if (arguments.length > 1) {
+    this._strictGetNode(v);
+    return v in this._incidentEdges[u] ? this._incidentEdges[u][v].keys() : [];
+  } else {
+    return Set.union(util.values(this._incidentEdges[u])).keys();
+  }
+};
+
+/*
+ * Returns a string representation of this graph.
+ */
+Graph.prototype.toString = function() {
+  return "Graph " + JSON.stringify(this, null, 2);
+};
+
+/*
+ * Adds a new node with the id `u` to the graph and assigns it the value
+ * `value`. If a node with the id is already a part of the graph this function
+ * throws an Error.
+ *
+ * @param {String} u a node id
+ * @param {Object} [value] an optional value to attach to the node
+ */
+Graph.prototype.addNode = function(u, value) {
+  u = BaseGraph.prototype.addNode.call(this, u, value);
+  this._incidentEdges[u] = {};
+  return u;
+};
+
+/*
+ * Removes a node from the graph that has the id `u`. Any edges incident on the
+ * node are also removed. If the graph does not contain a node with the id this
+ * function will throw an Error.
+ *
+ * @param {String} u a node id
+ */
+Graph.prototype.delNode = function(u) {
+  BaseGraph.prototype.delNode.call(this, u);
+  delete this._incidentEdges[u];
+};
+
+/*
+ * Adds a new edge to the graph with the id `e` between a node with the id `u`
+ * and a node with an id `v` and assigns it the value `value`. This graph
+ * allows more than one edge between `u` and `v` as long as the id `e`
+ * is unique in the set of edges. If `e` is `null` the graph will assign a
+ * unique identifier to the edge.
+ *
+ * If `u` or `v` are not present in the graph this function will throw an
+ * Error.
+ *
+ * @param {String} [e] an edge id
+ * @param {String} u the node id of one of the adjacent nodes
+ * @param {String} v the node id of the other adjacent node
+ * @param {Object} [value] an optional value to attach to the edge
+ */
+Graph.prototype.addEdge = function(e, u, v, value) {
+  return BaseGraph.prototype._addEdge.call(this, e, u, v, value,
+                                           this._incidentEdges, this._incidentEdges);
+};
+
+/*
+ * Removes an edge in the graph with the id `e`. If no edge in the graph has
+ * the id `e` this function will throw an Error.
+ *
+ * @param {String} e an edge id
+ */
+Graph.prototype.delEdge = function(e) {
+  BaseGraph.prototype._delEdge.call(this, e, this._incidentEdges, this._incidentEdges);
+};
+
+
+},{"./BaseGraph":25,"./util":45,"cp-data":19}],30:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = components;
+
+/**
+ * Finds all [connected components][] in a graph and returns an array of these
+ * components. Each component is itself an array that contains the ids of nodes
+ * in the component.
+ *
+ * This function only works with undirected Graphs.
+ *
+ * [connected components]: http://en.wikipedia.org/wiki/Connected_component_(graph_theory)
+ *
+ * @param {Graph} g the graph to search for components
+ */
+function components(g) {
+  var results = [];
+  var visited = new Set();
+
+  function dfs(v, component) {
+    if (!visited.has(v)) {
+      visited.add(v);
+      component.push(v);
+      g.neighbors(v).forEach(function(w) {
+        dfs(w, component);
+      });
+    }
+  }
+
+  g.nodes().forEach(function(v) {
+    var component = [];
+    dfs(v, component);
+    if (component.length > 0) {
+      results.push(component);
+    }
+  });
+
+  return results;
+}
+
+},{"cp-data":19}],31:[function(require,module,exports){
+var PriorityQueue = require("cp-data").PriorityQueue;
+
+module.exports = dijkstra;
+
+/**
+ * This function is an implementation of [Dijkstra's algorithm][] which finds
+ * the shortest path from **source** to all other nodes in **g**. This
+ * function returns a map of `u -> { distance, predecessor }`. The distance
+ * property holds the sum of the weights from **source** to `u` along the
+ * shortest path or `Number.POSITIVE_INFINITY` if there is no path from
+ * **source**. The predecessor property can be used to walk the individual
+ * elements of the path from **source** to **u** in reverse order.
+ *
+ * This function takes an optional `weightFunc(e)` which returns the
+ * weight of the edge `e`. If no weightFunc is supplied then each edge is
+ * assumed to have a weight of 1. This function throws an Error if any of
+ * the traversed edges have a negative edge weight.
+ *
+ * This function takes an optional `incidentFunc(u)` which returns the ids of
+ * all edges incident to the node `u` for the purposes of shortest path
+ * traversal. By default this function uses the `g.outEdges` for Digraphs and
+ * `g.incidentEdges` for Graphs.
+ *
+ * This function takes `O((|E| + |V|) * log |V|)` time.
+ *
+ * [Dijkstra's algorithm]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
+ *
+ * @param {Graph} g the graph to search for shortest paths from **source**
+ * @param {Object} source the source from which to start the search
+ * @param {Function} [weightFunc] optional weight function
+ * @param {Function} [incidentFunc] optional incident function
+ */
+function dijkstra(g, source, weightFunc, incidentFunc) {
+  var results = {},
+      pq = new PriorityQueue();
+
+  function updateNeighbors(e) {
+    var incidentNodes = g.incidentNodes(e),
+        v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1],
+        vEntry = results[v],
+        weight = weightFunc(e),
+        distance = uEntry.distance + weight;
+
+    if (weight < 0) {
+      throw new Error("dijkstra does not allow negative edge weights. Bad edge: " + e + " Weight: " + weight);
+    }
+
+    if (distance < vEntry.distance) {
+      vEntry.distance = distance;
+      vEntry.predecessor = u;
+      pq.decrease(v, distance);
+    }
+  }
+
+  weightFunc = weightFunc || function() { return 1; };
+  incidentFunc = incidentFunc || (g.isDirected()
+      ? function(u) { return g.outEdges(u); }
+      : function(u) { return g.incidentEdges(u); });
+
+  g.eachNode(function(u) {
+    var distance = u === source ? 0 : Number.POSITIVE_INFINITY;
+    results[u] = { distance: distance };
+    pq.add(u, distance);
+  });
+
+  var u, uEntry;
+  while (pq.size() > 0) {
+    u = pq.removeMin();
+    uEntry = results[u];
+    if (uEntry.distance === Number.POSITIVE_INFINITY) {
+      break;
+    }
+
+    incidentFunc(u).forEach(updateNeighbors);
+  }
+
+  return results;
+}
+
+},{"cp-data":19}],32:[function(require,module,exports){
+var dijkstra = require("./dijkstra");
+
+module.exports = dijkstraAll;
+
+/**
+ * This function finds the shortest path from each node to every other
+ * reachable node in the graph. It is similar to [alg.dijkstra][], but
+ * instead of returning a single-source array, it returns a mapping of
+ * of `source -> alg.dijksta(g, source, weightFunc, incidentFunc)`.
+ *
+ * This function takes an optional `weightFunc(e)` which returns the
+ * weight of the edge `e`. If no weightFunc is supplied then each edge is
+ * assumed to have a weight of 1. This function throws an Error if any of
+ * the traversed edges have a negative edge weight.
+ *
+ * This function takes an optional `incidentFunc(u)` which returns the ids of
+ * all edges incident to the node `u` for the purposes of shortest path
+ * traversal. By default this function uses the `outEdges` function on the
+ * supplied graph.
+ *
+ * This function takes `O(|V| * (|E| + |V|) * log |V|)` time.
+ *
+ * [alg.dijkstra]: dijkstra.js.html#dijkstra
+ *
+ * @param {Graph} g the graph to search for shortest paths from **source**
+ * @param {Function} [weightFunc] optional weight function
+ * @param {Function} [incidentFunc] optional incident function
+ */
+function dijkstraAll(g, weightFunc, incidentFunc) {
+  var results = {};
+  g.eachNode(function(u) {
+    results[u] = dijkstra(g, u, weightFunc, incidentFunc);
+  });
+  return results;
+}
+
+},{"./dijkstra":31}],33:[function(require,module,exports){
+var tarjan = require("./tarjan");
+
+module.exports = findCycles;
+
+/*
+ * Given a Digraph **g** this function returns all nodes that are part of a
+ * cycle. Since there may be more than one cycle in a graph this function
+ * returns an array of these cycles, where each cycle is itself represented
+ * by an array of ids for each node involved in that cycle.
+ *
+ * [alg.isAcyclic][] is more efficient if you only need to determine whether
+ * a graph has a cycle or not.
+ *
+ * [alg.isAcyclic]: isAcyclic.js.html#isAcyclic
+ *
+ * @param {Digraph} g the graph to search for cycles.
+ */
+function findCycles(g) {
+  return tarjan(g).filter(function(cmpt) { return cmpt.length > 1; });
+}
+
+},{"./tarjan":39}],34:[function(require,module,exports){
+module.exports = floydWarshall;
+
+/**
+ * This function is an implementation of the [Floyd-Warshall algorithm][],
+ * which finds the shortest path from each node to every other reachable node
+ * in the graph. It is similar to [alg.dijkstraAll][], but it handles negative
+ * edge weights and is more efficient for some types of graphs. This function
+ * returns a map of `source -> { target -> { distance, predecessor }`. The
+ * distance property holds the sum of the weights from `source` to `target`
+ * along the shortest path of `Number.POSITIVE_INFINITY` if there is no path
+ * from `source`. The predecessor property can be used to walk the individual
+ * elements of the path from `source` to `target` in reverse order.
+ *
+ * This function takes an optional `weightFunc(e)` which returns the
+ * weight of the edge `e`. If no weightFunc is supplied then each edge is
+ * assumed to have a weight of 1.
+ *
+ * This function takes an optional `incidentFunc(u)` which returns the ids of
+ * all edges incident to the node `u` for the purposes of shortest path
+ * traversal. By default this function uses the `outEdges` function on the
+ * supplied graph.
+ *
+ * This algorithm takes O(|V|^3) time.
+ *
+ * [Floyd-Warshall algorithm]: https://en.wikipedia.org/wiki/Floyd-Warshall_algorithm
+ * [alg.dijkstraAll]: dijkstraAll.js.html#dijkstraAll
+ *
+ * @param {Graph} g the graph to search for shortest paths from **source**
+ * @param {Function} [weightFunc] optional weight function
+ * @param {Function} [incidentFunc] optional incident function
+ */
+function floydWarshall(g, weightFunc, incidentFunc) {
+  var results = {},
+      nodes = g.nodes();
+
+  weightFunc = weightFunc || function() { return 1; };
+  incidentFunc = incidentFunc || (g.isDirected()
+      ? function(u) { return g.outEdges(u); }
+      : function(u) { return g.incidentEdges(u); });
+
+  nodes.forEach(function(u) {
+    results[u] = {};
+    results[u][u] = { distance: 0 };
+    nodes.forEach(function(v) {
+      if (u !== v) {
+        results[u][v] = { distance: Number.POSITIVE_INFINITY };
+      }
+    });
+    incidentFunc(u).forEach(function(e) {
+      var incidentNodes = g.incidentNodes(e),
+          v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1],
+          d = weightFunc(e);
+      if (d < results[u][v].distance) {
+        results[u][v] = { distance: d, predecessor: u };
+      }
+    });
+  });
+
+  nodes.forEach(function(k) {
+    var rowK = results[k];
+    nodes.forEach(function(i) {
+      var rowI = results[i];
+      nodes.forEach(function(j) {
+        var ik = rowI[k];
+        var kj = rowK[j];
+        var ij = rowI[j];
+        var altDistance = ik.distance + kj.distance;
+        if (altDistance < ij.distance) {
+          ij.distance = altDistance;
+          ij.predecessor = kj.predecessor;
+        }
+      });
+    });
+  });
+
+  return results;
+}
+
+},{}],35:[function(require,module,exports){
+var topsort = require("./topsort");
+
+module.exports = isAcyclic;
+
+/*
+ * Given a Digraph **g** this function returns `true` if the graph has no
+ * cycles and returns `false` if it does. This algorithm returns as soon as it
+ * detects the first cycle.
+ *
+ * Use [alg.findCycles][] if you need the actual list of cycles in a graph.
+ *
+ * [alg.findCycles]: findCycles.js.html#findCycles
+ *
+ * @param {Digraph} g the graph to test for cycles
+ */
+function isAcyclic(g) {
+  try {
+    topsort(g);
+  } catch (e) {
+    if (e instanceof topsort.CycleException) return false;
+    throw e;
+  }
+  return true;
+}
+
+},{"./topsort":40}],36:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = postorder;
+
+// Postorder traversal of g, calling f for each visited node. Assumes the graph
+// is a tree.
+function postorder(g, root, f) {
+  var visited = new Set();
+  if (g.isDirected()) {
+    throw new Error("This function only works for undirected graphs");
+  }
+  function dfs(u, prev) {
+    if (visited.has(u)) {
+      throw new Error("The input graph is not a tree: " + g);
+    }
+    visited.add(u);
+    g.neighbors(u).forEach(function(v) {
+      if (v !== prev) dfs(v, u);
+    });
+    f(u);
+  }
+  dfs(root);
+}
+
+},{"cp-data":19}],37:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = preorder;
+
+// Preorder traversal of g, calling f for each visited node. Assumes the graph
+// is a tree.
+function preorder(g, root, f) {
+  var visited = new Set();
+  if (g.isDirected()) {
+    throw new Error("This function only works for undirected graphs");
+  }
+  function dfs(u, prev) {
+    if (visited.has(u)) {
+      throw new Error("The input graph is not a tree: " + g);
+    }
+    visited.add(u);
+    f(u);
+    g.neighbors(u).forEach(function(v) {
+      if (v !== prev) dfs(v, u);
+    });
+  }
+  dfs(root);
+}
+
+},{"cp-data":19}],38:[function(require,module,exports){
+var Graph = require("../Graph"),
+    PriorityQueue = require("cp-data").PriorityQueue;
+
+module.exports = prim;
+
+/**
+ * [Prim's algorithm][] takes a connected undirected graph and generates a
+ * [minimum spanning tree][]. This function returns the minimum spanning
+ * tree as an undirected graph. This algorithm is derived from the description
+ * in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634.
+ *
+ * This function takes a `weightFunc(e)` which returns the weight of the edge
+ * `e`. It throws an Error if the graph is not connected.
+ *
+ * This function takes `O(|E| log |V|)` time.
+ *
+ * [Prim's algorithm]: https://en.wikipedia.org/wiki/Prim's_algorithm
+ * [minimum spanning tree]: https://en.wikipedia.org/wiki/Minimum_spanning_tree
+ *
+ * @param {Graph} g the graph used to generate the minimum spanning tree
+ * @param {Function} weightFunc the weight function to use
+ */
+function prim(g, weightFunc) {
+  var result = new Graph(),
+      parents = {},
+      pq = new PriorityQueue(),
+      u;
+
+  function updateNeighbors(e) {
+    var incidentNodes = g.incidentNodes(e),
+        v = incidentNodes[0] !== u ? incidentNodes[0] : incidentNodes[1],
+        pri = pq.priority(v);
+    if (pri !== undefined) {
+      var edgeWeight = weightFunc(e);
+      if (edgeWeight < pri) {
+        parents[v] = u;
+        pq.decrease(v, edgeWeight);
+      }
+    }
+  }
+
+  if (g.order() === 0) {
+    return result;
+  }
+
+  g.eachNode(function(u) {
+    pq.add(u, Number.POSITIVE_INFINITY);
+    result.addNode(u);
+  });
+
+  // Start from an arbitrary node
+  pq.decrease(g.nodes()[0], 0);
+
+  var init = false;
+  while (pq.size() > 0) {
+    u = pq.removeMin();
+    if (u in parents) {
+      result.addEdge(null, u, parents[u]);
+    } else if (init) {
+      throw new Error("Input graph is not connected: " + g);
+    } else {
+      init = true;
+    }
+
+    g.incidentEdges(u).forEach(updateNeighbors);
+  }
+
+  return result;
+}
+
+},{"../Graph":29,"cp-data":19}],39:[function(require,module,exports){
+module.exports = tarjan;
+
+/**
+ * This function is an implementation of [Tarjan's algorithm][] which finds
+ * all [strongly connected components][] in the directed graph **g**. Each
+ * strongly connected component is composed of nodes that can reach all other
+ * nodes in the component via directed edges. A strongly connected component
+ * can consist of a single node if that node cannot both reach and be reached
+ * by any other specific node in the graph. Components of more than one node
+ * are guaranteed to have at least one cycle.
+ *
+ * This function returns an array of components. Each component is itself an
+ * array that contains the ids of all nodes in the component.
+ *
+ * [Tarjan's algorithm]: http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
+ * [strongly connected components]: http://en.wikipedia.org/wiki/Strongly_connected_component
+ *
+ * @param {Digraph} g the graph to search for strongly connected components
+ */
+function tarjan(g) {
+  if (!g.isDirected()) {
+    throw new Error("tarjan can only be applied to a directed graph. Bad input: " + g);
+  }
+
+  var index = 0,
+      stack = [],
+      visited = {}, // node id -> { onStack, lowlink, index }
+      results = [];
+
+  function dfs(u) {
+    var entry = visited[u] = {
+      onStack: true,
+      lowlink: index,
+      index: index++
+    };
+    stack.push(u);
+
+    g.successors(u).forEach(function(v) {
+      if (!(v in visited)) {
+        dfs(v);
+        entry.lowlink = Math.min(entry.lowlink, visited[v].lowlink);
+      } else if (visited[v].onStack) {
+        entry.lowlink = Math.min(entry.lowlink, visited[v].index);
+      }
+    });
+
+    if (entry.lowlink === entry.index) {
+      var cmpt = [],
+          v;
+      do {
+        v = stack.pop();
+        visited[v].onStack = false;
+        cmpt.push(v);
+      } while (u !== v);
+      results.push(cmpt);
+    }
+  }
+
+  g.nodes().forEach(function(u) {
+    if (!(u in visited)) {
+      dfs(u);
+    }
+  });
+
+  return results;
+}
+
+},{}],40:[function(require,module,exports){
+module.exports = topsort;
+topsort.CycleException = CycleException;
+
+/*
+ * Given a graph **g**, this function returns an ordered list of nodes such
+ * that for each edge `u -> v`, `u` appears before `v` in the list. If the
+ * graph has a cycle it is impossible to generate such a list and
+ * **CycleException** is thrown.
+ *
+ * See [topological sorting](https://en.wikipedia.org/wiki/Topological_sorting)
+ * for more details about how this algorithm works.
+ *
+ * @param {Digraph} g the graph to sort
+ */
+function topsort(g) {
+  if (!g.isDirected()) {
+    throw new Error("topsort can only be applied to a directed graph. Bad input: " + g);
+  }
+
+  var visited = {};
+  var stack = {};
+  var results = [];
+
+  function visit(node) {
+    if (node in stack) {
+      throw new CycleException();
+    }
+
+    if (!(node in visited)) {
+      stack[node] = true;
+      visited[node] = true;
+      g.predecessors(node).forEach(function(pred) {
+        visit(pred);
+      });
+      delete stack[node];
+      results.push(node);
+    }
+  }
+
+  var sinks = g.sinks();
+  if (g.order() !== 0 && sinks.length === 0) {
+    throw new CycleException();
+  }
+
+  g.sinks().forEach(function(sink) {
+    visit(sink);
+  });
+
+  return results;
+}
+
+function CycleException() {}
+
+CycleException.prototype.toString = function() {
+  return "Graph has at least one cycle";
+};
+
+},{}],41:[function(require,module,exports){
+// This file provides a helper function that mixes-in Dot behavior to an
+// existing graph prototype.
+
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+module.exports = compoundify;
+
+// Extends the given SuperConstructor with the ability for nodes to contain
+// other nodes. A special node id `null` is used to indicate the root graph.
+function compoundify(SuperConstructor) {
+  function Constructor() {
+    SuperConstructor.call(this);
+
+    // Map of object id -> parent id (or null for root graph)
+    this._parents = {};
+
+    // Map of id (or null) -> children set
+    this._children = {};
+    this._children[null] = new Set();
+  }
+
+  Constructor.prototype = new SuperConstructor();
+  Constructor.prototype.constructor = Constructor;
+
+  Constructor.prototype.parent = function(u, parent) {
+    this._strictGetNode(u);
+
+    if (arguments.length < 2) {
+      return this._parents[u];
+    }
+
+    if (u === parent) {
+      throw new Error("Cannot make " + u + " a parent of itself");
+    }
+    if (parent !== null) {
+      this._strictGetNode(parent);
+    }
+
+    this._children[this._parents[u]].remove(u);
+    this._parents[u] = parent;
+    this._children[parent].add(u);
+  };
+
+  Constructor.prototype.children = function(u) {
+    if (u !== null) {
+      this._strictGetNode(u);
+    }
+    return this._children[u].keys();
+  };
+
+  Constructor.prototype.addNode = function(u, value) {
+    u = SuperConstructor.prototype.addNode.call(this, u, value);
+    this._parents[u] = null;
+    this._children[u] = new Set();
+    this._children[null].add(u);
+    return u;
+  };
+
+  Constructor.prototype.delNode = function(u) {
+    // Promote all children to the parent of the subgraph
+    var parent = this.parent(u);
+    this._children[u].keys().forEach(function(child) {
+      this.parent(child, parent);
+    }, this);
+
+    this._children[parent].remove(u);
+    delete this._parents[u];
+    delete this._children[u];
+
+    return SuperConstructor.prototype.delNode.call(this, u);
+  };
+
+  Constructor.prototype.copy = function() {
+    var copy = SuperConstructor.prototype.copy.call(this);
+    this.nodes().forEach(function(u) {
+      copy.parent(u, this.parent(u));
+    }, this);
+    return copy;
+  };
+
+  Constructor.prototype.filterNodes = function(filter) {
+    var self = this,
+        copy = SuperConstructor.prototype.filterNodes.call(this, filter);
+
+    var parents = {};
+    function findParent(u) {
+      var parent = self.parent(u);
+      if (parent === null || copy.hasNode(parent)) {
+        parents[u] = parent;
+        return parent;
+      } else if (parent in parents) {
+        return parents[parent];
+      } else {
+        return findParent(parent);
+      }
+    }
+
+    copy.eachNode(function(u) { copy.parent(u, findParent(u)); });
+
+    return copy;
+  };
+
+  return Constructor;
+}
+
+},{"cp-data":19}],42:[function(require,module,exports){
+var Graph = require("../Graph"),
+    Digraph = require("../Digraph"),
+    CGraph = require("../CGraph"),
+    CDigraph = require("../CDigraph");
+
+exports.decode = function(nodes, edges, Ctor) {
+  Ctor = Ctor || Digraph;
+
+  if (typeOf(nodes) !== "Array") {
+    throw new Error("nodes is not an Array");
+  }
+
+  if (typeOf(edges) !== "Array") {
+    throw new Error("edges is not an Array");
+  }
+
+  if (typeof Ctor === "string") {
+    switch(Ctor) {
+      case "graph": Ctor = Graph; break;
+      case "digraph": Ctor = Digraph; break;
+      case "cgraph": Ctor = CGraph; break;
+      case "cdigraph": Ctor = CDigraph; break;
+      default: throw new Error("Unrecognized graph type: " + Ctor);
+    }
+  }
+
+  var graph = new Ctor();
+
+  nodes.forEach(function(u) {
+    graph.addNode(u.id, u.value);
+  });
+
+  // If the graph is compound, set up children...
+  if (graph.parent) {
+    nodes.forEach(function(u) {
+      if (u.children) {
+        u.children.forEach(function(v) {
+          graph.parent(v, u.id);
+        });
+      }
+    });
+  }
+
+  edges.forEach(function(e) {
+    graph.addEdge(e.id, e.u, e.v, e.value);
+  });
+
+  return graph;
+};
+
+exports.encode = function(graph) {
+  var nodes = [];
+  var edges = [];
+
+  graph.eachNode(function(u, value) {
+    var node = {id: u, value: value};
+    if (graph.children) {
+      var children = graph.children(u);
+      if (children.length) {
+        node.children = children;
+      }
+    }
+    nodes.push(node);
+  });
+
+  graph.eachEdge(function(e, u, v, value) {
+    edges.push({id: e, u: u, v: v, value: value});
+  });
+
+  var type;
+  if (graph instanceof CDigraph) {
+    type = "cdigraph";
+  } else if (graph instanceof CGraph) {
+    type = "cgraph";
+  } else if (graph instanceof Digraph) {
+    type = "digraph";
+  } else if (graph instanceof Graph) {
+    type = "graph";
+  } else {
+    throw new Error("Couldn't determine type of graph: " + graph);
+  }
+
+  return { nodes: nodes, edges: edges, type: type };
+};
+
+function typeOf(obj) {
+  return Object.prototype.toString.call(obj).slice(8, -1);
+}
+
+},{"../CDigraph":26,"../CGraph":27,"../Digraph":28,"../Graph":29}],43:[function(require,module,exports){
+/* jshint -W079 */
+var Set = require("cp-data").Set;
+/* jshint +W079 */
+
+exports.all = function() {
+  return function() { return true; };
+};
+
+exports.nodesFromList = function(nodes) {
+  var set = new Set(nodes);
+  return function(u) {
+    return set.has(u);
+  };
+};
+
+},{"cp-data":19}],44:[function(require,module,exports){
+var Graph = require("./Graph"),
+    Digraph = require("./Digraph");
+
+// Side-effect based changes are lousy, but node doesn't seem to resolve the
+// requires cycle.
+
+/**
+ * Returns a new directed graph using the nodes and edges from this graph. The
+ * new graph will have the same nodes, but will have twice the number of edges:
+ * each edge is split into two edges with opposite directions. Edge ids,
+ * consequently, are not preserved by this transformation.
+ */
+Graph.prototype.toDigraph =
+Graph.prototype.asDirected = function() {
+  var g = new Digraph();
+  this.eachNode(function(u, value) { g.addNode(u, value); });
+  this.eachEdge(function(e, u, v, value) {
+    g.addEdge(null, u, v, value);
+    g.addEdge(null, v, u, value);
+  });
+  return g;
+};
+
+/**
+ * Returns a new undirected graph using the nodes and edges from this graph.
+ * The new graph will have the same nodes, but the edges will be made
+ * undirected. Edge ids are preserved in this transformation.
+ */
+Digraph.prototype.toGraph =
+Digraph.prototype.asUndirected = function() {
+  var g = new Graph();
+  this.eachNode(function(u, value) { g.addNode(u, value); });
+  this.eachEdge(function(e, u, v, value) {
+    g.addEdge(e, u, v, value);
+  });
+  return g;
+};
+
+},{"./Digraph":28,"./Graph":29}],45:[function(require,module,exports){
+// Returns an array of all values for properties of **o**.
+exports.values = function(o) {
+  var ks = Object.keys(o),
+      len = ks.length,
+      result = new Array(len),
+      i;
+  for (i = 0; i < len; ++i) {
+    result[i] = o[ks[i]];
+  }
+  return result;
+};
+
+},{}],46:[function(require,module,exports){
+module.exports = '0.7.4';
+
+},{}]},{},[1])
+;
+joint.layout.DirectedGraph = {
+
+    layout: function(graph, opt) {
+
+        opt = opt || {};
+
+        var inputGraph = this._prepareData(graph);
+        var runner = dagre.layout();
+
+        if (opt.debugLevel) { runner.debugLevel(opt.debugLevel); }
+        if (opt.rankDir) { runner.rankDir(opt.rankDir); }
+        if (opt.rankSep) { runner.rankSep(opt.rankSep); }
+        if (opt.edgeSep) { runner.edgeSep(opt.edgeSep); }
+        if (opt.nodeSep) { runner.nodeSep(opt.nodeSep); }
+
+        var layoutGraph = runner.run(inputGraph);
+
+        layoutGraph.eachNode(function(u, value) {
+            if (!value.dummy) {
+                graph.get('cells').get(u).set('position', {
+                    x: value.x - value.width/2,
+                    y: value.y - value.height/2
+                });
+            }
+        });
+
+        if (opt.setLinkVertices) {
+
+            layoutGraph.eachEdge(function(e, u, v, value) {
+                var link = graph.get('cells').get(e);
+                if (link) {
+                    graph.get('cells').get(e).set('vertices', value.points);
+                }
+            });
+        }
+
+        return { width: layoutGraph.graph().width, height: layoutGraph.graph().height };
+    },
+
+    _prepareData: function(graph) {
+        var dagreGraph = new dagre.Digraph();
+
+        // For each element.
+        _.each(graph.getElements(), function(cell) {
+
+            if (dagreGraph.hasNode(cell.id)) return;
+
+            dagreGraph.addNode(cell.id, {
+                width: cell.get('size').width,
+                height: cell.get('size').height,
+                rank: cell.get('rank')
+            });
+        });
+
+        // For each link.
+        _.each(graph.getLinks(), function(cell) {
+
+            if (dagreGraph.hasEdge(cell.id)) return;
+
+            var sourceId = cell.get('source').id;
+            var targetId = cell.get('target').id;
+
+            dagreGraph.addEdge(cell.id, sourceId, targetId, { minLen: cell.get('minLen') || 1 });
+        });
+
+        return dagreGraph;
+    }
+};
diff --git a/js/joint.shapes.erd.js b/js/joint.shapes.erd.js
new file mode 100644 (file)
index 0000000..3012582
--- /dev/null
@@ -0,0 +1,229 @@
+/*! JointJS v0.9.0 - JavaScript diagramming library  2014-05-13 
+
+
+This Source Code Form is subject to the terms of the Mozilla Public
+License, v. 2.0. If a copy of the MPL was not distributed with this
+file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+if (typeof exports === 'object') {
+
+    var joint = {
+        util: require('../src/core').util,
+        shapes: {},
+        dia: {
+            Element: require('../src/joint.dia.element').Element,
+            Link: require('../src/joint.dia.link').Link
+        }
+    };
+}
+
+
+joint.shapes.erd = {};
+
+joint.shapes.erd.Entity = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Entity',
+        size: { width: 150, height: 60 },
+        attrs: {
+            '.outer': {
+                fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2,
+                points: '100,0 100,60 0,60 0,0'
+            },
+            '.inner': {
+                fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2,
+                points: '95,5 95,55 5,55 5,5',
+                display: 'none'
+            },
+            text: {
+                text: 'Entity',
+                'font-family': 'Arial', 'font-size': 14,
+                ref: '.outer', 'ref-x': .5, 'ref-y': .5,
+                'x-alignment': 'middle', 'y-alignment': 'middle'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.erd.WeakEntity = joint.shapes.erd.Entity.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.WeakEntity',
+
+        attrs: {
+            '.inner' : { display: 'auto' },
+            text: { text: 'Weak Entity' }
+        }
+
+    }, joint.shapes.erd.Entity.prototype.defaults)
+});
+
+joint.shapes.erd.Relationship = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',
+    
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Relationship',
+        size: { width: 80, height: 80 },
+        attrs: {
+            '.outer': {
+                fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2,
+                points: '40,0 80,40 40,80 0,40'
+            },
+            '.inner': {
+                fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2,
+                points: '40,5 75,40 40,75 5,40',
+                display: 'none'
+            },
+            text: {
+                text: 'Relationship',
+                'font-family': 'Arial', 'font-size': 12,
+                ref: '.', 'ref-x': .5, 'ref-y': .5,
+                'x-alignment': 'middle', 'y-alignment': 'middle'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+});
+
+joint.shapes.erd.IdentifyingRelationship = joint.shapes.erd.Relationship.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.IdentifyingRelationship',
+
+        attrs: {
+            '.inner': { display: 'auto' },
+            text: { text: 'Identifying' }
+        }
+
+    }, joint.shapes.erd.Relationship.prototype.defaults)
+});
+
+joint.shapes.erd.Attribute = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><ellipse class="outer"/><ellipse class="inner"/></g><text/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Attribute',
+        size: { width: 100, height: 50 },
+        attrs: {
+            'ellipse': {
+                transform: 'translate(50, 25)'
+            },
+            '.outer': {
+                stroke: '#D35400', 'stroke-width': 2,
+                cx: 0, cy: 0, rx: 50, ry: 25,
+                fill: '#E67E22'
+            },
+            '.inner': {
+                stroke: '#D35400', 'stroke-width': 2,
+                cx: 0, cy: 0, rx: 45, ry: 20,
+                fill: 'transparent', display: 'none'
+            },
+            text: {
+                 'font-family': 'Arial', 'font-size': 14,
+                 ref: '.', 'ref-x': .5, 'ref-y': .5,
+                 'x-alignment': 'middle', 'y-alignment': 'middle'
+             }
+         }
+
+     }, joint.dia.Element.prototype.defaults)
+
+ });
+
+ joint.shapes.erd.Multivalued = joint.shapes.erd.Attribute.extend({
+
+     defaults: joint.util.deepSupplement({
+
+         type: 'erd.Multivalued',
+
+         attrs: {
+             '.inner': { display: 'block' },
+             text: { text: 'multivalued' }
+         }
+     }, joint.shapes.erd.Attribute.prototype.defaults)
+ });
+
+ joint.shapes.erd.Derived = joint.shapes.erd.Attribute.extend({
+
+     defaults: joint.util.deepSupplement({
+
+         type: 'erd.Derived',
+
+         attrs: {
+             '.outer': { 'stroke-dasharray': '3,5' },
+             text: { text: 'derived' }
+         }
+
+     }, joint.shapes.erd.Attribute.prototype.defaults)
+ });
+
+ joint.shapes.erd.Key = joint.shapes.erd.Attribute.extend({
+
+     defaults: joint.util.deepSupplement({
+
+         type: 'erd.Key',
+
+         attrs: {
+             ellipse: { 'stroke-width': 4 },
+             text: { text: 'key', 'font-weight': 'bold', 'text-decoration': 'underline' }
+         }
+     }, joint.shapes.erd.Attribute.prototype.defaults)
+});
+
+joint.shapes.erd.Normal = joint.shapes.erd.Attribute.extend({
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.Normal',
+
+        attrs: { text: { text: 'Normal' }}
+
+    }, joint.shapes.erd.Attribute.prototype.defaults)
+});
+
+joint.shapes.erd.ISA = joint.dia.Element.extend({
+
+    markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>',
+
+    defaults: joint.util.deepSupplement({
+
+        type: 'erd.ISA',
+        size: { width: 100, height: 50 },
+        attrs: {
+            polygon: {
+                points: '0,0 50,50 100,0',
+                fill: '#F1C40F', stroke: '#F39C12', 'stroke-width': 2
+            },
+            text: {
+                text: 'ISA',
+                ref: '.', 'ref-x': .5, 'ref-y': .3,
+                'x-alignment': 'middle', 'y-alignment': 'middle'
+            }
+        }
+
+    }, joint.dia.Element.prototype.defaults)
+
+});
+
+joint.shapes.erd.Line = joint.dia.Link.extend({
+
+    defaults: { type: "erd.Line" },
+
+    cardinality: function(value) {
+        this.set('labels', [{ position: -20, attrs: { text: { dy: -8, text: value }}}]);
+    }
+});
+
+if (typeof exports === 'object') {
+
+    module.exports = joint.shapes.erd;
+}
diff --git a/js/jquery.min.js b/js/jquery.min.js
new file mode 100644 (file)
index 0000000..73f33fb
--- /dev/null
@@ -0,0 +1,4 @@
+/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
+}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML="  <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],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>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
+},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
diff --git a/js/loadbalancer.js b/js/loadbalancer.js
new file mode 100644 (file)
index 0000000..4c7c967
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2014 SDN Hub
+ *
+ * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.
+ * You may not use this file except in compliance with this License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.gnu.org/licenses/gpl-3.0.txt
+ *
+ * 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.
+ */
+
+var url = "http://" + location.hostname + ":8080";
+var hostList = {};
+
+function updateHosts() {
+    var serverSelect = document.getElementById("servers");
+
+       $.getJSON(url.concat("/v1.0/hosts"), function(hosts){
+           $.each(hosts, function(key, value){
+            hostList[key] = value.mac
+            el = document.createElement("option");
+            el.textContent = key;
+            el.value = key;
+            serverSelect.appendChild(el);
+        });
+    });
+}
+    
+updateHosts();
+
+/* Format of the POST data is as follows:
+
+{'servers': list of {'ip': ip string, 'mac': mac string},
+'virtual_ip': ip string,
+'rewrite_ip': 0 or 1 }
+
+ */
+
+function makePostData() {
+    var vip = $('#virtual-ip').val();
+    var servers = $('#servers').val();
+    var rewriteIP = $('#rewrite-ip').is(':checked');
+    var lbConfig = {};
+    lbConfig['servers'] = [];
+
+    if (servers != undefined) {
+        for (i=0; i<servers.length;i++) {
+            var server = servers[i];
+            lbConfig['servers'].push({'ip': server, 'mac': hostList[server]});
+        }
+    }
+    lbConfig['virtual_ip'] = vip;
+
+    if (rewriteIP) 
+        lbConfig['rewrite_ip'] = 1;
+    else
+        lbConfig['rewrite_ip'] = 0;
+
+    return lbConfig;
+}
+
+
+function createLBPool() {
+    $('#post-status').html('');
+
+    var lbConfig = makePostData();
+    if (lbConfig == undefined)
+        return;
+
+    $.post(url.concat("/v1.0/loadbalancer/create"), JSON.stringify(lbConfig), function() { 
+    }, "json")
+    .done(function() {
+        $('#post-status').html('');
+        $('#main').html('<h2>Load-balancer pool created</h2><p>Successfully created load-balancer pool.  Start sending requests to the virtual IP.</p><button class="pure-button pure-button-primary" onclick="deleteLBPool(\''+lbConfig.virtual_ip+'\')">Delete LB pool</button>');
+    })
+    .fail(function() {
+        $('#post-status').html('<p style="color:red; background:silver;">Error: Load-balancer pool creation failed. Please verify your input.');
+    });
+}
+
+function deleteLBPool(vip) {
+    if (typeof(vip)==='undefined') {
+        vip = $('#virtual-ip').val();
+    }
+
+    $('#post-status').html('');
+
+    lbConfig = {};
+    lbConfig['virtual_ip'] = vip;
+    lbConfig['rewrite_ip'] = 1;
+    lbConfig.servers = [];
+
+    $.post(url.concat("/v1.0/loadbalancer/delete"), JSON.stringify(lbConfig), function() { 
+    }, "json")
+    .done(function() {
+        // In direct call cases where VIP was pre-specified in onClick,
+        // it will be best to direct to the original main even before
+        // the delete pool button click
+        $('#post-status').html('');
+        $('#main').html('<h2>Load-balancer pool deleted</h2><p>Successfully deleted load-balancer pool.</p><button class="pure-button pure-button-primary" onclick="window.location.reload()">Create LB pool</button>');
+    })
+    .fail(function() {
+        $('#post-status').html('<p style="color:red; background:silver;">Error: Load-balancer pool deletion failed. Please verify your input.');
+    });
+}
+
diff --git a/js/port-stats.js b/js/port-stats.js
new file mode 100644 (file)
index 0000000..41f0c7b
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2014 SDN Hub
+ *
+ * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.
+ * You may not use this file except in compliance with this License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.gnu.org/licenses/gpl-3.0.txt
+ *
+ * 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.
+ */
+
+var url = "http://" + location.hostname + ":8080";
+
+function updatePortStats() {
+    var statsTableBody = document.getElementById('port-stats-data');
+    while (statsTableBody.firstChild) {
+            statsTableBody.removeChild(statsTableBody.firstChild);
+    }
+
+    $.getJSON(url.concat("/stats/switches"), function(switches){
+        $.each(switches, function(index, dpid){
+            var hex_dpid = parseInt(dpid).toString(16);
+
+            $.getJSON(url.concat("/stats/port/").concat(dpid), function(ports) {
+                var portStats = ports[dpid];
+
+                var tr = document.createElement('TR');
+                var physicalPorts = 0;
+                var switchColTd = document.createElement('TD');
+                switchColTd.appendChild(document.createTextNode(hex_dpid));
+                tr.appendChild(switchColTd);
+
+                $.each(portStats, function(index, obj) {
+                    if (obj.port_no < 65280) {
+                        physicalPorts += 1;
+                        var statsArray = new Array(obj.port_no, obj.rx_packets, obj.rx_bytes, obj.rx_dropped, obj.rx_errors, obj.tx_packets, obj.tx_bytes, obj.tx_dropped, obj.tx_errors);
+
+                        $.each(statsArray, function(index, value) {
+                            var td = document.createElement('TD');
+                            td.appendChild(document.createTextNode(value));
+                            tr.appendChild(td);
+                        });
+                        statsTableBody.appendChild(tr);
+                        tr = document.createElement('TR');
+                    }
+                });
+
+                switchColTd.rowSpan = physicalPorts;
+            });
+        });
+    });
+}
+
+updatePortStats();
+
+var portStatsIntervalID = setInterval(function(){updatePortStats()}, 5000);
+
+function stopPortStatsTableRefresh() {
+    clearInterval(portStatsIntervalID);
+}
diff --git a/js/tap.js b/js/tap.js
new file mode 100644 (file)
index 0000000..c61c263
--- /dev/null
+++ b/js/tap.js
@@ -0,0 +1,223 @@
+/*
+ * Copyright (C) 2014 SDN Hub
+ *
+ * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.
+ * You may not use this file except in compliance with this License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.gnu.org/licenses/gpl-3.0.txt
+ *
+ * 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.
+ */
+
+var url = "http://" + location.hostname + ":8080";
+var originalMain;
+
+var portMap = {};
+
+function updateSwitchList() {
+    var switchSelect = document.getElementById("switch");
+    $.getJSON(url.concat("/v1.0/topology/switches"), function(switches){
+        $.each(switches, function(index, value){
+            var el = document.createElement("option");
+            el.textContent = value.dpid;
+            el.value = value.dpid;
+            switchSelect.appendChild(el);
+
+            portMap[value.dpid] = value.ports;
+        });
+    }).then(updatePorts);
+}
+
+function updatePorts() {
+    var srcPortSelect = document.getElementById("src-ports");
+    removeAllChildren(srcPortSelect);
+
+    var allEl = document.createElement("option");
+    allEl.textContent = "all";
+    allEl.value = "all";
+    allEl.setAttribute('selected', 'selected');
+    srcPortSelect.appendChild(allEl);
+
+    var sinkPortSelect = document.getElementById("sink-ports");
+    removeAllChildren(sinkPortSelect);
+
+    var dpid = $('#switch').val();
+    $.each(portMap[dpid], function(key, value) {
+        var portNum = parseInt(value.port_no);
+        var el = document.createElement("option");
+        el.textContent = portNum;
+        el.value = portNum;
+        srcPortSelect.appendChild(el);
+
+        el = document.createElement("option");
+        el.textContent = portNum;
+        el.value = portNum;
+        sinkPortSelect.appendChild(el);
+   });
+}
+
+/* Format of the POST data is as follows:
+
+{'fields': {'  'dl_src': mac string,
+               'dl_dst': mac string,
+               'dl_type': int,
+               'dl_vlan': int,
+               'nw_src': ip string,
+               'nw_dst': ip string,
+               'nw_proto': int,
+               'tp_src': int,
+               'tp_dst': int},
+'sources': list of {'dpid': int, 'port_no': int},
+'sinks': list of {'dpid': int, 'port_no': int}
+}
+
+ */
+
+function makePostData() {
+    var tapInfo = {};
+    var dpid = $('#switch').val();
+    var srcPorts = $('#src-ports').val();
+    var sinkPorts = $('#sink-ports').val();
+
+    if (sinkPorts == undefined) {
+        alert("Sink ports need to be specified.");
+        return undefined;
+    } 
+
+    tapInfo['sources'] = [];
+    tapInfo['sinks'] = [];
+    tapInfo['fields'] = {};
+
+    if ($.inArray('all', srcPorts) != -1)
+         tapInfo.sources.push({'dpid': parseInt(dpid), 'port_no': 'all'});
+    else {
+        $.each(srcPorts, function(index, value) {
+            port = {'dpid': parseInt(dpid), 'port_no': parseInt(value)};
+            tapInfo.sources.push(port);
+        });
+    }
+    $.each(sinkPorts, function(index, value) {
+        var port = {'dpid': parseInt(dpid), 'port_no': parseInt(value)};
+        tapInfo.sinks.push(port);
+    });
+
+    var macStr = $('#mac-addr').val();
+    var ipStr = $('#ip-addr').val();
+    var trafficType = $('#traffic-type').val();
+    var macClass = $('#mac-class').val();
+    var ipClass = $('#ip-class').val();
+
+    if (macClass != "--Ignore--") {
+        if (macStr == undefined || macStr=="") {
+            alert("MAC address needs to be specified.");
+            return undefined;
+        }
+    }
+    if (macClass == 'Source') 
+        tapInfo.fields['dl_src'] = macStr;
+    else if (macClass == 'Destination') 
+        tapInfo.fields['dl_dst'] = macStr;
+    else if (macClass == 'Src or Dest') 
+        tapInfo.fields['dl_host'] = macStr;
+
+    if (ipClass != "--Ignore--") {
+        if (ipStr == undefined || ipStr=="") {
+            alert("MAC address needs to be specified.");
+            return undefined;
+        }
+        tapInfo.fields['dl_type'] = 0x800;
+    }
+    if (ipClass == 'Source') 
+        tapInfo.fields['nw_src'] = ipStr;
+    else if (ipClass == 'Destination') 
+        tapInfo.fields['nw_dst'] = ipStr;
+    else if (ipClass == 'Src or Dest') 
+        tapInfo.fields['nw_host'] = ipStr;
+
+    if (trafficType == 'ARP') {
+        tapInfo.fields['dl_type'] = 0x806;
+    }
+
+    // Set prerequisite of IPv4 for all other types
+    else if (trafficType == 'ICMP') {
+        tapInfo.fields['dl_type'] = 0x800;
+        tapInfo.fields['nw_proto'] = 1;
+
+    } else if (trafficType == 'TCP') {
+        tapInfo.fields['dl_type'] = 0x800;
+        tapInfo.fields['nw_proto'] = 6;
+    }
+    else if (trafficType == 'HTTP') {
+        tapInfo.fields['dl_type'] = 0x800;
+        tapInfo.fields['nw_proto'] = 6;
+        tapInfo.fields['tp_port'] = 80;
+    }
+    else if (trafficType == 'HTTPS') {
+        tapInfo.fields['dl_type'] = 0x800;
+        tapInfo.fields['tp_port'] = 443;
+        tapInfo.fields['nw_proto'] = 6;
+    }
+    else if (trafficType == 'UDP') {
+        tapInfo.fields['dl_type'] = 0x800;
+        tapInfo.fields['nw_proto'] = 0x11;
+    }
+    else if (trafficType == 'DNS') {
+        tapInfo.fields['dl_type'] = 0x800;
+        tapInfo.fields['tp_port'] = 53;
+        tapInfo.fields['nw_proto'] = 0x11;
+    } else if (trafficType == 'DHCP') {
+        tapInfo.fields['dl_type'] = 0x800;
+        tapInfo.fields['tp_port'] = 67;
+        tapInfo.fields['nw_proto'] = 0x11;
+    } 
+    console.log(tapInfo.fields);
+
+    return tapInfo;
+}
+
+function restoreMain() {
+    $("#main").replaceWith(originalMain);
+    $('#post-status').html('');
+}
+
+function setTap() {
+    var tapInfo = makePostData();
+    if (tapInfo == undefined)
+        return;
+
+    $.post(url.concat("/v1.0/tap/create"), JSON.stringify(tapInfo), function() { 
+    }, "json")
+    .done(function() {
+        originalMain = $('#main').clone();
+        $('#post-status').html('');
+        $('#main').html('<h2>Tap created</h2><p>Successfully created tap. Check the <a href="/web/stats.html#flow">flow statistics</a> to verify that the rules have been created.</p><button class="pure-button pure-button-primary" onclick="restoreMain()">Create another tap</button>');
+    })
+    .fail(function() {
+        $('#post-status').html('<p style="color:red; background:silver;">Error: Tap creation failed. Please verify your input.');
+    });
+}
+
+
+function clearTap() {
+    var tapInfo = makePostData();
+    if (tapInfo == undefined)
+        return;
+
+    $.post(url.concat("/v1.0/tap/delete"), JSON.stringify(tapInfo), function() { 
+    }, "json")
+    .done(function() {
+        originalMain = $('#main').clone();
+        $('#post-status').html('');
+        $('#main').html('<h2>Tap deleted</h2><p>Successfully deleted tap. Check the <a href="/web/stats.html#flow">flow statistics</a> to verify that the rules have been deleted.</p><button class="pure-button pure-button-primary" onclick="restoreMain()">Create another tap</button>');
+    })
+    .fail(function() {
+        $('#post-status').html('<p style="color:red; background:silver;">Error: Tap deletion failed. Please verify your input.');
+    });
+}
+
+updateSwitchList();
+
diff --git a/js/topology.js b/js/topology.js
new file mode 100644 (file)
index 0000000..e8bc66d
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ * Copyright (C) 2014 SDN Hub
+ *
+ * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.
+ * You may not use this file except in compliance with this License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.gnu.org/licenses/gpl-3.0.txt
+ *
+ * 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.
+ */
+
+var switchList = {};
+var hostList = {};
+var hostSwitchLinkList = [];
+
+var url = "http://" + location.hostname + ":8080";
+var graph = new joint.dia.Graph;
+var erd = joint.shapes.erd;
+
+var element = function(elm, x, y, label) {
+    var cell = new elm({ position: { x: x, y: y }, size: { width: 150, height: 30 },
+             attrs: { text: { text: label }}});
+
+       cell.attr({
+                 rect: { fill: '#2C3E50', rx: 5, ry: 5, 'stroke-width': 2, stroke: 'black' },
+             text: {
+                 fill: 'white',
+                 'font-size': 16, 'font-weight': 'bold', 'font-variant': 'small-caps', 'text-transform': 'capitalize'
+             }
+         });
+    graph.addCell(cell);
+    return cell;
+};
+
+var link = function(elm1, elm2) {
+
+    var cell = new erd.Line({ source: { id: elm1.id }, target: { id: elm2.id },
+        attrs : { '.connection': { stroke: 'blue' } },
+        labels: [{ text: {'font-size': 10 } },
+                 { text: {'font-size': 10 } }]
+    });
+
+    try {
+        graph.addCell(cell);
+    } catch (e) {
+      console.log(e);
+    }
+    return cell;
+};
+
+var getSwitchDesc = function(dpid) {
+    var ofctl_dpid = parseInt(dpid, 16);
+    $.getJSON(url.concat("/stats/desc/").concat(ofctl_dpid), function(descs){
+           $.each(descs, function(key, value){
+            var valueJson = JSON.stringify(value);
+            var switchDesc = JSON.parse(valueJson);
+
+            switchList[dpid]['desc'] = switchDesc;
+        });
+    }).then(setSwitchTooltip);
+};
+
+var getDom = function(modelId) {
+    var elems = document.getElementsByClassName("element");
+    for (i=0;i < elems.length; i++) {
+        dom = document.getElementById(elems[i].id);
+        if (modelId == dom.getAttribute("model-id"))
+            return dom;
+    }
+    return undefined;
+};
+
+var setSwitchTooltip = function() {
+    $.each(switchList, function(dpid, value) {
+        var rectDom = getDom(value.element.id);
+        if (rectDom != undefined && value.desc != undefined) {
+            value['tooltip'] = new joint.ui.Tooltip({
+                    target: rectDom,
+                    content: '<span>Switch ' + value['name'] + '</span>' +
+                             '<hr><table>' +
+                             '<tr><td>H/w type:</td><td>' + value.desc.hw_desc + '</td></tr>' +
+                             '<tr><td>S/w version:</td><td>' + value.desc.sw_desc + '</td></tr>' +
+                             '<tr><td>Vendor:</td><td>' + value.desc.mfr_desc + '</td></tr>' +
+                             '<tr><td>Serial #:</td><td>' + value.desc.serial_num + '</td></tr>' +
+                             '<tr><td>Description:</td><td>' + value.desc.dp_desc + '</td></tr>' +
+                             '</table>',
+                    top: rectDom,
+                    direction: 'top'
+            });
+        }
+    });
+};
+
+var hostCleanup = function(currentHosts) {
+    $.each(hostList, function(key, value){
+        value.tooltip.remove();
+        try {
+        value.link.remove();
+      } catch (e) {
+        console.log(e);
+      }
+        if (!(key in currentHosts))
+            value.element.remove();
+    });
+};
+
+var drawHosts = function() {
+       srcSwitch = {};
+       dstSwitch = {};
+
+       $.getJSON(url.concat("/v1.0/hosts"), function(hosts){
+        //Remove old tooltips and host links
+        hostCleanup(hosts);
+
+           $.each(hosts, function(key, value){
+            //Do all common stuff for an IP
+            if (!(key in hostList))
+                hostList[key] = {};
+
+            if (!('element' in hostList[key])) {
+                var x = 1000, y=1000;
+                var cell = new erd.Normal({ position: { x: x, y: y }, attrs: { text: { text: key }}});
+                graph.addCell(cell);
+
+                hostList[key]['element'] = cell;
+                hostList[key]['dom'] = getDom(cell.id);
+            }
+
+            hostList[key]['entry'] = value;
+            var hostDom = hostList[key]['dom'];
+            var cell = hostList[key]['element'];
+
+            if (value.dpid in switchList && hostDom != undefined) {
+                var date = new Date(value.timestamp * 1000);
+                var dateStr = (date.getMonth() + 1) + "/" +
+                               date.getDate() + "/" +
+                               date.getFullYear() + " " +
+                               date.getHours() + ":" +
+                               date.getMinutes() + ":" +
+                               date.getSeconds();
+
+                hostList[key]['tooltip'] = new joint.ui.Tooltip({
+                        target: hostDom,
+                        content: '<table>' +
+                                 '<tr><td>IP:</td><td>' + key + '</td></tr>' +
+                                 '<tr><td>MAC:</td><td>' + value.mac + '</td></tr>' +
+                                 '<tr><td>Assoc switch:</td><td>' + value.dpid + '</td></tr>' +
+                                 '<tr><td>Assoc port:</td><td>' + value.port + '</td></tr>' +
+                                 '<tr><td>Time seen:</td><td>' + dateStr + '</td></tr>' +
+                                 '</table>',
+                        top: hostDom,
+                        direction: 'top'
+                });
+                
+                try{
+                hostList[key]['link'] =link(switchList[value.dpid]['element'], cell);
+              }catch(e){
+                console.log(e);
+              }
+            }
+               });
+    try {
+        joint.layout.DirectedGraph.layout(graph, { setLinkVertices: false, edgeSep: 20, rankSep: 80, nodeSep: 50 });
+      } catch (e) {
+        console.log(e)
+      }
+       });
+};
+
+var drawLinks = function() {
+       srcSwitch = {};
+       dstSwitch = {};
+       $.getJSON(url.concat("/v1.0/topology/links"), function(links){
+           $.each(links, function(key, value){
+            var valueJson = JSON.stringify(value);
+            var obj = JSON.parse(valueJson);
+
+            var portname = obj.src.name;
+
+
+            link(switchList[obj.src.dpid]['element'],
+                 switchList[obj.dst.dpid]['element']).cardinality(portname);
+               });
+    try{
+        joint.layout.DirectedGraph.layout(graph, { setLinkVertices: false, edgeSep: 20, rankSep: 80, nodeSep: 80 });
+      } catch (e) {
+        console.log(e)
+      }
+       }).then(drawHosts);
+}
+
+$(function()  {
+    var paperScroller = new joint.ui.PaperScroller;
+
+    var paper = new joint.dia.Paper({
+            el: paperScroller.el,
+            width: 2400,
+            height: 800,
+            model: graph
+    });
+
+    paperScroller.options.paper = paper;
+    $('#paper-container').append(paperScroller.render().el);
+    paper.on('blank:pointerdown', paperScroller.startPanning);
+
+$.getJSON(url.concat("/v1.0/topology/switches"), function(switches){
+       var counter = 0;
+    $.each(switches, function(index, value){
+               var valueJson = JSON.stringify(value);
+        var obj = JSON.parse(valueJson);
+
+        switchList[obj.dpid] = {}
+
+        var switchName = obj.dpid;
+        switchList[obj.dpid]['name'] = switchName;
+
+        var x = 200 + 150 * (index % 4);
+        var y = 100 + 150 * Math.floor(index/4);
+
+        //console.log("DPID: " + obj.dpid + " X = "+x + " Y = "+y)
+                   switchList[obj.dpid]['element'] = element(joint.shapes.basic.Rect, x, y, switchName);
+
+        getSwitchDesc(obj.dpid);
+        //console.log(switchList[obj.dpid]['element'])
+
+    });
+}).then(drawLinks);
+
+paper.on('cell:pointerdown',
+    function(cellView, evt, x, y) {
+        $.each(switchList, function(key, value) {
+          if (value.id == cellView.model.id) {
+            console.log("Clicked " + key);
+          }
+        });
+});
+
+var drawHostIntervalD = setInterval(function(){drawHosts()}, 10000);
+
+});
+/*
+graph.on('change:position', function(cell) {
+    var parentId = cell.get('parent');
+    if (!parentId) return;
+
+    var parent = graph.getCell(parentId);
+    var parentBbox = parent.getBBox();
+    var cellBbox = cell.getBBox();
+
+    if (parentBbox.containsPoint(cellBbox.origin()) &&
+        parentBbox.containsPoint(cellBbox.topRight()) &&
+        parentBbox.containsPoint(cellBbox.corner()) &&
+        parentBbox.containsPoint(cellBbox.bottomLeft())) {
+
+        // All the four corners of the child are inside
+        // the parent area.
+        return;
+    }
+
+    // Revert the child position.
+    cell.set('position', cell.previous('position'));
+});*/
diff --git a/js/utils.js b/js/utils.js
new file mode 100644 (file)
index 0000000..9541d76
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2014 SDN Hub
+ *
+ * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.
+ * You may not use this file except in compliance with this License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.gnu.org/licenses/gpl-3.0.txt
+ *
+ * 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.
+ */
+
+var ethertypeToString = function(type) {
+    switch (type) {
+        case 0x800: return "IPv4";
+        case 0x806: return "LLDP";
+        case 0x88cc: return "LLDP";
+        case 0x86dd: return "IPv6";
+        default: return "Unknown";
+    }
+}
+
+var nwprotoToString = function(type) {
+    switch (type) {
+        case 0x1: return "IPv4";
+        case 0x6: return "TCP";
+        case 0x11: return "UDP";
+        case 0x84: return "SCTP";
+        default: return "Unknown";
+    }
+}
+
+var removeAllChildren = function(node) {
+    while (node.firstChild) {
+            node.removeChild(node.firstChild);
+    }
+}
+
diff --git a/styles/font-awesome.min.css b/styles/font-awesome.min.css
new file mode 100644 (file)
index 0000000..5e07018
--- /dev/null
@@ -0,0 +1,4 @@
+/*!
+ *  Font Awesome 4.1.0 by @davegandy - http://fontawesome.io - @fontawesome
+ *  License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
+ */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.1.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff') format('woff'),url('../fonts/fontawesome-webfont.ttf') format('truetype'),url('../fonts/fontawesome-webfont.svg') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:spin 2s infinite linear;-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;animation:spin 2s infinite linear}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg)}100%{-moz-transform:rotate(359deg)}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg)}100%{-o-transform:rotate(359deg)}}@keyframes spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);-webkit-transform:scale(-1, 1);-moz-transform:scale(-1, 1);-ms-transform:scale(-1, 1);-o-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);-webkit-transform:scale(1, -1);-moz-transform:scale(1, -1);-ms-transform:scale(1, -1);-o-transform:scale(1, -1);transform:scale(1, -1)}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper-square:before,.fa-pied-piper:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}
diff --git a/styles/joint.all.min.css b/styles/joint.all.min.css
new file mode 100644 (file)
index 0000000..5c11d0c
--- /dev/null
@@ -0,0 +1,15 @@
+/*! Rappid - the diagramming toolkit
+
+Copyright (c) 2014 client IO
+
+ 2014-05-13 
+
+
+This Source Code Form is subject to the terms of the Rappid Academic License
+, v. 1.0. If a copy of the Rappid License was not distributed with this
+file, You can obtain one at http://jointjs.com/license/rappid_academic_v1.txt
+ or from the Rappid archive as was distributed by client IO. See the LICENSE file.*/
+
+
+
+.viewport{-webkit-user-select:none;-moz-user-select:none;user-select:none}[magnet=true]:not(.element){cursor:crosshair}[magnet=true]:not(.element):hover{opacity:.7}.element{cursor:move}.element *{vector-effect:non-scaling-stroke;-moz-user-select:none;user-drag:none}.connection-wrap{fill:none;stroke:#000;stroke-width:15;stroke-linecap:round;stroke-linejoin:round;opacity:0;cursor:move}.connection-wrap:hover{opacity:.4;stroke-opacity:.4}.connection{fill:none;stroke-linejoin:round}.marker-source,.marker-target{vector-effect:non-scaling-stroke}.marker-vertices{opacity:0;cursor:move}.marker-arrowheads{opacity:0;cursor:move;cursor:-webkit-grab;cursor:-moz-grab}.link-tools{opacity:0;display:none;cursor:pointer}.link-tools .tool-options{display:none}.link-tools .tool-remove circle{fill:red}.link-tools .tool-remove path{fill:#fff}.link:hover .marker-vertices,.link:hover .marker-arrowheads,.link:hover .link-tools{opacity:1}.marker-vertex{fill:#1ABC9C}.marker-vertex:hover{fill:#34495E;stroke:none}.marker-arrowhead{fill:#1ABC9C}.marker-arrowhead:hover{fill:#F39C12;stroke:none}.marker-vertex-remove{cursor:pointer;opacity:.1;fill:#fff}.marker-vertex-group:hover .marker-vertex-remove{opacity:1}.marker-vertex-remove-area{opacity:.1;cursor:pointer}.marker-vertex-group:hover .marker-vertex-remove-area{opacity:1}text.highlighted{fill:red}.highlighted{outline:2px solid red;opacity:.7 \9}@-moz-document url-prefix(){.highlighted{opacity:.7}.element .fobj,.element .fobj body,.element .fobj div{pointer-events:none}}doesnotexist:-o-prefocus,.highlighted{opacity:.7}@media screen and (-ms-high-contrast:active),(-ms-high-contrast:none){.highlighted{opacity:.7}}.element .fobj body{background-color:transparent;margin:0}.element .fobj div{text-align:center;vertical-align:middle;display:table-cell;padding:0 5px}.paper-scroller{position:relative;overflow:scroll;cursor:move;cursor:-moz-grabbing;cursor:-webkit-grabbing}.selection{position:absolute;background-color:#3498DB;opacity:.3;border:2px solid #2980B9;overflow:visible}.selection.selected{background-color:transparent;border:0;opacity:1;cursor:move;position:static;height:0!important}.selection-box{position:absolute;border:1px solid #000}.halo{position:absolute;pointer-events:none}.halo>div{position:absolute;pointer-events:auto;width:20px;height:20px;background-size:20px 20px;background-repeat:no-repeat;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;-webkit-user-drag:none;user-drag:none}.halo .handle{cursor:pointer}.halo.animate>div{transition:background-size 80ms,width 80ms,height 80ms,top 150ms,left 150ms,bottom 150ms,right 150ms}.halo.small>div{width:15px;height:15px;background-size:15px 15px}.halo.tiny>div{width:10px;height:10px;background-size:10px 10px}.halo .handle.se{bottom:-25px;right:-25px}.halo.small .handle.se{bottom:-19px;right:-19px}.halo.tiny .handle.se{bottom:-13px;right:-13px}.halo .handle.nw{top:-21px;left:-25px}.halo.small .handle.nw{top:-19px;left:-19px}.halo.tiny .handle.nw{top:-13px;left:-13px}.halo .handle.n{top:-22px;left:50%;margin-left:-10px}.halo.small .handle.n{top:-19px;margin-left:-7.5px}.halo.tiny .handle.n{top:-13px;margin-left:-5px}.halo .handle.e{right:-25px;top:-webkit-calc(50% - 10px);top:calc(50% - 10px)}.halo.small .handle.e{right:-19px;top:-webkit-calc(50% - 8px);top:calc(50% - 8px)}.halo.tiny .handle.e{right:-13px;top:-webkit-calc(50% - 5px);top:calc(50% - 5px)}.halo .handle.ne{top:-21px;right:-25px}.halo.small .handle.ne{top:-19px;right:-19px}.halo.tiny .handle.ne{top:-13px;right:-13px}.halo .handle.w{left:-25px;top:50%;margin-top:-10px}.halo.small .handle.w{left:-19px;margin-top:-8px}.halo.tiny .handle.w{left:-13px;margin-top:-5px}.halo .handle.sw{bottom:-25px;left:-25px}.halo.small .handle.sw{bottom:-19px;left:-19px}.halo.tiny .handle.sw{bottom:-13px;left:-13px}.halo .handle.s{bottom:-24px;left:50%;margin-left:-10px}.halo.small .handle.s{bottom:-19px;margin-left:-7.5px}.halo.tiny .handle.s{bottom:-13px;margin-left:-5px}.halo .resize{cursor:se-resize;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2RpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo2NjREODhDMjc4MkVFMjExODUyOEU5NTNCRjg5OEI3QiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDowQTc4MzUwQjJGMEIxMUUyOTFFNUE1RTAwQ0EwMjU5NyIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDowQTc4MzUwQTJGMEIxMUUyOTFFNUE1RTAwQ0EwMjU5NyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo2NjREODhDMjc4MkVFMjExODUyOEU5NTNCRjg5OEI3QiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo2NjREODhDMjc4MkVFMjExODUyOEU5NTNCRjg5OEI3QiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pk3oY88AAAEMSURBVHja7JftDYMgEIbRdABHcARG6CalGziCG3QE3KAj0A0cod3AEa6YUEMpcKeI9oeXvP5QuCeA90EBAGwPK7SU1hkZ12ldiT6F1oUycARDRHLBgiTiEzCwTNhNuRT8XOEog/AyMqlOXPEuZzx7q29aXGtIhLvQwfNuAgtrYgrcB+VWqH2BhceBD45ZE4EyB/7zIQTvCeAWgdpw1CqT2Sri2LsRZ4cddtg/GLfislo55oNZxE2ZLcFXT8haU7YED9yXpxsCGMvTn4Uqe7DIXJnsAqGYB5CjFnNT6yEE3qr7iIJT+60YXJUZQ3G8ALyof+JWfTV6xrluEuqkHw/ESW3CoJsBRVubtwADAI2b6h9uJAFqAAAAAElFTkSuQmCC)}.halo .remove{cursor:pointer;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAO5JREFUeNrUV9sNwyAMtLoAI3SEjJIRMgqjdBRG8CiMQGnlVHwEOBAE19L9OdwRGz+IcNsibISLCBk48dlooB0RXCDNgeXbbntWbovCyVlNtkf4AeQnvJwJ//IwCQdy8zAZeynm/gYBPpcT7gbyNDGb4/4CnyOLb1M+MED+MVPxZfEhQASnFQ4hp4qIlJxAEd+KaQGlpiIC8bmCRZOvRNBL/kvGltp+RdRLfqK5wZhCITMdjaury5lB5OFBCuxvQjAtCZc/w+WFaHkpXt6MVLTj5QOJipFs+VCqYixXsZioWM1GLaf7yK45ZT1/CzAAESidXQn9F/MAAAAASUVORK5CYII=)}.halo .clone{cursor:move;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2RpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo2NjREODhDMjc4MkVFMjExODUyOEU5NTNCRjg5OEI3QiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoxNTM0NjJBRjJGMkQxMUUyQkRFM0FCRTMxMDhFQkE2QiIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoxNTM0NjJBRTJGMkQxMUUyQkRFM0FCRTMxMDhFQkE2QiIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo2NjREODhDMjc4MkVFMjExODUyOEU5NTNCRjg5OEI3QiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo2NjREODhDMjc4MkVFMjExODUyOEU5NTNCRjg5OEI3QiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PkJFWv4AAAD3SURBVHja5FfRDYMgED2bDsAIjsAIMAluoqs4CY7gCI7ABtTTnsEUNCVQanzJGT/Qx7t7HFBZa6EEHlAIxYh90HPYzCHul+pixM93TV1wfDRNA0qppGRSyh2x8A2q6xqEEIc/mqZpCcTZWJ/iaPR9D13XLe/fNqKiNd6lahxHMMb8jlhrvRlgGAbvYJwQTsytMcH9hjEGnPN0NUZS15khx2L2SMi1GwgqQfdSkKPJ1RRnau/ZMq9J3LbtVtfodezrw6H1nAp2NeWK2bm5Tx9lTyAfilNhXuOkTv/n7hTqwbFwN5DDVGcMHVIsM2fVu7lXt7s7vQQYAIMHB7xhVbHdAAAAAElFTkSuQmCC)}.halo .link{cursor:move;cursor:-moz-grabbing;cursor:-webkit-grabbing;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjIwRkVFNkM3MkU3RjExRTJBMDA3RkZBQzMyMzExQzIzIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjIwRkVFNkM4MkU3RjExRTJBMDA3RkZBQzMyMzExQzIzIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MjBGRUU2QzUyRTdGMTFFMkEwMDdGRkFDMzIzMTFDMjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6MjBGRUU2QzYyRTdGMTFFMkEwMDdGRkFDMzIzMTFDMjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5hjT/5AAAA8ElEQVR42syXwQ3DIAxFUbtAR+gIHLsSN2+SboA6CSOEMbghJqCAHKlNmwYwkWvpKwdinmRsY4Sos2sSJJkknxRX8rgG+C/ZJG4YG2XQt9kuSVMHcK0J96qGzgOgi+Ya+GhoFfwo6C5890wBIGqto5SScuYf2fvTKcMW895T4G/ZblrARLh5bQ5VTjnMg+ClyUCL0yA4iJ7ONABewu17koQIz8z+2iTCaY3hG7zG7yQYjS3UbMnFVk5sDYStZbJdEizX4hnBDqeD21bNOedECKF8lVLCWttTuvekx9+MPmzDHut4yzrQsz5hDn+0PQUYAOGQcmTsT0IpAAAAAElFTkSuQmCC)}.halo .fork{cursor:move;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QUUEAUZcNUVHAAAALtJREFUWMPtlt0RgjAMgL9zAkZglI7ACLoJm8RNHIERGMER6ksfsIeRtsGq9LvLW2i+oz8JNBoHYAZcTQEfQoCupoAH7sBZS1jGDAwbCgwh1yfEDejfCSx/3SsksXAcIxsTZYfiSQJrEiUCT1sQ45TFNQkJ33aphzB1f9ckZK9rKBkHM2YqfYgsJIr5aYnJshfkSJj3Ak3C5fQCSwmTh+hTEh4YTwUCF+D6DRNPcTuuPpD8/UhWfShtNFQe+d/oVK9MAB0AAAAASUVORK5CYII=)}.halo .unlink{cursor:pointer;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjJCNjcxNUZBMkU3RjExRTI5RURCRDA5NDlGRDBFMDgwIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjJCNjcxNUZCMkU3RjExRTI5RURCRDA5NDlGRDBFMDgwIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MkI2NzE1RjgyRTdGMTFFMjlFREJEMDk0OUZEMEUwODAiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6MkI2NzE1RjkyRTdGMTFFMjlFREJEMDk0OUZEMEUwODAiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5htS6kAAABHElEQVR42uxW0Q2DIBBV0wEcwRHsBo7QERjBbkAnYARGaDdghI5gN9ANKCRHQy4HxFakH77kxeTAe95xd1JrrasSaKpCOIR3R2+oDLXHp+GQU3RAYhyezsZyCU8gwJGdgX3+wXcHfi1HyOwHGsQpuMjXprwFMU3QavGTtzHkwGJZIXoxFBBtyOer8opKog0ykQ0qrSoQpTsy7gfZg9EtKu/cnbBvm4iC454PijKUgQ4WYy9rot0Y6gBMhQvKoY70dYs+TERqAcOe4dXwsUXbWdF7IgsztM3/jsziqd69uLZqp/GbdgoNEJF7gMR+BC7KfuXInBIfwJrELF4Ss5yCLaiz4S3isyv6W8QXAbHXRaDI1ac+LvSHcC68BRgAHv/CnODh8mEAAAAASUVORK5CYII=)}.halo .rotate{cursor:move;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjI1NTk5RUFBMkU3RjExRTI4OUIyQzYwMkMyN0MxMDE3IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjI1NTk5RUFCMkU3RjExRTI4OUIyQzYwMkMyN0MxMDE3Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MjU1OTlFQTgyRTdGMTFFMjg5QjJDNjAyQzI3QzEwMTciIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6MjU1OTlFQTkyRTdGMTFFMjg5QjJDNjAyQzI3QzEwMTciLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6W+5aDAAABJElEQVR42syXbRGDMAyGYTcBOBgSkICESWAOmAMcTAJzgAQksCnYHFRC13Jlx7qkDf0Acvf+6ZF7mjRNQ8o5T/ZqmVAt1AkxIa5JrvXqmywUsAVANkmf3BV6RqKjSvpWlqD+7OYBhKKHoMNS6EuddaPUqjUqfIJyPb2Ysyye0pC6Qm0I8680KJ/vhDmcFbU2mAb9glvk48KhMAtiYY7RYunxuRVWcI2cqa/ZegBYFGWA5jPYwAy4MrGhI1hf6FaA8gPg/PSA9tSbcAz8il2XOIRM9SILXVxki3GdEvUmD6bhIHYDQeFrtEwUvsYj0WBRx34Wc5cXJcQg8GMpMPrUBsBb6DHrbie1IdNUeRe6UNLVRB72Nh1v9zfQR/+FSbf6afsIMAB0elCwFZfPigAAAABJRU5ErkJggg==)}.halo .box{position:absolute;top:100%;margin-top:30px;left:-20px;right:-20px;text-align:center;color:#fff;font-size:10px;line-height:14px;background-color:#1ABC9C;border-radius:6px;padding:6px}.halo.small .box{margin-top:25px}.halo.tiny .box{margin-top:20px}.halo .link.halo-magnet{opacity:.1;transition:none;display:none}.halo .link.halo-magnet:hover{opacity:1}.stencil{width:200px;float:left;border:1px solid gray}.stencil .elements{background-color:#fff;height:100%;width:100%}.stencil-paper-drag{position:absolute;z-index:100;width:800;height:800;top:-10000;left:-10000;display:none}.stencil-paper-drag.dragging{display:block;opacity:.7}.stencil .group{overflow:hidden;padding-left:10px;margin-bottom:1px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;transition:max-height 400ms linear;max-height:400px}.stencil .group.closed{height:26px;max-height:26px}.stencil .group>.group-label{padding:5px 4px;position:relative;left:-10px;margin-right:-20px;margin-top:0;margin-bottom:0;font-size:10px;font-weight:700;text-transform:uppercase;border-top:1px solid #3a3a3a;border-bottom:2px solid #1f1f1f;background:#242424;cursor:pointer;color:#bcbcbc}.stencil .group>.group-label:before{content:'';width:0;height:0;display:inline-block;margin-left:2px;margin-right:5px;position:relative;top:5px;border-top:5px solid #fff;border-right:5px solid transparent;border-left:5px solid transparent;border-bottom:5px solid transparent}.stencil .group.closed>.group-label:before{top:2px;left:2px;border-top:5px solid transparent;border-bottom:5px solid transparent;border-right:5px solid transparent;border-left:5px solid #fff}.stencil .element [magnet]{pointer-events:none}.inspector{position:absolute;top:0;bottom:0;right:0;left:0;overflow:auto}.inspector label{display:block;margin-top:5px;margin-bottom:10px;font-size:12px}.inspector input,.inspector textarea{width:200px;text-shadow:0 -1px 0 #000;color:#ddd;box-shadow:inset 0 0 0 1px rgba(0,0,0,.1),0 0 0 1px rgba(255,255,255,.1);border:1px solid #000;background:transparent;height:20px;line-height:20px}.inspector input[type=range]{height:1px;line-height:1px}@media screen and (min-width:0\0){.inspector input[type=range]{height:20px;line-height:20px}}@media screen and (-ms-high-contrast:active),(-ms-high-contrast:none){.inspector .group>.field>form{height:60px}.inspector input[type=range]{height:10px;border-style:hidden;box-shadow:none}.inspector input[type=range]::-ms-fill-lower{background-color:lightgray}.inspector input[type=range]::-ms-fill-upper{background-color:#fff}.inspector input[type=range]::-ms-track{color:transparent}.inspector input[type=range]::-ms-thumb{background-color:#242424;border-style:hidden}.inspector input[type=range]::-ms-tooltip{display:none}}.inspector .group{overflow:hidden;padding:10px}.inspector .group.closed{height:16px}.inspector .group>.group-label{padding:5px 4px;position:relative;left:-10px;margin-right:-20px;margin-top:0;margin-bottom:0;font-size:10px;font-weight:700;text-transform:uppercase;border-top:1px solid #3a3a3a;border-bottom:2px solid #1f1f1f;background:#242424;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.inspector .group>.group-label:before{content:'';width:0;height:0;display:inline-block;margin-left:2px;margin-right:5px;position:relative;top:5px;border-top:5px solid #fff;border-right:5px solid transparent;border-left:5px solid transparent;border-bottom:5px solid transparent}.inspector .group.closed>.group-label:before{top:2px;left:2px;border-top:5px solid transparent;border-bottom:5px solid transparent;border-right:5px solid transparent;border-left:5px solid #fff}.link-tools .tool-options{display:block}.inspector .toggle{position:relative;width:97px;height:14px}.inspector .toggle input{top:0;right:0;bottom:0;left:0;-ms-filter:"alpha(Opacity=0)";filter:alpha(opacity=0);-moz-opacity:0;opacity:0;z-index:100;position:absolute;width:100%;height:100%;cursor:pointer;box-sizing:border-box;padding:0;box-shadow:none;-webkit-appearance:none}.inspector .toggle input:checked+span{background:#9abb82}.inspector .toggle span{display:block;width:100%;height:100%;background:#a5a39d;border-radius:40px;box-shadow:inset 0 3px 8px 1px rgba(0,0,0,.2),0 1px 0 rgba(255,255,255,.5);position:relative}.inspector .toggle span:before{box-sizing:border-box;padding:0;margin:0;content:"";position:absolute;z-index:-1;top:-18px;right:-18px;bottom:-18px;left:-18px;border-radius:inherit;background:#eee;background:-moz-linear-gradient(#e5e7e6,#eee);background:-ms-linear-gradient(#e5e7e6,#eee);background:-o-linear-gradient(#e5e7e6,#eee);background:-webkit-gradient(linear,0 0,0 100%,from(#e5e7e6),to(#eee));background:-webkit-linear-gradient(#e5e7e6,#eee);background:linear-gradient(#e5e7e6,#eee);box-shadow:0 1px 0 rgba(255,255,255,.5)}.inspector .toggle input:checked+span i{right:-1%}.inspector .toggle input:checked+span i:before{content:"on";right:115%;color:#82a06a;text-shadow:0 1px 0 #afcb9b,0 -1px 0 #6b8659}.inspector .toggle span i{display:block;height:100%;width:60%;border-radius:inherit;background:silver;position:absolute;z-index:2;right:40%;top:0;background:#b2ac9e;background:-moz-linear-gradient(#f7f2f6,#b2ac9e);background:-ms-linear-gradient(#f7f2f6,#b2ac9e);background:-o-linear-gradient(#f7f2f6,#b2ac9e);background:-webkit-gradient(linear,0 0,0 100%,from(#f7f2f6),to(#b2ac9e));background:-webkit-linear-gradient(#f7f2f6,#b2ac9e);background:linear-gradient(#f7f2f6,#b2ac9e);box-shadow:inset 0 1px 0 white,0 0 8px rgba(0,0,0,.3),0 5px 5px rgba(0,0,0,.2)}.inspector .toggle span i:before{content:"off";text-transform:uppercase;font-style:normal;font-weight:700;color:rgba(0,0,0,.4);text-shadow:0 1px 0 #bcb8ae,0 -1px 0 #97958e;font-family:Helvetica,Arial,sans-serif;font-size:10px;position:absolute;top:50%;margin-top:-5px;right:-50%}.inspector .btn-list-add,.inspector .btn-list-del{background:transparent;color:#fff;border:1px solid gray;cursor:pointer;border-radius:2px;box-shadow:1px 1px 1px #000;width:23px;margin:2px;margin-right:8px}.inspector .btn-list-add:hover,.inspector .btn-list-del:hover{box-shadow:inset 1px 1px 1px #000}.inspector .list-items{margin-top:4px}.inspector .list-item{margin-top:2px;border:1px solid #242424;padding:10px;background-color:#3a3a3a;box-shadow:inset 0 0 2px gray}.inspector .list-item input{width:150px}.inspector .list-item .list-item input{width:125px}.inspector .list-item>.field>label{display:none}.inspector .field{display:inline}.inspector .hidden{display:none}.free-transform{position:absolute;pointer-events:none;border:1px dashed #000;border-radius:5px;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;-webkit-user-drag:none;user-drag:none}.free-transform>div{position:absolute;pointer-events:auto;background-color:#c0392b;border:1px solid #000}.free-transform>div:hover{background-color:#e74c3c}.free-transform .resize{border-radius:6px;width:8px;height:8px}.free-transform .resize[data-position=top-left]{top:-6px;left:-6px}.free-transform .resize[data-position=top-right]{top:-6px;right:-6px}.free-transform .resize[data-position=bottom-left]{bottom:-6px;left:-6px}.free-transform .resize[data-position=bottom-right]{bottom:-6px;right:-6px}.free-transform .resize[data-position=top]{top:-6px;left:50%;margin-left:-6px}.free-transform .resize[data-position=bottom]{bottom:-6px;left:50%;margin-left:-6px}.free-transform .resize[data-position=left]{left:-6px;top:50%;margin-top:-8px}.free-transform .resize[data-position=right]{right:-6px;top:50%;margin-top:-8px}.free-transform .resize.n{cursor:n-resize}.free-transform .resize.s{cursor:s-resize}.free-transform .resize.e{cursor:e-resize}.free-transform .resize.w{cursor:w-resize}.free-transform .resize.ne{cursor:ne-resize}.free-transform .resize.nw{cursor:nw-resize}.free-transform .resize.se{cursor:se-resize}.free-transform .resize.sw{cursor:sw-resize}.free-transform .rotate{border-radius:6px;width:10px;height:10px;top:-20px;left:-20px;cursor:pointer}.free-transform.in-operation{border-style:hidden}.free-transform.in-operation>div{display:none}.free-transform>div.in-operation{display:block;background-color:#e74c3c}.tooltip{position:fixed;z-index:100;border-radius:5px;background-color:#333;border:2px solid #242424;color:#bcbcbc;pointer-events:none;padding:10px;font-size:14px;text-shadow:0 -1px 0 #000}.tooltip.small{padding:5px;font-size:10px}.tooltip:after,.tooltip:before{border:solid transparent;content:" ";height:0;width:0;position:absolute;pointer-events:none}.tooltip.left:after,.tooltip.left:before{right:100%;top:50%}.tooltip.right:after,.tooltip.right:before{top:50%;left:100%}.tooltip.top:after,.tooltip.top:before{left:50%;bottom:100%}.tooltip.bottom:after,.tooltip.bottom:before{left:50%;top:100%}.tooltip:after{border-width:6px}.tooltip.left:after{border-right-color:#333;margin-top:-6px}.tooltip.right:after{border-left-color:#333;margin-top:-6px}.tooltip.top:after{border-bottom-color:#333;margin-left:-6px}.tooltip.bottom:after{border-top-color:#333;margin-left:-6px}.tooltip:before{border-width:8px}.tooltip.left:before{border-right-color:#242424;margin-top:-8px}.tooltip.right:before{border-left-color:#242424;margin-top:-8px}.tooltip.top:before{border-bottom-color:#242424;margin-left:-8px}.tooltip.bottom:before{border-top-color:#242424;margin-left:-8px}@media print{@page{margin:5mm}body{margin:0!important;padding:0!important}body:before{content:'JointJS';font-size:15mm;position:absolute;top:5mm;right:5mm;z-index:100000}.fobj>body:before{display:none}.printarea{left:0!important;top:0!important;background:none!important;border:0!important;margin:0;!important;padding:0;!important;overflow:visible;!important;z-index:99999}.printarea>:not(svg){display:none}}@media print and (orientation:landscape){.printarea.a4{width:270mm!important;height:168mm!important}}@media print and (orientation:portrait){.printarea.a4{width:200mm!important;height:232mm!important}}
diff --git a/styles/pure-custom.css b/styles/pure-custom.css
new file mode 100644 (file)
index 0000000..5e1f10d
--- /dev/null
@@ -0,0 +1,985 @@
+html, button, input, select, textarea,
+.pure-g [class *= "pure-u"] {
+    font-family: "proxima-nova", sans-serif;
+}
+
+
+/* --------------------------
+ * Element Styles
+ * --------------------------
+*/
+
+body {
+    min-width: 320px;
+    color: #777;
+    line-height: 1.6;
+}
+
+h1, h2, h3, h4, h5, h6 {
+    font-weight: bold;
+    color: rgb(75, 75, 75);
+}
+h3 {
+    font-size: 1.25em;
+}
+h4 {
+    font-size: 1.125em;
+}
+
+a {
+    color: #3b8bba; /* block-background-text-normal */
+    text-decoration: none;
+}
+
+a:visited {
+    color: #265778; /* block-normal-text-normal */
+}
+
+dt {
+    font-weight: bold;
+}
+dd {
+    margin: 0 0 10px 0;
+}
+
+aside {
+    background: #1f8dd6; /* same color as selected state on site menu */
+    padding: 0.3em 1em;
+    border-radius: 3px;
+    color: #fff;
+}
+
+aside a, aside a:visited {
+    color: rgb(169, 226, 255);
+}
+
+.fa {
+    float: right;
+    padding: 0.5em;
+}
+
+.home-menu {
+    background-color: #323b44 !important;
+    vertical-align: middle;
+}
+
+/* --------------------------
+ * Layout Styles
+ * --------------------------
+*/
+
+/* Navigation Push Styles */
+#layout {
+    position: relative;
+    padding-left: 0;
+    top: 20px;
+}
+    #layout.active {
+        position: relative;
+        left: 180px;
+    }
+        #layout.active #menu {
+            left: 180px;
+            width: 180px;
+        }
+
+#layout #main {
+    padding: 1em 1em 1em 1em;
+}
+/* Apply the .box class on the immediate parent of any grid element (pure-u-*) to apply some padding. */
+.l-box {
+    padding: 1em;
+}
+
+.l-wrap {
+    margin-left: auto;
+    margin-right: auto;
+}
+.content .l-wrap {
+    margin-left: -1em;
+    margin-right: -1em;
+}
+
+
+/* --------------------------
+ * Header Module Styles
+ * --------------------------
+*/
+
+.header {
+     font-family: "omnes-pro", sans-serif;
+     max-width: 768px;
+     margin: 0 auto;
+     padding: 1em;
+     text-align: center;
+     border-bottom: 1px solid #eee;
+ }
+    .header h1 {
+        font-size: 300%;
+        font-weight: 100;
+        margin: 0;
+    }
+     .header h2 {
+        font-size: 125%;
+        font-weight: 100;
+        line-height: 1.5;
+        margin: 0;
+        color: #666;
+    }
+
+
+ /* --------------------------
+  * Content Module Styles
+  * --------------------------
+ */
+
+/* The content div is placed as a wrapper around all the docs */
+.content {
+    margin-left: auto;
+    margin-right: auto;
+    padding-left: 1em;
+    padding-right: 1em;
+    max-width: 768px;
+}
+
+    .content .content-subhead {
+        margin: 2em 0 1em 0;
+        font-weight: 300;
+        color: #888;
+        position: relative;
+    }
+
+    .content .content-spaced {
+        line-height: 1.8;
+    }
+
+    .content .content-quote {
+        font-family: "Georgia", serif;
+        color: #666;
+        font-style: italic;
+        line-height: 1.8;
+        border-left: 5px solid #ddd;
+        padding-left: 1.5em;
+    }
+
+    .content-link {
+        position: absolute;
+        top: 0;
+        right: 0;
+        display: block;
+        height: 100%;
+        width: 20px;
+        background: transparent url('/img/link-icon.png') no-repeat center center;
+        background-size: 20px 20px;
+    }
+
+    @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx) {
+        .content-link {
+            background-image: url('/img/link-icon@2x.png');
+        }
+    }
+
+
+/* --------------------------
+ * Code Styles
+ * --------------------------
+*/
+
+pre,
+code {
+    font-family: Consolas, 'Liberation Mono', Courier, monospace;
+    color: #333;
+    background: rgb(250, 250, 250);
+}
+
+code {
+    padding: 0.2em 0.4em;
+    white-space: nowrap;
+}
+.content p code {
+    font-size: 90%;
+}
+
+.code {
+    margin-left: -1em;
+    margin-right: -1em;
+    padding: 1em;
+    border: 1px solid #eee;
+    border-left-width: 0;
+    border-right-width: 0;
+    overflow-x: auto;
+    -webkit-overflow-scrolling: touch;
+}
+.code code {
+    font-size: 95%;
+    white-space: pre;
+    word-wrap: normal;
+    padding: 0;
+    background: none;
+}
+.code-wrap code {
+    white-space: pre-wrap;
+    word-wrap: break-word;
+}
+
+/* --------------------------
+ * Footer Module Styles
+ * --------------------------
+*/
+
+.footer {
+    font-size: 87.5%;
+    border-top: 1px solid #eee;
+    margin-top: 3.4286em;
+    padding: 1.1429em;
+    background: rgb(250, 250, 250);
+}
+
+.legal {
+    line-height: 1.6;
+    text-align: center;
+    margin: 0 auto;
+}
+
+    .legal-license {
+        margin-top: 0;
+    }
+    .legal-links {
+        list-style: none;
+        padding: 0;
+        margin-bottom: 0;
+    }
+    .legal-copyright {
+        margin-top: 0;
+        margin-bottom: 0;
+    }
+
+
+/* --------------------------
+ * Main Navigation Bar Styles
+ * --------------------------
+*/
+
+/* Add transition to containers so they can push in and out */
+#layout,
+#menu,
+.menu-link {
+    -webkit-transition: all 0.2s ease-out;
+    -moz-transition: all 0.2s ease-out;
+    -ms-transition: all 0.2s ease-out;
+    -o-transition: all 0.2s ease-out;
+    transition: all 0.2s ease-out;
+}
+
+#layout.active .menu-link {
+    left: 180px;
+}
+
+#menu {
+    margin-left: -180px; /* "#menu" width */
+    width: 180px;
+    position: fixed;
+    top: 48px;
+    left: 0;
+    bottom: 0;
+    z-index: 1000; /* so the menu or its navicon stays above all content */
+    background: #191818;
+    overflow-y: auto;
+    -webkit-overflow-scrolling: touch;
+}
+    #menu a {
+        color: #999;
+        border: none;
+        white-space: normal;
+        padding: 0.625em 1em;
+    }
+
+    #menu .pure-menu-open {
+        background: transparent;
+        border: 0;
+    }
+
+    #menu .pure-menu ul {
+        border: none;
+        background: transparent;
+    }
+
+    #menu .pure-menu ul,
+    #menu .pure-menu .menu-item-divided {
+        border-top: 1px solid #333;
+    }
+
+        #menu .pure-menu li a:hover,
+        #menu .pure-menu li a:focus {
+            background: #333;
+        }
+
+    .menu-link {
+        position: fixed;
+        display: block; /* show this only on small screens */
+        top: 0;
+        left: 0; /* "#menu width" */
+        background: #000;
+        background: rgba(0,0,0,0.7);
+        font-size: 11px; /* change this value to increase/decrease button size */
+        z-index: 10;
+        width: 4em;
+        height: 4em;
+        padding: 1em;
+    }
+
+        .menu-link:hover,
+        .menu-link:focus {
+            background: #000;
+        }
+
+        .menu-link span {
+            position: relative;
+            display: block;
+            margin-top: 0.9em;
+        }
+
+        .menu-link span,
+        .menu-link span:before,
+        .menu-link span:after {
+            background-color: #fff;
+            width: 100%;
+            height: .2em;
+            -webkit-transition: all 0.4s;
+               -moz-transition: all 0.4s;
+                -ms-transition: all 0.4s;
+                 -o-transition: all 0.4s;
+                    transition: all 0.4s;
+        }
+
+            .menu-link span:before,
+            .menu-link span:after {
+                position: absolute;
+                top: -.55em;
+                content: " ";
+            }
+
+            .menu-link span:after {
+                top: .55em;
+            }
+
+        .menu-link.active span {
+            background: transparent;
+        }
+
+            .menu-link.active span:before {
+                -webkit-transform: rotate(45deg) translate(.5em, .4em);
+                   -moz-transform: rotate(45deg) translate(.5em, .4em);
+                    -ms-transform: rotate(45deg) translate(.5em, .4em);
+                     -o-transform: rotate(45deg) translate(.5em, .4em);
+                        transform: rotate(45deg) translate(.5em, .4em);
+            }
+
+            .menu-link.active span:after {
+                -webkit-transform: rotate(-45deg) translate(.4em, -.3em);
+                   -moz-transform: rotate(-45deg) translate(.4em, -.3em);
+                    -ms-transform: rotate(-45deg) translate(.4em, -.3em);
+                     -o-transform: rotate(-45deg) translate(.4em, -.3em);
+                        transform: rotate(-45deg) translate(.4em, -.3em);
+            }
+
+    #menu .pure-menu-heading {
+        font-size: 125%;
+        font-weight: 300;
+        letter-spacing: 0.1em;
+        color: #fff;
+        margin-top: 0;
+        padding: 0.5em 0.8em;
+    }
+    #menu .pure-menu-heading:hover,
+    #menu .pure-menu-heading:focus {
+        color: #999;
+    }
+
+    #menu .pure-menu-selected {
+        background: #1f8dd6;
+    }
+
+        #menu .pure-menu-selected a {
+            color: #fff;
+        }
+
+        #menu li.pure-menu-selected a:hover,
+        #menu li.pure-menu-selected a:focus {
+            background: none;
+        }
+
+
+
+/* ---------------------
+ * Smaller Module Styles
+ * ---------------------
+*/
+
+.pure-img-responsive {
+    max-width: 100%;
+    height: auto;
+}
+
+.pure-paginator .pure-button {
+    -webkit-box-sizing: content-box;
+    -moz-box-sizing: content-box;
+    box-sizing: content-box;
+}
+
+.pure-button {
+    font-family: inherit;
+}
+a.pure-button-primary {
+    color: white;
+}
+
+
+/* green call to action button class */
+.notice {
+    background-color: #61B842;
+    color: white;
+}
+
+.muted {
+    color: #ccc;
+}
+
+
+
+/* -------------
+ * Table Styles
+ * -------------
+*/
+
+.pure-table th,
+.pure-table td {
+    padding: 0.5em 1em;
+    font-size: 90%;
+}
+
+.table-responsive {
+    margin-left: -1em;
+    margin-right: -1em;
+    overflow-x: auto;
+    -webkit-overflow-scrolling: touch;
+    margin-bottom: 1em;
+}
+.table-responsive table {
+    width: 100%;
+    min-width: 35.5em;
+    border-left-width: 0;
+    border-right-width: 0;
+}
+
+.table-responsive .mq-table {
+    width: 100%;
+    min-width: 44em;
+}
+.mq-table th.highlight {
+    background-color: rgb(255, 234, 133);
+}
+.mq-table td.highlight {
+    background-color: rgb(255, 250, 229);
+}
+.mq-table th.highlight code,
+.mq-table td.highlight code {
+    background: rgb(255, 255, 243);
+}
+.mq-table-mq code {
+    font-size: 0.875em;
+}
+
+/* ----------------------------
+ * Example for full-width Grids
+ * ----------------------------
+*/
+
+.grids-example {
+    background: rgb(250, 250, 250);
+    margin: 2em auto;
+    border-top: 1px solid #ddd;
+    border-bottom: 1px solid #ddd;
+}
+
+/* --------------------------
+ * State Rules
+ * --------------------------
+*/
+
+
+.is-code-full {
+    text-align: center;
+}
+.is-code-full .code {
+    margin-left: auto;
+    margin-right: auto;
+}
+
+
+/* --------------------------
+ * Responsive Styles
+ * --------------------------
+*/
+
+@media screen and (min-width: 35.5em) {
+
+    .legal-license {
+        text-align: left;
+        margin: 0;
+    }
+    .legal-copyright,
+    .legal-links,
+    .legal-links li {
+        text-align: right;
+        margin: 0;
+    }
+
+}
+
+@media screen and (min-width: 48em) {
+
+    .l-wrap,
+    .l-wrap .content {
+        padding-left: 1em;
+        padding-right: 1em;
+    }
+    .content .l-wrap {
+        margin-left: -2em;
+        margin-right: -2em;
+    }
+
+    .header,
+    .content {
+        padding-left: 2em;
+        padding-right: 2em;
+    }
+
+    .header h1 {
+        font-size: 350%;
+    }
+    .header h2 {
+        font-size: 150%;
+    }
+
+    .content p {
+        font-size: 1.125em;
+    }
+
+    .code {
+        margin-left: auto;
+        margin-right: auto;
+        border-left-width: 1px;
+        border-right-width: 1px;
+    }
+
+    .table-responsive {
+        margin-left: auto;
+        margin-right: auto;
+    }
+    .table-responsive table {
+        border-left-width: 1px;
+        border-right-width: 1px;
+    }
+
+}
+
+@media (min-width: 58em) {
+
+    #layout {
+        padding-left: 180px; /* left col width "#menu" */
+        left: 0;
+    }
+    #menu {
+        left: 180px;
+    }
+    .menu-link {
+        position: fixed;
+        left: 180px;
+        display: none;
+    }
+    #layout.active .menu-link {
+        left: 180px;
+    }
+
+}
+
+.hero {
+    text-align: center;
+}
+    .hero-titles {
+        font-family: "omnes-pro", sans-serif;
+        padding: 0 1em;
+        margin: 2em auto;
+        max-width: 768px;
+    }
+    .hero-site {
+        font-size: 400%;
+        font-weight: 100;
+        margin: 0;
+        color: #1f8dd6;
+    }
+    .hero-tagline {
+        font-size: 150%;
+        font-weight: 100;
+        line-height: 1.5;
+        margin: 0 0 1em;
+        color: #666;
+    }
+
+a.button-cta,
+a.button-secondary {
+    margin: 0.25em;
+}
+
+a.button-cta {
+    background: #1f8dd6;
+    color: #fff;
+    border: 1px solid #1f8dd6;
+}
+
+a.button-secondary {
+    background: #fff;
+    color: #666;
+    border: 1px solid #ddd;
+}
+
+.size-chart {
+    width: 100%;
+    font-size: 87.5%;
+    line-height: 1.4;
+    margin-bottom: 2em;
+}
+
+    a.size-chart-item {
+        display: block;
+        color: #fff;
+        padding: 1.45em 0;
+        text-align: center;
+        text-decoration: none;
+        text-transform: capitalize;
+    }
+
+    .size-chart-label {
+        display: inline-block;
+        -webkit-transform: rotate(-90deg);
+        -moz-transform:    rotate(-90deg);
+        -ms-transform:     rotate(-90deg);
+        -o-transform:      rotate(-90deg);
+    }
+    .size-chart-size {
+        display: none;
+    }
+
+    .size-chart-base {
+        background: #0e90d2;
+    }
+        .size-chart-base .size-chart-size {
+            color: rgb(103, 194, 240);
+        }
+
+    .size-chart-grids {
+        background: rgb(128, 88, 165);
+    }
+        .size-chart-grids .size-chart-size {
+            color: rgb(200, 131, 255);
+        }
+
+    .size-chart-forms {
+        background: #5eb95e;
+    }
+
+        .size-chart-forms .size-chart-size {
+            color: rgb(161, 240, 137);
+        }
+
+    .size-chart-buttons {
+        background: #dd514c;
+    }
+
+        .size-chart-buttons .size-chart-size {
+            color: rgb(236, 164, 154);
+        }
+
+    .size-chart-menus {
+        background: rgb(250, 210, 50);
+    }
+        .size-chart-menus .size-chart-size {
+            color: rgb(255, 240, 134);
+        }
+
+    .size-chart-tables {
+        background: rgb(243, 123, 29);
+    }
+        .size-chart-tables .size-chart-label {
+            margin-left: -0.5em;
+        }
+        .size-chart-tables .size-chart-size {
+            color: rgb(255, 190, 129);
+        }
+
+.marketing {
+    border-bottom: 1px solid #eee;
+    margin-top: 1em;
+    margin-bottom: 1em;
+    padding-bottom: 2em;
+}
+.marketing-customize {
+    margin-bottom: 0;
+    border-bottom: 0;
+    padding-bottom: 0;
+}
+
+    .marketing .content {
+        margin-bottom: 0;
+    }
+
+    .marketing-header {
+        font-weight: 400;
+    }
+
+    .marketing-diagram {
+        margin: 2em auto;
+    }
+
+.sample-buttons {
+    margin: 1em auto;
+    padding: 0 0.5em;
+}
+
+    .sample-button {
+        padding: 0.5em;
+        text-align: center;
+    }
+    .sample-button .pure-button {
+        width: 100%;
+    }
+
+    .button-a {
+        background: #e1f2fa;
+        color: #5992aa;
+    }
+
+    .button-b {
+        background: #fcebbd;
+        color: #af9540;
+    }
+
+    .button-c,
+    .button-d,
+    .button-e {
+        border-radius: 8px;
+    }
+
+    .button-f,
+    .button-g,
+    .button-h {
+        border-radius: 20px;
+    }
+
+    .button-c {
+        background: #333;
+        color: #fff;
+    }
+    .button-d {
+        background: #d3eda3;
+        color: #72962e;
+    }
+
+    .button-e {
+        background: #f5ab9e;
+        color: #8c3a2b;
+    }
+    .button-f {
+        background: #ddaeff;
+        color: #8156a7;
+    }
+
+    .button-g {
+        background: #f57b00;
+        color: #ffca95;
+    }
+
+    .button-h {
+        background: #008ed4;
+        color: #fff;
+    }
+    .sample-button .button-h {
+        width: 50%; /* Updated to 80% at sm breakpoint */
+    }
+
+@media screen and (min-width: 30em) {
+    .size-chart-tables .size-chart-label {
+        margin-left: 0;
+    }
+}
+
+@media screen and (min-width: 35.5em) {
+    .hero {
+        margin-bottom: 3em;
+    }
+
+    .sample-button .button-h {
+        width: 100%;
+    }
+}
+
+@media screen and (min-width: 48em) {
+    .hero-titles {
+        padding: 0 2em;
+    }
+    .hero-site {
+        font-size: 800%;
+    }
+    .hero-tagline {
+        font-size: 250%;
+    }
+
+    a.button-cta,
+    a.button-secondary {
+        font-size: 125%;
+    }
+
+    .size-chart {
+        font-size: 100%;
+    }
+    a.size-chart-item {
+        padding: 0.5em;
+        text-align: left;
+    }
+    .size-chart-label {
+        -webkit-transform: none;
+        -moz-transform:    none;
+        -ms-transform:     none;
+        -o-transform:      none;
+    }
+    .size-chart-size {
+        display: block;
+    }
+
+    .marketing-header {
+        font-size: 150%;
+    }
+
+    .l-wrap .sample-buttons {
+        padding: 0 0.5em;
+    }
+}
+
+/**
+ * Baby Blue theme for RainbowJS
+ *
+ * @author tilomitra
+ */
+
+pre .comment {
+    color: #999;
+}
+
+pre .tag,
+pre .tag-name,
+pre .support.tag-name {
+    color: rgb(85, 85, 85);
+}
+
+pre .keyword,
+pre .css-property,
+pre .vendor-prefix,
+pre .sass,
+pre .class,
+pre .id,
+pre .css-value,
+pre .entity.function,
+pre .storage.function {
+    font-weight: bold;
+}
+
+pre .css-property,
+pre .css-value,
+pre .vendor-prefix,
+pre .support.namespace {
+    color: #333;
+}
+
+pre .constant.numeric,
+pre .keyword.unit,
+pre .hex-color {
+    font-weight: normal;
+    color: #099;
+}
+
+pre .attribute,
+pre .variable,
+pre .support {
+    color:  #757575; /* skinbuilder block-page-text-normal with #1f8dd6 as primary */
+}
+
+pre .string,
+pre .support.value  {
+    font-weight: normal;
+    color: #3b8bba; /* skinbuilder block-mine-text-low with #1f8dd6 as primary */
+}
+
+/* --------------------------
+ * Tabbed look in statistics
+ * --------------------------
+*/
+
+/* Set the size and font of the tab widget 
+.tabGroup {
+    font: 10pt arial, verdana;
+    width: 800px;
+    height: 400px;
+}
+/* Configure the radio buttons to hide off screen */
+.tabGroup > input[type="radio"] {
+    position: absolute;
+    left:-100px;
+    top:-100px;
+}
+/* Configure labels to look like tabs */
+.tabGroup > input[type="radio"] + label {
+    /* inline-block such that the label can be given dimensions */
+    display: inline-block;
+    border: 1px solid silver;
+     
+    /* the bottom border is handled by the tab content div */
+    border-bottom: 0;
+    /* Padding around tab text */
+    padding: 5px 10px;
+    /* Set the background color to default gray (non-selected tab) */
+    background-color:#ddd;
+}
+/* Focused tabs need to be highlighted as such */
+.tabGroup > input[type="radio"]:focus + label {
+    border:1px dashed silver;
+}
+/* Checked tabs must be white with the bottom border removed */
+.tabGroup > input[type="radio"]:checked + label {
+    background-color:white;
+    font-weight: bold;
+    border-bottom: 1px solid white;
+    margin-bottom: -1px;
+}
+/* The tab content must fill the widgets size and have a nice border */
+.tabGroup > div {
+    display: none;
+    background-color: white;
+    border: 1px solid silver;
+    padding: 10px 10px;
+    height: 100%;
+    overflow: auto;
+}
+/* This matchs tabs displaying to their associated radio inputs */
+.port-stats:checked ~ .port-stats, .flow-stats:checked ~ .flow-stats {
+    display: block;
+}
diff --git a/styles/pure-min-0.5.0.css b/styles/pure-min-0.5.0.css
new file mode 100644 (file)
index 0000000..14497d9
--- /dev/null
@@ -0,0 +1,11 @@
+/*!
+Pure v0.5.0
+Copyright 2014 Yahoo! Inc. All rights reserved.
+Licensed under the BSD License.
+https://github.com/yui/pure/blob/master/LICENSE.md
+*/
+/*!
+normalize.css v1.1.3 | MIT License | git.io/normalize
+Copyright (c) Nicolas Gallagher and Jonathan Neal
+*/
+/*! normalize.css v1.1.3 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-size:100%;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}html,button,input,select,textarea{font-family:sans-serif}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{font-size:2em;margin:.67em 0}h2{font-size:1.5em;margin:.83em 0}h3{font-size:1.17em;margin:1em 0}h4{font-size:1em;margin:1.33em 0}h5{font-size:.83em;margin:1.67em 0}h6{font-size:.67em;margin:2.33em 0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}blockquote{margin:1em 40px}dfn{font-style:italic}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}mark{background:#ff0;color:#000}p,pre{margin:1em 0}code,kbd,pre,samp{font-family:monospace,serif;_font-family:'courier new',monospace;font-size:1em}pre{white-space:pre;white-space:pre-wrap;word-wrap:break-word}q{quotes:none}q:before,q:after{content:'';content:none}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}dl,menu,ol,ul{margin:1em 0}dd{margin:0 0 0 40px}menu,ol,ul{padding:0 0 0 40px}nav ul,nav ol{list-style:none;list-style-image:none}img{border:0;-ms-interpolation-mode:bicubic}svg:not(:root){overflow:hidden}figure{margin:0}form{margin:0}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0;white-space:normal;*margin-left:-7px}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer;*overflow:visible}button[disabled],html input[disabled]{cursor:default}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0;*height:13px;*width:13px}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}[hidden]{display:none!important}.pure-img{max-width:100%;height:auto;display:block}.pure-g{letter-spacing:-.31em;*letter-spacing:normal;*word-spacing:-.43em;text-rendering:optimizespeed;font-family:FreeSans,Arimo,"Droid Sans",Helvetica,Arial,sans-serif;display:-webkit-flex;-webkit-flex-flow:row wrap;display:-ms-flexbox;-ms-flex-flow:row wrap}.opera-only :-o-prefocus,.pure-g{word-spacing:-.43em}.pure-u{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-g [class *="pure-u"]{font-family:sans-serif}.pure-u-1,.pure-u-1-1,.pure-u-1-2,.pure-u-1-3,.pure-u-2-3,.pure-u-1-4,.pure-u-3-4,.pure-u-1-5,.pure-u-2-5,.pure-u-3-5,.pure-u-4-5,.pure-u-5-5,.pure-u-1-6,.pure-u-5-6,.pure-u-1-8,.pure-u-3-8,.pure-u-5-8,.pure-u-7-8,.pure-u-1-12,.pure-u-5-12,.pure-u-7-12,.pure-u-11-12,.pure-u-1-24,.pure-u-2-24,.pure-u-3-24,.pure-u-4-24,.pure-u-5-24,.pure-u-6-24,.pure-u-7-24,.pure-u-8-24,.pure-u-9-24,.pure-u-10-24,.pure-u-11-24,.pure-u-12-24,.pure-u-13-24,.pure-u-14-24,.pure-u-15-24,.pure-u-16-24,.pure-u-17-24,.pure-u-18-24,.pure-u-19-24,.pure-u-20-24,.pure-u-21-24,.pure-u-22-24,.pure-u-23-24,.pure-u-24-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-u-1-24{width:4.1667%;*width:4.1357%}.pure-u-1-12,.pure-u-2-24{width:8.3333%;*width:8.3023%}.pure-u-1-8,.pure-u-3-24{width:12.5%;*width:12.469%}.pure-u-1-6,.pure-u-4-24{width:16.6667%;*width:16.6357%}.pure-u-1-5{width:20%;*width:19.969%}.pure-u-5-24{width:20.8333%;*width:20.8023%}.pure-u-1-4,.pure-u-6-24{width:25%;*width:24.969%}.pure-u-7-24{width:29.1667%;*width:29.1357%}.pure-u-1-3,.pure-u-8-24{width:33.3333%;*width:33.3023%}.pure-u-3-8,.pure-u-9-24{width:37.5%;*width:37.469%}.pure-u-2-5{width:40%;*width:39.969%}.pure-u-5-12,.pure-u-10-24{width:41.6667%;*width:41.6357%}.pure-u-11-24{width:45.8333%;*width:45.8023%}.pure-u-1-2,.pure-u-12-24{width:50%;*width:49.969%}.pure-u-13-24{width:54.1667%;*width:54.1357%}.pure-u-7-12,.pure-u-14-24{width:58.3333%;*width:58.3023%}.pure-u-3-5{width:60%;*width:59.969%}.pure-u-5-8,.pure-u-15-24{width:62.5%;*width:62.469%}.pure-u-2-3,.pure-u-16-24{width:66.6667%;*width:66.6357%}.pure-u-17-24{width:70.8333%;*width:70.8023%}.pure-u-3-4,.pure-u-18-24{width:75%;*width:74.969%}.pure-u-19-24{width:79.1667%;*width:79.1357%}.pure-u-4-5{width:80%;*width:79.969%}.pure-u-5-6,.pure-u-20-24{width:83.3333%;*width:83.3023%}.pure-u-7-8,.pure-u-21-24{width:87.5%;*width:87.469%}.pure-u-11-12,.pure-u-22-24{width:91.6667%;*width:91.6357%}.pure-u-23-24{width:95.8333%;*width:95.8023%}.pure-u-1,.pure-u-1-1,.pure-u-5-5,.pure-u-24-24{width:100%}.pure-button{display:inline-block;*display:inline;zoom:1;line-height:normal;white-space:nowrap;vertical-align:baseline;text-align:center;cursor:pointer;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.pure-button::-moz-focus-inner{padding:0;border:0}.pure-button{font-family:inherit;font-size:100%;*font-size:90%;*overflow:visible;padding:.5em 1em;color:#444;color:rgba(0,0,0,.8);*color:#444;border:1px solid #999;border:0 rgba(0,0,0,0);background-color:#E6E6E6;text-decoration:none;border-radius:2px}.pure-button-hover,.pure-button:hover,.pure-button:focus{filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#1a000000', GradientType=0);background-image:-webkit-gradient(linear,0 0,0 100%,from(transparent),color-stop(40%,rgba(0,0,0,.05)),to(rgba(0,0,0,.1)));background-image:-webkit-linear-gradient(transparent,rgba(0,0,0,.05) 40%,rgba(0,0,0,.1));background-image:-moz-linear-gradient(top,rgba(0,0,0,.05) 0,rgba(0,0,0,.1));background-image:-o-linear-gradient(transparent,rgba(0,0,0,.05) 40%,rgba(0,0,0,.1));background-image:linear-gradient(transparent,rgba(0,0,0,.05) 40%,rgba(0,0,0,.1))}.pure-button:focus{outline:0}.pure-button-active,.pure-button:active{box-shadow:0 0 0 1px rgba(0,0,0,.15) inset,0 0 6px rgba(0,0,0,.2) inset}.pure-button[disabled],.pure-button-disabled,.pure-button-disabled:hover,.pure-button-disabled:focus,.pure-button-disabled:active{border:0;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);filter:alpha(opacity=40);-khtml-opacity:.4;-moz-opacity:.4;opacity:.4;cursor:not-allowed;box-shadow:none}.pure-button-hidden{display:none}.pure-button::-moz-focus-inner{padding:0;border:0}.pure-button-primary,.pure-button-selected,a.pure-button-primary,a.pure-button-selected{background-color:#0078e7;color:#fff}.pure-form input[type=text],.pure-form input[type=password],.pure-form input[type=email],.pure-form input[type=url],.pure-form input[type=date],.pure-form input[type=month],.pure-form input[type=time],.pure-form input[type=datetime],.pure-form input[type=datetime-local],.pure-form input[type=week],.pure-form input[type=number],.pure-form input[type=search],.pure-form input[type=tel],.pure-form input[type=color],.pure-form select,.pure-form textarea{padding:.5em .6em;display:inline-block;border:1px solid #ccc;box-shadow:inset 0 1px 3px #ddd;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.pure-form input:not([type]){padding:.5em .6em;display:inline-block;border:1px solid #ccc;box-shadow:inset 0 1px 3px #ddd;border-radius:4px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.pure-form input[type=color]{padding:.2em .5em}.pure-form input[type=text]:focus,.pure-form input[type=password]:focus,.pure-form input[type=email]:focus,.pure-form input[type=url]:focus,.pure-form input[type=date]:focus,.pure-form input[type=month]:focus,.pure-form input[type=time]:focus,.pure-form input[type=datetime]:focus,.pure-form input[type=datetime-local]:focus,.pure-form input[type=week]:focus,.pure-form input[type=number]:focus,.pure-form input[type=search]:focus,.pure-form input[type=tel]:focus,.pure-form input[type=color]:focus,.pure-form select:focus,.pure-form textarea:focus{outline:0;outline:thin dotted \9;border-color:#129FEA}.pure-form input:not([type]):focus{outline:0;outline:thin dotted \9;border-color:#129FEA}.pure-form input[type=file]:focus,.pure-form input[type=radio]:focus,.pure-form input[type=checkbox]:focus{outline:thin dotted #333;outline:1px auto #129FEA}.pure-form .pure-checkbox,.pure-form .pure-radio{margin:.5em 0;display:block}.pure-form input[type=text][disabled],.pure-form input[type=password][disabled],.pure-form input[type=email][disabled],.pure-form input[type=url][disabled],.pure-form input[type=date][disabled],.pure-form input[type=month][disabled],.pure-form input[type=time][disabled],.pure-form input[type=datetime][disabled],.pure-form input[type=datetime-local][disabled],.pure-form input[type=week][disabled],.pure-form input[type=number][disabled],.pure-form input[type=search][disabled],.pure-form input[type=tel][disabled],.pure-form input[type=color][disabled],.pure-form select[disabled],.pure-form textarea[disabled]{cursor:not-allowed;background-color:#eaeded;color:#cad2d3}.pure-form input:not([type])[disabled]{cursor:not-allowed;background-color:#eaeded;color:#cad2d3}.pure-form input[readonly],.pure-form select[readonly],.pure-form textarea[readonly]{background:#eee;color:#777;border-color:#ccc}.pure-form input:focus:invalid,.pure-form textarea:focus:invalid,.pure-form select:focus:invalid{color:#b94a48;border-color:#ee5f5b}.pure-form input:focus:invalid:focus,.pure-form textarea:focus:invalid:focus,.pure-form select:focus:invalid:focus{border-color:#e9322d}.pure-form input[type=file]:focus:invalid:focus,.pure-form input[type=radio]:focus:invalid:focus,.pure-form input[type=checkbox]:focus:invalid:focus{outline-color:#e9322d}.pure-form select{border:1px solid #ccc;background-color:#fff}.pure-form select[multiple]{height:auto}.pure-form label{margin:.5em 0 .2em}.pure-form fieldset{margin:0;padding:.35em 0 .75em;border:0}.pure-form legend{display:block;width:100%;padding:.3em 0;margin-bottom:.3em;color:#333;border-bottom:1px solid #e5e5e5}.pure-form-stacked input[type=text],.pure-form-stacked input[type=password],.pure-form-stacked input[type=email],.pure-form-stacked input[type=url],.pure-form-stacked input[type=date],.pure-form-stacked input[type=month],.pure-form-stacked input[type=time],.pure-form-stacked input[type=datetime],.pure-form-stacked input[type=datetime-local],.pure-form-stacked input[type=week],.pure-form-stacked input[type=number],.pure-form-stacked input[type=search],.pure-form-stacked input[type=tel],.pure-form-stacked input[type=color],.pure-form-stacked select,.pure-form-stacked label,.pure-form-stacked textarea{display:block;margin:.25em 0}.pure-form-stacked input:not([type]){display:block;margin:.25em 0}.pure-form-aligned input,.pure-form-aligned textarea,.pure-form-aligned select,.pure-form-aligned .pure-help-inline,.pure-form-message-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.pure-form-aligned textarea{vertical-align:top}.pure-form-aligned .pure-control-group{margin-bottom:.5em}.pure-form-aligned .pure-control-group label{text-align:right;display:inline-block;vertical-align:middle;width:10em;margin:0 1em 0 0}.pure-form-aligned .pure-controls{margin:1.5em 0 0 10em}.pure-form input.pure-input-rounded,.pure-form .pure-input-rounded{border-radius:2em;padding:.5em 1em}.pure-form .pure-group fieldset{margin-bottom:10px}.pure-form .pure-group input{display:block;padding:10px;margin:0;border-radius:0;position:relative;top:-1px}.pure-form .pure-group input:focus{z-index:2}.pure-form .pure-group input:first-child{top:1px;border-radius:4px 4px 0 0}.pure-form .pure-group input:last-child{top:-2px;border-radius:0 0 4px 4px}.pure-form .pure-group button{margin:.35em 0}.pure-form .pure-input-1{width:100%}.pure-form .pure-input-2-3{width:66%}.pure-form .pure-input-1-2{width:50%}.pure-form .pure-input-1-3{width:33%}.pure-form .pure-input-1-4{width:25%}.pure-form .pure-help-inline,.pure-form-message-inline{display:inline-block;padding-left:.3em;color:#666;vertical-align:middle;font-size:.875em}.pure-form-message{display:block;color:#666;font-size:.875em}@media only screen and (max-width :480px){.pure-form button[type=submit]{margin:.7em 0 0}.pure-form input:not([type]),.pure-form input[type=text],.pure-form input[type=password],.pure-form input[type=email],.pure-form input[type=url],.pure-form input[type=date],.pure-form input[type=month],.pure-form input[type=time],.pure-form input[type=datetime],.pure-form input[type=datetime-local],.pure-form input[type=week],.pure-form input[type=number],.pure-form input[type=search],.pure-form input[type=tel],.pure-form input[type=color],.pure-form label{margin-bottom:.3em;display:block}.pure-group input:not([type]),.pure-group input[type=text],.pure-group input[type=password],.pure-group input[type=email],.pure-group input[type=url],.pure-group input[type=date],.pure-group input[type=month],.pure-group input[type=time],.pure-group input[type=datetime],.pure-group input[type=datetime-local],.pure-group input[type=week],.pure-group input[type=number],.pure-group input[type=search],.pure-group input[type=tel],.pure-group input[type=color]{margin-bottom:0}.pure-form-aligned .pure-control-group label{margin-bottom:.3em;text-align:left;display:block;width:100%}.pure-form-aligned .pure-controls{margin:1.5em 0 0}.pure-form .pure-help-inline,.pure-form-message-inline,.pure-form-message{display:block;font-size:.75em;padding:.2em 0 .8em}}.pure-menu ul{position:absolute;visibility:hidden}.pure-menu.pure-menu-open{visibility:visible;z-index:2;width:100%}.pure-menu ul{left:-10000px;list-style:none;margin:0;padding:0;top:-10000px;z-index:1}.pure-menu>ul{position:relative}.pure-menu-open>ul{left:0;top:0;visibility:visible}.pure-menu-open>ul:focus{outline:0}.pure-menu li{position:relative}.pure-menu a,.pure-menu .pure-menu-heading{display:block;color:inherit;line-height:1.5em;padding:5px 20px;text-decoration:none;white-space:nowrap}.pure-menu.pure-menu-horizontal>.pure-menu-heading{display:inline-block;*display:inline;zoom:1;margin:0;vertical-align:middle}.pure-menu.pure-menu-horizontal>ul{display:inline-block;*display:inline;zoom:1;vertical-align:middle}.pure-menu li a{padding:5px 20px}.pure-menu-can-have-children>.pure-menu-label:after{content:'\25B8';float:right;font-family:'Lucida Grande','Lucida Sans Unicode','DejaVu Sans',sans-serif;margin-right:-20px;margin-top:-1px}.pure-menu-can-have-children>.pure-menu-label{padding-right:30px}.pure-menu-separator{background-color:#dfdfdf;display:block;height:1px;font-size:0;margin:7px 2px;overflow:hidden}.pure-menu-hidden{display:none}.pure-menu-fixed{position:fixed;top:0;left:0;width:100%}.pure-menu-horizontal li{display:inline-block;*display:inline;zoom:1;vertical-align:middle}.pure-menu-horizontal li li{display:block}.pure-menu-horizontal>.pure-menu-children>.pure-menu-can-have-children>.pure-menu-label:after{content:"\25BE"}.pure-menu-horizontal>.pure-menu-children>.pure-menu-can-have-children>.pure-menu-label{padding-right:30px}.pure-menu-horizontal li.pure-menu-separator{height:50%;width:1px;margin:0 7px}.pure-menu-horizontal li li.pure-menu-separator{height:1px;width:auto;margin:7px 2px}.pure-menu.pure-menu-open,.pure-menu.pure-menu-horizontal li .pure-menu-children{background:#fff;border:1px solid #b7b7b7}.pure-menu.pure-menu-horizontal,.pure-menu.pure-menu-horizontal .pure-menu-heading{border:0}.pure-menu a{border:1px solid transparent;border-left:0;border-right:0}.pure-menu a,.pure-menu .pure-menu-can-have-children>li:after{color:#777}.pure-menu .pure-menu-can-have-children>li:hover:after{color:#fff}.pure-menu .pure-menu-open{background:#dedede}.pure-menu li a:hover,.pure-menu li a:focus{background:#eee}.pure-menu li.pure-menu-disabled a:hover,.pure-menu li.pure-menu-disabled a:focus{background:#fff;color:#bfbfbf}.pure-menu .pure-menu-disabled>a{background-image:none;border-color:transparent;cursor:default}.pure-menu .pure-menu-disabled>a,.pure-menu .pure-menu-can-have-children.pure-menu-disabled>a:after{color:#bfbfbf}.pure-menu .pure-menu-heading{color:#565d64;text-transform:uppercase;font-size:90%;margin-top:.5em;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:#dfdfdf}.pure-menu .pure-menu-selected a{color:#000}.pure-menu.pure-menu-open.pure-menu-fixed{border:0;border-bottom:1px solid #b7b7b7}.pure-paginator{letter-spacing:-.31em;*letter-spacing:normal;*word-spacing:-.43em;text-rendering:optimizespeed;list-style:none;margin:0;padding:0}.opera-only :-o-prefocus,.pure-paginator{word-spacing:-.43em}.pure-paginator li{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-paginator .pure-button{border-radius:0;padding:.8em 1.4em;vertical-align:top;height:1.1em}.pure-paginator .pure-button:focus,.pure-paginator .pure-button:active{outline-style:none}.pure-paginator .prev,.pure-paginator .next{color:#C0C1C3;text-shadow:0 -1px 0 rgba(0,0,0,.45)}.pure-paginator .prev{border-radius:2px 0 0 2px}.pure-paginator .next{border-radius:0 2px 2px 0}@media (max-width:480px){.pure-menu-horizontal{width:100%}.pure-menu-children li{display:block;border-bottom:1px solid #000}}.pure-table{border-collapse:collapse;border-spacing:0;empty-cells:show;border:1px solid #cbcbcb}.pure-table caption{color:#000;font:italic 85%/1 arial,sans-serif;padding:1em 0;text-align:center}.pure-table td,.pure-table th{border-left:1px solid #cbcbcb;border-width:0 0 0 1px;font-size:inherit;margin:0;overflow:visible;padding:.5em 1em}.pure-table td:first-child,.pure-table th:first-child{border-left-width:0}.pure-table thead{background:#e0e0e0;color:#000;text-align:left;vertical-align:bottom}.pure-table td{background-color:transparent}.pure-table-odd td{background-color:#f2f2f2}.pure-table-striped tr:nth-child(2n-1) td{background-color:#f2f2f2}.pure-table-bordered td{border-bottom:1px solid #cbcbcb}.pure-table-bordered tbody>tr:last-child td,.pure-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.pure-table-horizontal td,.pure-table-horizontal th{border-width:0 0 1px;border-bottom:1px solid #cbcbcb}.pure-table-horizontal tbody>tr:last-child td{border-bottom-width:0}
\ No newline at end of file