--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/FileSaver.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,244 @@
+/* FileSaver.js
+ * A saveAs() FileSaver implementation.
+ * 2014-12-17
+ *
+ * By Eli Grey, http://eligrey.com
+ * License: X11/MIT
+ * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
+ */
+
+/*global self */
+/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
+
+/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
+
+var saveAs = saveAs
+ // IE 10+ (native saveAs)
+ || (typeof navigator !== "undefined" &&
+ navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
+ // Everyone else
+ || (function(view) {
+ "use strict";
+ // IE <10 is explicitly unsupported
+ if (typeof navigator !== "undefined" &&
+ /MSIE [1-9]\./.test(navigator.userAgent)) {
+ return;
+ }
+ var
+ doc = view.document
+ // only get URL when necessary in case Blob.js hasn't overridden it yet
+ , get_URL = function() {
+ return view.URL || view.webkitURL || view;
+ }
+ , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
+ , can_use_save_link = "download" in save_link
+ , click = function(node) {
+ var event = doc.createEvent("MouseEvents");
+ event.initMouseEvent(
+ "click", true, false, view, 0, 0, 0, 0, 0
+ , false, false, false, false, 0, null
+ );
+ node.dispatchEvent(event);
+ }
+ , webkit_req_fs = view.webkitRequestFileSystem
+ , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
+ , throw_outside = function(ex) {
+ (view.setImmediate || view.setTimeout)(function() {
+ throw ex;
+ }, 0);
+ }
+ , force_saveable_type = "application/octet-stream"
+ , fs_min_size = 0
+ // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
+ // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
+ // for the reasoning behind the timeout and revocation flow
+ , arbitrary_revoke_timeout = 500 // in ms
+ , revoke = function(file) {
+ var revoker = function() {
+ if (typeof file === "string") { // file is an object URL
+ get_URL().revokeObjectURL(file);
+ } else { // file is a File
+ file.remove();
+ }
+ };
+ if (view.chrome) {
+ revoker();
+ } else {
+ setTimeout(revoker, arbitrary_revoke_timeout);
+ }
+ }
+ , dispatch = function(filesaver, event_types, event) {
+ event_types = [].concat(event_types);
+ var i = event_types.length;
+ while (i--) {
+ var listener = filesaver["on" + event_types[i]];
+ if (typeof listener === "function") {
+ try {
+ listener.call(filesaver, event || filesaver);
+ } catch (ex) {
+ throw_outside(ex);
+ }
+ }
+ }
+ }
+ , FileSaver = function(blob, name) {
+ // First try a.download, then web filesystem, then object URLs
+ var
+ filesaver = this
+ , type = blob.type
+ , blob_changed = false
+ , object_url
+ , target_view
+ , dispatch_all = function() {
+ dispatch(filesaver, "writestart progress write writeend".split(" "));
+ }
+ // on any filesys errors revert to saving with object URLs
+ , fs_error = function() {
+ // don't create more object URLs than needed
+ if (blob_changed || !object_url) {
+ object_url = get_URL().createObjectURL(blob);
+ }
+ if (target_view) {
+ target_view.location.href = object_url;
+ } else {
+ var new_tab = view.open(object_url, "_blank");
+ if (new_tab == undefined && typeof safari !== "undefined") {
+ //Apple do not allow window.open, see http://bit.ly/1kZffRI
+ view.location.href = object_url
+ }
+ }
+ filesaver.readyState = filesaver.DONE;
+ dispatch_all();
+ revoke(object_url);
+ }
+ , abortable = function(func) {
+ return function() {
+ if (filesaver.readyState !== filesaver.DONE) {
+ return func.apply(this, arguments);
+ }
+ };
+ }
+ , create_if_not_found = {create: true, exclusive: false}
+ , slice
+ ;
+ filesaver.readyState = filesaver.INIT;
+ if (!name) {
+ name = "download";
+ }
+ if (can_use_save_link) {
+ object_url = get_URL().createObjectURL(blob);
+ save_link.href = object_url;
+ save_link.download = name;
+ click(save_link);
+ filesaver.readyState = filesaver.DONE;
+ dispatch_all();
+ revoke(object_url);
+ return;
+ }
+ // Object and web filesystem URLs have a problem saving in Google Chrome when
+ // viewed in a tab, so I force save with application/octet-stream
+ // http://code.google.com/p/chromium/issues/detail?id=91158
+ // Update: Google errantly closed 91158, I submitted it again:
+ // https://code.google.com/p/chromium/issues/detail?id=389642
+ if (view.chrome && type && type !== force_saveable_type) {
+ slice = blob.slice || blob.webkitSlice;
+ blob = slice.call(blob, 0, blob.size, force_saveable_type);
+ blob_changed = true;
+ }
+ // Since I can't be sure that the guessed media type will trigger a download
+ // in WebKit, I append .download to the filename.
+ // https://bugs.webkit.org/show_bug.cgi?id=65440
+ if (webkit_req_fs && name !== "download") {
+ name += ".download";
+ }
+ if (type === force_saveable_type || webkit_req_fs) {
+ target_view = view;
+ }
+ if (!req_fs) {
+ fs_error();
+ return;
+ }
+ fs_min_size += blob.size;
+ req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
+ fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
+ var save = function() {
+ dir.getFile(name, create_if_not_found, abortable(function(file) {
+ file.createWriter(abortable(function(writer) {
+ writer.onwriteend = function(event) {
+ target_view.location.href = file.toURL();
+ filesaver.readyState = filesaver.DONE;
+ dispatch(filesaver, "writeend", event);
+ revoke(file);
+ };
+ writer.onerror = function() {
+ var error = writer.error;
+ if (error.code !== error.ABORT_ERR) {
+ fs_error();
+ }
+ };
+ "writestart progress write abort".split(" ").forEach(function(event) {
+ writer["on" + event] = filesaver["on" + event];
+ });
+ writer.write(blob);
+ filesaver.abort = function() {
+ writer.abort();
+ filesaver.readyState = filesaver.DONE;
+ };
+ filesaver.readyState = filesaver.WRITING;
+ }), fs_error);
+ }), fs_error);
+ };
+ dir.getFile(name, {create: false}, abortable(function(file) {
+ // delete file if it already exists
+ file.remove();
+ save();
+ }), abortable(function(ex) {
+ if (ex.code === ex.NOT_FOUND_ERR) {
+ save();
+ } else {
+ fs_error();
+ }
+ }));
+ }), fs_error);
+ }), fs_error);
+ }
+ , FS_proto = FileSaver.prototype
+ , saveAs = function(blob, name) {
+ return new FileSaver(blob, name);
+ }
+ ;
+ FS_proto.abort = function() {
+ var filesaver = this;
+ filesaver.readyState = filesaver.DONE;
+ dispatch(filesaver, "abort");
+ };
+ FS_proto.readyState = FS_proto.INIT = 0;
+ FS_proto.WRITING = 1;
+ FS_proto.DONE = 2;
+
+ FS_proto.error =
+ FS_proto.onwritestart =
+ FS_proto.onprogress =
+ FS_proto.onwrite =
+ FS_proto.onabort =
+ FS_proto.onerror =
+ FS_proto.onwriteend =
+ null;
+
+ return saveAs;
+}(
+ typeof self !== "undefined" && self
+ || typeof window !== "undefined" && window
+ || this.content
+));
+// `self` is undefined in Firefox for Android content script context
+// while `this` is nsIContentFrameMessageManager
+// with an attribute `content` that corresponds to the window
+
+if (typeof module !== "undefined" && module.exports) {
+ module.exports = saveAs;
+} else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
+ define([], function() {
+ return saveAs;
+ });
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/FileSaver.min.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,2 @@
+/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
+var saveAs=saveAs||typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob&&navigator.msSaveOrOpenBlob.bind(navigator)||function(view){"use strict";if(typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var doc=view.document,get_URL=function(){return view.URL||view.webkitURL||view},save_link=doc.createElementNS("http://www.w3.org/1999/xhtml","a"),can_use_save_link="download"in save_link,click=function(node){var event=doc.createEvent("MouseEvents");event.initMouseEvent("click",true,false,view,0,0,0,0,0,false,false,false,false,0,null);node.dispatchEvent(event)},webkit_req_fs=view.webkitRequestFileSystem,req_fs=view.requestFileSystem||webkit_req_fs||view.mozRequestFileSystem,throw_outside=function(ex){(view.setImmediate||view.setTimeout)(function(){throw ex},0)},force_saveable_type="application/octet-stream",fs_min_size=0,arbitrary_revoke_timeout=500,revoke=function(file){var revoker=function(){if(typeof file==="string"){get_URL().revokeObjectURL(file)}else{file.remove()}};if(view.chrome){revoker()}else{setTimeout(revoker,arbitrary_revoke_timeout)}},dispatch=function(filesaver,event_types,event){event_types=[].concat(event_types);var i=event_types.length;while(i--){var listener=filesaver["on"+event_types[i]];if(typeof listener==="function"){try{listener.call(filesaver,event||filesaver)}catch(ex){throw_outside(ex)}}}},FileSaver=function(blob,name){var filesaver=this,type=blob.type,blob_changed=false,object_url,target_view,dispatch_all=function(){dispatch(filesaver,"writestart progress write writeend".split(" "))},fs_error=function(){if(blob_changed||!object_url){object_url=get_URL().createObjectURL(blob)}if(target_view){target_view.location.href=object_url}else{var new_tab=view.open(object_url,"_blank");if(new_tab==undefined&&typeof safari!=="undefined"){view.location.href=object_url}}filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url)},abortable=function(func){return function(){if(filesaver.readyState!==filesaver.DONE){return func.apply(this,arguments)}}},create_if_not_found={create:true,exclusive:false},slice;filesaver.readyState=filesaver.INIT;if(!name){name="download"}if(can_use_save_link){object_url=get_URL().createObjectURL(blob);save_link.href=object_url;save_link.download=name;click(save_link);filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url);return}if(view.chrome&&type&&type!==force_saveable_type){slice=blob.slice||blob.webkitSlice;blob=slice.call(blob,0,blob.size,force_saveable_type);blob_changed=true}if(webkit_req_fs&&name!=="download"){name+=".download"}if(type===force_saveable_type||webkit_req_fs){target_view=view}if(!req_fs){fs_error();return}fs_min_size+=blob.size;req_fs(view.TEMPORARY,fs_min_size,abortable(function(fs){fs.root.getDirectory("saved",create_if_not_found,abortable(function(dir){var save=function(){dir.getFile(name,create_if_not_found,abortable(function(file){file.createWriter(abortable(function(writer){writer.onwriteend=function(event){target_view.location.href=file.toURL();filesaver.readyState=filesaver.DONE;dispatch(filesaver,"writeend",event);revoke(file)};writer.onerror=function(){var error=writer.error;if(error.code!==error.ABORT_ERR){fs_error()}};"writestart progress write abort".split(" ").forEach(function(event){writer["on"+event]=filesaver["on"+event]});writer.write(blob);filesaver.abort=function(){writer.abort();filesaver.readyState=filesaver.DONE};filesaver.readyState=filesaver.WRITING}),fs_error)}),fs_error)};dir.getFile(name,{create:false},abortable(function(file){file.remove();save()}),abortable(function(ex){if(ex.code===ex.NOT_FOUND_ERR){save()}else{fs_error()}}))}),fs_error)}),fs_error)},FS_proto=FileSaver.prototype,saveAs=function(blob,name){return new FileSaver(blob,name)};FS_proto.abort=function(){var filesaver=this;filesaver.readyState=filesaver.DONE;dispatch(filesaver,"abort")};FS_proto.readyState=FS_proto.INIT=0;FS_proto.WRITING=1;FS_proto.DONE=2;FS_proto.error=FS_proto.onwritestart=FS_proto.onprogress=FS_proto.onwrite=FS_proto.onabort=FS_proto.onerror=FS_proto.onwriteend=null;return saveAs}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!=null){define([],function(){return saveAs})}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/LICENSE.md Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,9 @@
+Copyright © 2014 [Eli Grey][1].
+
+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.
+
+ [1]: http://eligrey.com
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/README.md Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,102 @@
+FileSaver.js
+============
+
+FileSaver.js implements the HTML5 W3C `saveAs()` FileSaver interface in browsers that do
+not natively support it. There is a [FileSaver.js demo][1] that demonstrates saving
+various media types.
+
+FileSaver.js is the solution to saving files on the client-side, and is perfect for
+webapps that need to generate files, or for saving sensitive information that shouldn't be
+sent to an external server.
+
+Looking for `canvas.toBlob()` for saving canvases? Check out
+[canvas-toBlob.js](https://github.com/eligrey/canvas-toBlob.js) for a cross-browser implementation.
+
+Supported browsers
+------------------
+
+| Browser | Constructs as | Filenames | Max Blob Size | Dependencies |
+| -------------- | ------------- | ------------ | ------------- | ------------ |
+| Firefox 20+ | Blob | Yes | 800 MiB | None |
+| Firefox < 20 | data: URI | No | n/a | [Blob.js](https://github.com/eligrey/Blob.js) |
+| Chrome | Blob | Yes | 345 MiB | None |
+| Chrome for Android | Blob | Yes | 345 MiB | None |
+| IE 10+ | Blob | Yes | 600 MiB | None |
+| Opera 15+ | Blob | Yes | 345 MiB | None |
+| Opera < 15 | data: URI | No | n/a | [Blob.js](https://github.com/eligrey/Blob.js) |
+| Safari 6.1+* | Blob | No | ? | None |
+| Safari < 6 | data: URI | No | n/a | [Blob.js](https://github.com/eligrey/Blob.js) |
+
+Feature detection is possible:
+
+```js
+try {
+ var isFileSaverSupported = !!new Blob;
+} catch (e) {}
+```
+
+### IE < 10
+
+It is possible to save text files in IE < 10 without Flash-based polyfills.
+See [ChenWenBrian and koffsyrup's `saveTextAs()`](https://github.com/koffsyrup/FileSaver.js#examples) for more details.
+
+### Safari 6.1+
+
+Blobs may be opened instead of saved sometimes—you may have to direct your Safari users to manually
+press <kbd>⌘</kbd>+<kbd>S</kbd> to save the file after it is opened. Using the `application/octet-stream` MIME type to force downloads [can cause issues in Safari](https://github.com/eligrey/FileSaver.js/issues/12#issuecomment-47247096).
+
+### iOS
+
+saveAs must be run within a user interaction event such as onTouchDown or onClick; setTimeout will prevent saveAs from triggering. Due to restrictions in iOS saveAs opens in a new window instead of downloading, if you want this fixed please [tell Apple](https://bugs.webkit.org/show_bug.cgi?id=102914) how this bug is affecting you.
+
+Syntax
+------
+
+```js
+FileSaver saveAs(in Blob data, in DOMString filename)
+```
+
+Examples
+--------
+
+### Saving text
+
+```js
+var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
+saveAs(blob, "hello world.txt");
+```
+
+The standard W3C File API [`Blob`][3] interface is not available in all browsers.
+[Blob.js][4] is a cross-browser `Blob` implementation that solves this.
+
+### Saving a canvas
+
+```js
+var canvas = document.getElementById("my-canvas"), ctx = canvas.getContext("2d");
+// draw to canvas...
+canvas.toBlob(function(blob) {
+ saveAs(blob, "pretty image.png");
+});
+```
+
+Note: The standard HTML5 `canvas.toBlob()` method is not available in all browsers.
+[canvas-toBlob.js][5] is a cross-browser `canvas.toBlob()` that polyfills this.
+
+
+
+
+ [1]: http://eligrey.com/demos/FileSaver.js/
+ [3]: https://developer.mozilla.org/en-US/docs/DOM/Blob
+ [4]: https://github.com/eligrey/Blob.js
+ [5]: https://github.com/eligrey/canvas-toBlob.js
+
+Contributing
+------------
+
+The `FileSaver.js` distribution file is compiled with Uglify.js like so:
+
+```bash
+uglifyjs FileSaver.js --comments /@source/ > FileSaver.min.js
+```
+
+Please make sure you build a production version before submitting a pull request.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/demo/demo.css Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,50 @@
+html {
+ background-color: #DDD;
+}
+body {
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ width: 900px;
+ margin: 0 auto;
+ font-family: Verdana, Helvetica, Arial, sans-serif;
+ -webkit-box-shadow: 0 0 10px 2px rgba(0, 0, 0, .5);
+ -moz-box-shadow: 0 0 10px 2px rgba(0, 0, 0, .5);
+ box-shadow: 0 0 10px 2px rgba(0, 0, 0, .5);
+ padding: 7px 25px 70px;
+ background-color: #FFF;
+}
+h1, h2, h3, h4, h5, h6 {
+ font-family: Georgia, "Times New Roman", serif;
+}
+h2, form {
+ text-align: center;
+}
+form {
+ margin-top: 5px;
+}
+.input {
+ width: 500px;
+ height: 300px;
+ margin: 0 auto;
+ display: block;
+}
+section {
+ margin-top: 40px;
+}
+#canvas {
+ cursor: crosshair;
+}
+#canvas, #html {
+ border: 1px solid #000;
+}
+.filename {
+ text-align: right;
+}
+#html {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ overflow: auto;
+ padding: 1em;
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/demo/demo.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,216 @@
+/*! FileSaver.js demo script
+ * 2012-01-23
+ *
+ * By Eli Grey, http://eligrey.com
+ * License: X11/MIT
+ * See LICENSE.md
+ */
+
+/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
+
+/*jshint laxbreak: true, laxcomma: true, smarttabs: true*/
+/*global saveAs, self*/
+
+(function(view) {
+"use strict";
+// The canvas drawing portion of the demo is based off the demo at
+// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
+var
+ document = view.document
+ , $ = function(id) {
+ return document.getElementById(id);
+ }
+ , session = view.sessionStorage
+ // only get URL when necessary in case Blob.js hasn't defined it yet
+ , get_blob = function() {
+ return view.Blob;
+ }
+
+ , canvas = $("canvas")
+ , canvas_options_form = $("canvas-options")
+ , canvas_filename = $("canvas-filename")
+ , canvas_clear_button = $("canvas-clear")
+
+ , text = $("text")
+ , text_options_form = $("text-options")
+ , text_filename = $("text-filename")
+
+ , html = $("html")
+ , html_options_form = $("html-options")
+ , html_filename = $("html-filename")
+
+ , ctx = canvas.getContext("2d")
+ , drawing = false
+ , x_points = session.x_points || []
+ , y_points = session.y_points || []
+ , drag_points = session.drag_points || []
+ , add_point = function(x, y, dragging) {
+ x_points.push(x);
+ y_points.push(y);
+ drag_points.push(dragging);
+ }
+ , draw = function(){
+ canvas.width = canvas.width;
+ ctx.lineWidth = 6;
+ ctx.lineJoin = "round";
+ ctx.strokeStyle = "#000000";
+ var
+ i = 0
+ , len = x_points.length
+ ;
+ for(; i < len; i++) {
+ ctx.beginPath();
+ if (i && drag_points[i]) {
+ ctx.moveTo(x_points[i-1], y_points[i-1]);
+ } else {
+ ctx.moveTo(x_points[i]-1, y_points[i]);
+ }
+ ctx.lineTo(x_points[i], y_points[i]);
+ ctx.closePath();
+ ctx.stroke();
+ }
+ }
+ , stop_drawing = function() {
+ drawing = false;
+ }
+
+ // Title guesser and document creator available at https://gist.github.com/1059648
+ , guess_title = function(doc) {
+ var
+ h = "h6 h5 h4 h3 h2 h1".split(" ")
+ , i = h.length
+ , headers
+ , header_text
+ ;
+ while (i--) {
+ headers = doc.getElementsByTagName(h[i]);
+ for (var j = 0, len = headers.length; j < len; j++) {
+ header_text = headers[j].textContent.trim();
+ if (header_text) {
+ return header_text;
+ }
+ }
+ }
+ }
+ , doc_impl = document.implementation
+ , create_html_doc = function(html) {
+ var
+ dt = doc_impl.createDocumentType('html', null, null)
+ , doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
+ , doc_el = doc.documentElement
+ , head = doc_el.appendChild(doc.createElement("head"))
+ , charset_meta = head.appendChild(doc.createElement("meta"))
+ , title = head.appendChild(doc.createElement("title"))
+ , body = doc_el.appendChild(doc.createElement("body"))
+ , i = 0
+ , len = html.childNodes.length
+ ;
+ charset_meta.setAttribute("charset", html.ownerDocument.characterSet);
+ for (; i < len; i++) {
+ body.appendChild(doc.importNode(html.childNodes.item(i), true));
+ }
+ var title_text = guess_title(doc);
+ if (title_text) {
+ title.appendChild(doc.createTextNode(title_text));
+ }
+ return doc;
+ }
+;
+canvas.width = 500;
+canvas.height = 300;
+
+ if (typeof x_points === "string") {
+ x_points = JSON.parse(x_points);
+} if (typeof y_points === "string") {
+ y_points = JSON.parse(y_points);
+} if (typeof drag_points === "string") {
+ drag_points = JSON.parse(drag_points);
+} if (session.canvas_filename) {
+ canvas_filename.value = session.canvas_filename;
+} if (session.text) {
+ text.value = session.text;
+} if (session.text_filename) {
+ text_filename.value = session.text_filename;
+} if (session.html) {
+ html.innerHTML = session.html;
+} if (session.html_filename) {
+ html_filename.value = session.html_filename;
+}
+
+drawing = true;
+draw();
+drawing = false;
+
+canvas_clear_button.addEventListener("click", function() {
+ canvas.width = canvas.width;
+ x_points.length =
+ y_points.length =
+ drag_points.length =
+ 0;
+}, false);
+canvas.addEventListener("mousedown", function(event) {
+ event.preventDefault();
+ drawing = true;
+ add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false);
+ draw();
+}, false);
+canvas.addEventListener("mousemove", function(event) {
+ if (drawing) {
+ add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true);
+ draw();
+ }
+}, false);
+canvas.addEventListener("mouseup", stop_drawing, false);
+canvas.addEventListener("mouseout", stop_drawing, false);
+
+canvas_options_form.addEventListener("submit", function(event) {
+ event.preventDefault();
+ canvas.toBlob(function(blob) {
+ saveAs(
+ blob
+ , (canvas_filename.value || canvas_filename.placeholder) + ".png"
+ );
+ }, "image/png");
+}, false);
+
+text_options_form.addEventListener("submit", function(event) {
+ event.preventDefault();
+ var BB = get_blob();
+ saveAs(
+ new BB(
+ [text.value || text.placeholder]
+ , {type: "text/plain;charset=" + document.characterSet}
+ )
+ , (text_filename.value || text_filename.placeholder) + ".txt"
+ );
+}, false);
+
+html_options_form.addEventListener("submit", function(event) {
+ event.preventDefault();
+ var
+ BB = get_blob()
+ , xml_serializer = new XMLSerializer()
+ , doc = create_html_doc(html)
+ ;
+ saveAs(
+ new BB(
+ [xml_serializer.serializeToString(doc)]
+ , {type: "application/xhtml+xml;charset=" + document.characterSet}
+ )
+ , (html_filename.value || html_filename.placeholder) + ".xhtml"
+ );
+}, false);
+
+view.addEventListener("unload", function() {
+ session.x_points = JSON.stringify(x_points);
+ session.y_points = JSON.stringify(y_points);
+ session.drag_points = JSON.stringify(drag_points);
+ session.canvas_filename = canvas_filename.value;
+
+ session.text = text.value;
+ session.text_filename = text_filename.value;
+
+ session.html = html.innerHTML;
+ session.html_filename = html_filename.value;
+}, false);
+}(self));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/demo/demo.min.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,2 @@
+/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
+(function(n){"use strict";var s=n.document,g=function(A){return s.getElementById(A)},b=n.sessionStorage,x=function(){return n.Blob},f=g("canvas"),r=g("canvas-options"),y=g("canvas-filename"),p=g("canvas-clear"),q=g("text"),t=g("text-options"),h=g("text-filename"),m=g("html"),e=g("html-options"),i=g("html-filename"),u=f.getContext("2d"),z=false,a=b.x_points||[],o=b.y_points||[],d=b.drag_points||[],j=function(A,C,B){a.push(A);o.push(C);d.push(B)},l=function(){f.width=f.width;u.lineWidth=6;u.lineJoin="round";u.strokeStyle="#000000";var B=0,A=a.length;for(;B<A;B++){u.beginPath();if(B&&d[B]){u.moveTo(a[B-1],o[B-1])}else{u.moveTo(a[B]-1,o[B])}u.lineTo(a[B],o[B]);u.closePath();u.stroke()}},c=function(){z=false},w=function(E){var D="h6 h5 h4 h3 h2 h1".split(" "),C=D.length,F,G;while(C--){F=E.getElementsByTagName(D[C]);for(var B=0,A=F.length;B<A;B++){G=F[B].textContent.trim();if(G){return G}}}},v=s.implementation,k=function(D){var B=v.createDocumentType("html",null,null),J=v.createDocument("http://www.w3.org/1999/xhtml","html",B),A=J.documentElement,H=A.appendChild(J.createElement("head")),K=H.appendChild(J.createElement("meta")),I=H.appendChild(J.createElement("title")),E=A.appendChild(J.createElement("body")),C=0,G=D.childNodes.length;K.setAttribute("charset",D.ownerDocument.characterSet);for(;C<G;C++){E.appendChild(J.importNode(D.childNodes.item(C),true))}var F=w(J);if(F){I.appendChild(J.createTextNode(F))}return J};f.width=500;f.height=300;if(typeof a==="string"){a=JSON.parse(a)}if(typeof o==="string"){o=JSON.parse(o)}if(typeof d==="string"){d=JSON.parse(d)}if(b.canvas_filename){y.value=b.canvas_filename}if(b.text){q.value=b.text}if(b.text_filename){h.value=b.text_filename}if(b.html){m.innerHTML=b.html}if(b.html_filename){i.value=b.html_filename}z=true;l();z=false;p.addEventListener("click",function(){f.width=f.width;a.length=o.length=d.length=0},false);f.addEventListener("mousedown",function(A){A.preventDefault();z=true;j(A.pageX-f.offsetLeft,A.pageY-f.offsetTop,false);l()},false);f.addEventListener("mousemove",function(A){if(z){j(A.pageX-f.offsetLeft,A.pageY-f.offsetTop,true);l()}},false);f.addEventListener("mouseup",c,false);f.addEventListener("mouseout",c,false);r.addEventListener("submit",function(A){A.preventDefault();f.toBlob(function(B){saveAs(B,(y.value||y.placeholder)+".png")},"image/png")},false);t.addEventListener("submit",function(A){A.preventDefault();var B=x();saveAs(new B([q.value||q.placeholder],{type:"text/plain;charset="+s.characterSet}),(h.value||h.placeholder)+".txt")},false);e.addEventListener("submit",function(B){B.preventDefault();var D=x(),A=new XMLSerializer,C=k(m);saveAs(new D([A.serializeToString(C)],{type:"application/xhtml+xml;charset="+s.characterSet}),(i.value||i.placeholder)+".xhtml")},false);n.addEventListener("unload",function(){b.x_points=JSON.stringify(a);b.y_points=JSON.stringify(o);b.drag_points=JSON.stringify(d);b.canvas_filename=y.value;b.text=q.value;b.text_filename=h.value;b.html=m.innerHTML;b.html_filename=i.value},false)}(self));
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/FileSaver/demo/index.xhtml Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US-x-Hixie">
+<head>
+ <meta charset="utf-8"/>
+ <title>FileSaver.js demo</title>
+ <link rel="stylesheet" type="text/css" href="demo.css"/>
+</head>
+<body>
+ <h1><a href="https://github.com/eligrey/FileSaver.js">FileSaver.js</a> demo</h1>
+ <p>
+ The following examples demonstrate how it is possible to generate and save any type of data right in the browser using the W3C <code>saveAs()</code> <a href="http://www.w3.org/TR/file-writer-api/#the-filesaver-interface">FileSaver</a> interface, without contacting any servers.
+ </p>
+ <section id="image-demo">
+ <h2>Saving an image</h2>
+ <canvas class="input" id="canvas" width="500" height="300"/>
+ <form id="canvas-options">
+ <label>Filename: <input type="text" class="filename" id="canvas-filename" placeholder="doodle"/>.png</label>
+ <input type="submit" value="Save"/>
+ <input type="button" id="canvas-clear" value="Clear"/>
+ </form>
+ </section>
+ <section id="text-demo">
+ <h2>Saving text</h2>
+ <textarea class="input" id="text" placeholder="Once upon a time..."/>
+ <form id="text-options">
+ <label>Filename: <input type="text" class="filename" id="text-filename" placeholder="a plain document"/>.txt</label>
+ <input type="submit" value="Save"/>
+ </form>
+ </section>
+ <section id="html-demo">
+ <h2>Saving rich text</h2>
+ <div class="input" id="html" contenteditable="">
+ <h3>Some example rich text</h3>
+ <ul>
+ <li><del>Plain</del> <ins>Boring</ins> text.</li>
+ <li><em>Emphasized text!</em></li>
+ <li><strong>Strong text!</strong></li>
+ <li>
+ <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="70" height="70">
+ <circle cx="35" cy="35" r="35" fill="red"/>
+ <text x="10" y="40">image</text>
+ </svg>
+ </li>
+ <li><a href="https://github.com/eligrey/FileSaver.js">A link.</a></li>
+ </ul>
+ </div>
+ <form id="html-options">
+ <label>Filename: <input type="text" class="filename" id="html-filename" placeholder="a rich document"/>.xhtml</label>
+ <input type="submit" value="Save"/>
+ </form>
+ </section>
+ <script async="" src="https://cdn.rawgit.com/eligrey/Blob.js/master/Blob.js"/>
+ <script async="" src="https://cdn.rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"/>
+ <script async="" src="https://cdn.rawgit.com/eligrey/FileSaver.js/master/FileSaver.js"/>
+ <script async="" src="https://cdn.rawgit.com/eligrey/FileSaver.js/master/demo/demo.js"/>
+</body>
+</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/backbone-relational/backbone-relational.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,2077 @@
+/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab: */
+/**
+ * Backbone-relational.js 0.9.0
+ * (c) 2011-2014 Paul Uithol and contributors (https://github.com/PaulUithol/Backbone-relational/graphs/contributors)
+ *
+ * Backbone-relational may be freely distributed under the MIT license; see the accompanying LICENSE.txt.
+ * For details and documentation: https://github.com/PaulUithol/Backbone-relational.
+ * Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone.
+ *
+ * Example:
+ *
+ Zoo = Backbone.RelationalModel.extend({
+ relations: [ {
+ type: Backbone.HasMany,
+ key: 'animals',
+ relatedModel: 'Animal',
+ reverseRelation: {
+ key: 'livesIn',
+ includeInJSON: 'id'
+ // 'relatedModel' is automatically set to 'Zoo'; the 'relationType' to 'HasOne'.
+ }
+ } ],
+
+ toString: function() {
+ return this.get( 'name' );
+ }
+ });
+
+ Animal = Backbone.RelationalModel.extend({
+ toString: function() {
+ return this.get( 'species' );
+ }
+ });
+
+ // Creating the zoo will give it a collection with one animal in it: the monkey.
+ // The animal created after that has a relation `livesIn` that points to the zoo it's currently associated with.
+ // If you instantiate (or fetch) the zebra later, it will automatically be added.
+
+ var zoo = new Zoo({
+ name: 'Artis',
+ animals: [ { id: 'monkey-1', species: 'Chimp' }, 'lion-1', 'zebra-1' ]
+ });
+
+ var lion = new Animal( { id: 'lion-1', species: 'Lion' } ),
+ monkey = zoo.get( 'animals' ).first(),
+ sameZoo = lion.get( 'livesIn' );
+ */
+( function( root, factory ) {
+ // Set up Backbone-relational for the environment. Start with AMD.
+ if ( typeof define === 'function' && define.amd ) {
+ define( [ 'exports', 'backbone', 'underscore' ], factory );
+ }
+ // Next for Node.js or CommonJS.
+ else if ( typeof exports !== 'undefined' ) {
+ factory( exports, require( 'backbone' ), require( 'underscore' ) );
+ }
+ // Finally, as a browser global. Use `root` here as it references `window`.
+ else {
+ factory( root, root.Backbone, root._ );
+ }
+}( this, function( exports, Backbone, _ ) {
+ "use strict";
+
+ Backbone.Relational = {
+ showWarnings: true
+ };
+
+ /**
+ * Semaphore mixin; can be used as both binary and counting.
+ **/
+ Backbone.Semaphore = {
+ _permitsAvailable: null,
+ _permitsUsed: 0,
+
+ acquire: function() {
+ if ( this._permitsAvailable && this._permitsUsed >= this._permitsAvailable ) {
+ throw new Error( 'Max permits acquired' );
+ }
+ else {
+ this._permitsUsed++;
+ }
+ },
+
+ release: function() {
+ if ( this._permitsUsed === 0 ) {
+ throw new Error( 'All permits released' );
+ }
+ else {
+ this._permitsUsed--;
+ }
+ },
+
+ isLocked: function() {
+ return this._permitsUsed > 0;
+ },
+
+ setAvailablePermits: function( amount ) {
+ if ( this._permitsUsed > amount ) {
+ throw new Error( 'Available permits cannot be less than used permits' );
+ }
+ this._permitsAvailable = amount;
+ }
+ };
+
+ /**
+ * A BlockingQueue that accumulates items while blocked (via 'block'),
+ * and processes them when unblocked (via 'unblock').
+ * Process can also be called manually (via 'process').
+ */
+ Backbone.BlockingQueue = function() {
+ this._queue = [];
+ };
+ _.extend( Backbone.BlockingQueue.prototype, Backbone.Semaphore, {
+ _queue: null,
+
+ add: function( func ) {
+ if ( this.isBlocked() ) {
+ this._queue.push( func );
+ }
+ else {
+ func();
+ }
+ },
+
+ // Some of the queued events may trigger other blocking events. By
+ // copying the queue here it allows queued events to process closer to
+ // the natural order.
+ //
+ // queue events [ 'A', 'B', 'C' ]
+ // A handler of 'B' triggers 'D' and 'E'
+ // By copying `this._queue` this executes:
+ // [ 'A', 'B', 'D', 'E', 'C' ]
+ // The same order the would have executed if they didn't have to be
+ // delayed and queued.
+ process: function() {
+ var queue = this._queue;
+ this._queue = [];
+ while ( queue && queue.length ) {
+ queue.shift()();
+ }
+ },
+
+ block: function() {
+ this.acquire();
+ },
+
+ unblock: function() {
+ this.release();
+ if ( !this.isBlocked() ) {
+ this.process();
+ }
+ },
+
+ isBlocked: function() {
+ return this.isLocked();
+ }
+ });
+ /**
+ * Global event queue. Accumulates external events ('add:<key>', 'remove:<key>' and 'change:<key>')
+ * until the top-level object is fully initialized (see 'Backbone.RelationalModel').
+ */
+ Backbone.Relational.eventQueue = new Backbone.BlockingQueue();
+
+ /**
+ * Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel.
+ * Handles lookup for relations.
+ */
+ Backbone.Store = function() {
+ this._collections = [];
+ this._reverseRelations = [];
+ this._orphanRelations = [];
+ this._subModels = [];
+ this._modelScopes = [ exports ];
+ };
+ _.extend( Backbone.Store.prototype, Backbone.Events, {
+ /**
+ * Create a new `Relation`.
+ * @param {Backbone.RelationalModel} [model]
+ * @param {Object} relation
+ * @param {Object} [options]
+ */
+ initializeRelation: function( model, relation, options ) {
+ var type = !_.isString( relation.type ) ? relation.type : Backbone[ relation.type ] || this.getObjectByName( relation.type );
+ if ( type && type.prototype instanceof Backbone.Relation ) {
+ var rel = new type( model, relation, options ); // Also pushes the new Relation into `model._relations`
+ }
+ else {
+ Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid relation type!', relation );
+ }
+ },
+
+ /**
+ * Add a scope for `getObjectByName` to look for model types by name.
+ * @param {Object} scope
+ */
+ addModelScope: function( scope ) {
+ this._modelScopes.push( scope );
+ },
+
+ /**
+ * Remove a scope.
+ * @param {Object} scope
+ */
+ removeModelScope: function( scope ) {
+ this._modelScopes = _.without( this._modelScopes, scope );
+ },
+
+ /**
+ * Add a set of subModelTypes to the store, that can be used to resolve the '_superModel'
+ * for a model later in 'setupSuperModel'.
+ *
+ * @param {Backbone.RelationalModel} subModelTypes
+ * @param {Backbone.RelationalModel} superModelType
+ */
+ addSubModels: function( subModelTypes, superModelType ) {
+ this._subModels.push({
+ 'superModelType': superModelType,
+ 'subModels': subModelTypes
+ });
+ },
+
+ /**
+ * Check if the given modelType is registered as another model's subModel. If so, add it to the super model's
+ * '_subModels', and set the modelType's '_superModel', '_subModelTypeName', and '_subModelTypeAttribute'.
+ *
+ * @param {Backbone.RelationalModel} modelType
+ */
+ setupSuperModel: function( modelType ) {
+ _.find( this._subModels, function( subModelDef ) {
+ return _.filter( subModelDef.subModels || [], function( subModelTypeName, typeValue ) {
+ var subModelType = this.getObjectByName( subModelTypeName );
+
+ if ( modelType === subModelType ) {
+ // Set 'modelType' as a child of the found superModel
+ subModelDef.superModelType._subModels[ typeValue ] = modelType;
+
+ // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'.
+ modelType._superModel = subModelDef.superModelType;
+ modelType._subModelTypeValue = typeValue;
+ modelType._subModelTypeAttribute = subModelDef.superModelType.prototype.subModelTypeAttribute;
+ return true;
+ }
+ }, this ).length;
+ }, this );
+ },
+
+ /**
+ * Add a reverse relation. Is added to the 'relations' property on model's prototype, and to
+ * existing instances of 'model' in the store as well.
+ * @param {Object} relation
+ * @param {Backbone.RelationalModel} relation.model
+ * @param {String} relation.type
+ * @param {String} relation.key
+ * @param {String|Object} relation.relatedModel
+ */
+ addReverseRelation: function( relation ) {
+ var exists = _.any( this._reverseRelations, function( rel ) {
+ return _.all( relation || [], function( val, key ) {
+ return val === rel[ key ];
+ });
+ });
+
+ if ( !exists && relation.model && relation.type ) {
+ this._reverseRelations.push( relation );
+ this._addRelation( relation.model, relation );
+ this.retroFitRelation( relation );
+ }
+ },
+
+ /**
+ * Deposit a `relation` for which the `relatedModel` can't be resolved at the moment.
+ *
+ * @param {Object} relation
+ */
+ addOrphanRelation: function( relation ) {
+ var exists = _.any( this._orphanRelations, function( rel ) {
+ return _.all( relation || [], function( val, key ) {
+ return val === rel[ key ];
+ });
+ });
+
+ if ( !exists && relation.model && relation.type ) {
+ this._orphanRelations.push( relation );
+ }
+ },
+
+ /**
+ * Try to initialize any `_orphanRelation`s
+ */
+ processOrphanRelations: function() {
+ // Make sure to operate on a copy since we're removing while iterating
+ _.each( this._orphanRelations.slice( 0 ), function( rel ) {
+ var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel );
+ if ( relatedModel ) {
+ this.initializeRelation( null, rel );
+ this._orphanRelations = _.without( this._orphanRelations, rel );
+ }
+ }, this );
+ },
+
+ /**
+ *
+ * @param {Backbone.RelationalModel.constructor} type
+ * @param {Object} relation
+ * @private
+ */
+ _addRelation: function( type, relation ) {
+ if ( !type.prototype.relations ) {
+ type.prototype.relations = [];
+ }
+ type.prototype.relations.push( relation );
+
+ _.each( type._subModels || [], function( subModel ) {
+ this._addRelation( subModel, relation );
+ }, this );
+ },
+
+ /**
+ * Add a 'relation' to all existing instances of 'relation.model' in the store
+ * @param {Object} relation
+ */
+ retroFitRelation: function( relation ) {
+ var coll = this.getCollection( relation.model, false );
+ coll && coll.each( function( model ) {
+ if ( !( model instanceof relation.model ) ) {
+ return;
+ }
+
+ var rel = new relation.type( model, relation );
+ }, this );
+ },
+
+ /**
+ * Find the Store's collection for a certain type of model.
+ * @param {Backbone.RelationalModel} type
+ * @param {Boolean} [create=true] Should a collection be created if none is found?
+ * @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null
+ */
+ getCollection: function( type, create ) {
+ if ( type instanceof Backbone.RelationalModel ) {
+ type = type.constructor;
+ }
+
+ var rootModel = type;
+ while ( rootModel._superModel ) {
+ rootModel = rootModel._superModel;
+ }
+
+ var coll = _.find( this._collections, function( item ) {
+ return item.model === rootModel;
+ });
+
+ if ( !coll && create !== false ) {
+ coll = this._createCollection( rootModel );
+ }
+
+ return coll;
+ },
+
+ /**
+ * Find a model type on one of the modelScopes by name. Names are split on dots.
+ * @param {String} name
+ * @return {Object}
+ */
+ getObjectByName: function( name ) {
+ var parts = name.split( '.' ),
+ type = null;
+
+ _.find( this._modelScopes, function( scope ) {
+ type = _.reduce( parts || [], function( memo, val ) {
+ return memo ? memo[ val ] : undefined;
+ }, scope );
+
+ if ( type && type !== scope ) {
+ return true;
+ }
+ }, this );
+
+ return type;
+ },
+
+ _createCollection: function( type ) {
+ var coll;
+
+ // If 'type' is an instance, take its constructor
+ if ( type instanceof Backbone.RelationalModel ) {
+ type = type.constructor;
+ }
+
+ // Type should inherit from Backbone.RelationalModel.
+ if ( type.prototype instanceof Backbone.RelationalModel ) {
+ coll = new Backbone.Collection();
+ coll.model = type;
+
+ this._collections.push( coll );
+ }
+
+ return coll;
+ },
+
+ /**
+ * Find the attribute that is to be used as the `id` on a given object
+ * @param type
+ * @param {String|Number|Object|Backbone.RelationalModel} item
+ * @return {String|Number}
+ */
+ resolveIdForItem: function( type, item ) {
+ var id = _.isString( item ) || _.isNumber( item ) ? item : null;
+
+ if ( id === null ) {
+ if ( item instanceof Backbone.RelationalModel ) {
+ id = item.id;
+ }
+ else if ( _.isObject( item ) ) {
+ id = item[ type.prototype.idAttribute ];
+ }
+ }
+
+ // Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179')
+ if ( !id && id !== 0 ) {
+ id = null;
+ }
+
+ return id;
+ },
+
+ /**
+ * Find a specific model of a certain `type` in the store
+ * @param type
+ * @param {String|Number|Object|Backbone.RelationalModel} item
+ */
+ find: function( type, item ) {
+ var id = this.resolveIdForItem( type, item ),
+ coll = this.getCollection( type );
+
+ // Because the found object could be of any of the type's superModel
+ // types, only return it if it's actually of the type asked for.
+ if ( coll ) {
+ var obj = coll.get( id );
+
+ if ( obj instanceof type ) {
+ return obj;
+ }
+ }
+
+ return null;
+ },
+
+ /**
+ * Add a 'model' to its appropriate collection. Retain the original contents of 'model.collection'.
+ * @param {Backbone.RelationalModel} model
+ */
+ register: function( model ) {
+ var coll = this.getCollection( model );
+
+ if ( coll ) {
+ var modelColl = model.collection;
+ coll.add( model );
+ model.collection = modelColl;
+ }
+ },
+
+ /**
+ * Check if the given model may use the given `id`
+ * @param model
+ * @param [id]
+ */
+ checkId: function( model, id ) {
+ var coll = this.getCollection( model ),
+ duplicate = coll && coll.get( id );
+
+ if ( duplicate && model !== duplicate ) {
+ if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) {
+ console.warn( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o', duplicate, model );
+ }
+
+ throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" );
+ }
+ },
+
+ /**
+ * Explicitly update a model's id in its store collection
+ * @param {Backbone.RelationalModel} model
+ */
+ update: function( model ) {
+ var coll = this.getCollection( model );
+
+ // Register a model if it isn't yet (which happens if it was created without an id).
+ if ( !coll.contains( model ) ) {
+ this.register( model );
+ }
+
+ // This triggers updating the lookup indices kept in a collection
+ coll._onModelEvent( 'change:' + model.idAttribute, model, coll );
+
+ // Trigger an event on model so related models (having the model's new id in their keyContents) can add it.
+ model.trigger( 'relational:change:id', model, coll );
+ },
+
+ /**
+ * Unregister from the store: a specific model, a collection, or a model type.
+ * @param {Backbone.RelationalModel|Backbone.RelationalModel.constructor|Backbone.Collection} type
+ */
+ unregister: function( type ) {
+ var coll,
+ models;
+
+ if ( type instanceof Backbone.Model ) {
+ coll = this.getCollection( type );
+ models = [ type ];
+ }
+ else if ( type instanceof Backbone.Collection ) {
+ coll = this.getCollection( type.model );
+ models = _.clone( type.models );
+ }
+ else {
+ coll = this.getCollection( type );
+ models = _.clone( coll.models );
+ }
+
+ _.each( models, function( model ) {
+ this.stopListening( model );
+ _.invoke( model.getRelations(), 'stopListening' );
+ }, this );
+
+
+ // If we've unregistered an entire store collection, reset the collection (which is much faster).
+ // Otherwise, remove each model one by one.
+ if ( _.contains( this._collections, type ) ) {
+ coll.reset( [] );
+ }
+ else {
+ _.each( models, function( model ) {
+ if ( coll.get( model ) ) {
+ coll.remove( model );
+ }
+ else {
+ coll.trigger( 'relational:remove', model, coll );
+ }
+ }, this );
+ }
+ },
+
+ /**
+ * Reset the `store` to it's original state. The `reverseRelations` are kept though, since attempting to
+ * re-initialize these on models would lead to a large amount of warnings.
+ */
+ reset: function() {
+ this.stopListening();
+
+ // Unregister each collection to remove event listeners
+ _.each( this._collections, function( coll ) {
+ this.unregister( coll );
+ }, this );
+
+ this._collections = [];
+ this._subModels = [];
+ this._modelScopes = [ exports ];
+ }
+ });
+ Backbone.Relational.store = new Backbone.Store();
+
+ /**
+ * The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:<key>' events
+ * are used to regulate addition and removal of models from relations.
+ *
+ * @param {Backbone.RelationalModel} [instance] Model that this relation is created for. If no model is supplied,
+ * Relation just tries to instantiate it's `reverseRelation` if specified, and bails out after that.
+ * @param {Object} options
+ * @param {string} options.key
+ * @param {Backbone.RelationalModel.constructor} options.relatedModel
+ * @param {Boolean|String} [options.includeInJSON=true] Serialize the given attribute for related model(s)' in toJSON, or just their ids.
+ * @param {Boolean} [options.createModels=true] Create objects from the contents of keys if the object is not found in Backbone.store.
+ * @param {Object} [options.reverseRelation] Specify a bi-directional relation. If provided, Relation will reciprocate
+ * the relation to the 'relatedModel'. Required and optional properties match 'options', except that it also needs
+ * {Backbone.Relation|String} type ('HasOne' or 'HasMany').
+ * @param {Object} opts
+ */
+ Backbone.Relation = function( instance, options, opts ) {
+ this.instance = instance;
+ // Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype
+ options = _.isObject( options ) ? options : {};
+ this.reverseRelation = _.defaults( options.reverseRelation || {}, this.options.reverseRelation );
+ this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options );
+
+ this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type :
+ Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type );
+
+ this.key = this.options.key;
+ this.keySource = this.options.keySource || this.key;
+ this.keyDestination = this.options.keyDestination || this.keySource || this.key;
+
+ this.model = this.options.model || this.instance.constructor;
+
+ this.relatedModel = this.options.relatedModel;
+
+ // No 'relatedModel' is interpreted as self-referential
+ if ( _.isUndefined( this.relatedModel ) ) {
+ this.relatedModel = this.model;
+ }
+
+ // Otherwise, try to resolve the given value to an object
+ if ( _.isFunction( this.relatedModel ) && !( this.relatedModel.prototype instanceof Backbone.RelationalModel ) ) {
+ this.relatedModel = _.result( this, 'relatedModel' );
+ }
+ if ( _.isString( this.relatedModel ) ) {
+ this.relatedModel = Backbone.Relational.store.getObjectByName( this.relatedModel );
+ }
+
+
+ if ( !this.checkPreconditions() ) {
+ return;
+ }
+
+ // Add the reverse relation on 'relatedModel' to the store's reverseRelations
+ if ( !this.options.isAutoRelation && this.reverseRelation.type && this.reverseRelation.key ) {
+ Backbone.Relational.store.addReverseRelation( _.defaults( {
+ isAutoRelation: true,
+ model: this.relatedModel,
+ relatedModel: this.model,
+ reverseRelation: this.options // current relation is the 'reverseRelation' for its own reverseRelation
+ },
+ this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.)
+ ) );
+ }
+
+ if ( instance ) {
+ var contentKey = this.keySource;
+ if ( contentKey !== this.key && _.isObject( this.instance.get( this.key ) ) ) {
+ contentKey = this.key;
+ }
+
+ this.setKeyContents( this.instance.get( contentKey ) );
+ this.relatedCollection = Backbone.Relational.store.getCollection( this.relatedModel );
+
+ // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
+ if ( this.keySource !== this.key ) {
+ delete this.instance.attributes[ this.keySource ];
+ }
+
+ // Add this Relation to instance._relations
+ this.instance._relations[ this.key ] = this;
+
+ this.initialize( opts );
+
+ if ( this.options.autoFetch ) {
+ this.instance.getAsync( this.key, _.isObject( this.options.autoFetch ) ? this.options.autoFetch : {} );
+ }
+
+ // When 'relatedModel' are created or destroyed, check if it affects this relation.
+ this.listenTo( this.instance, 'destroy', this.destroy )
+ .listenTo( this.relatedCollection, 'relational:add relational:change:id', this.tryAddRelated )
+ .listenTo( this.relatedCollection, 'relational:remove', this.removeRelated );
+ }
+ };
+ // Fix inheritance :\
+ Backbone.Relation.extend = Backbone.Model.extend;
+ // Set up all inheritable **Backbone.Relation** properties and methods.
+ _.extend( Backbone.Relation.prototype, Backbone.Events, Backbone.Semaphore, {
+ options: {
+ createModels: true,
+ includeInJSON: true,
+ isAutoRelation: false,
+ autoFetch: false,
+ parse: false
+ },
+
+ instance: null,
+ key: null,
+ keyContents: null,
+ relatedModel: null,
+ relatedCollection: null,
+ reverseRelation: null,
+ related: null,
+
+ /**
+ * Check several pre-conditions.
+ * @return {Boolean} True if pre-conditions are satisfied, false if they're not.
+ */
+ checkPreconditions: function() {
+ var i = this.instance,
+ k = this.key,
+ m = this.model,
+ rm = this.relatedModel,
+ warn = Backbone.Relational.showWarnings && typeof console !== 'undefined';
+
+ if ( !m || !k || !rm ) {
+ warn && console.warn( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).', this, m, k, rm );
+ return false;
+ }
+ // Check if the type in 'model' inherits from Backbone.RelationalModel
+ if ( !( m.prototype instanceof Backbone.RelationalModel ) ) {
+ warn && console.warn( 'Relation=%o: model does not inherit from Backbone.RelationalModel (%o).', this, i );
+ return false;
+ }
+ // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel
+ if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) {
+ warn && console.warn( 'Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).', this, rm );
+ return false;
+ }
+ // Check if this is not a HasMany, and the reverse relation is HasMany as well
+ if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) {
+ warn && console.warn( 'Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.', this );
+ return false;
+ }
+ // Check if we're not attempting to create a relationship on a `key` that's already used.
+ if ( i && _.keys( i._relations ).length ) {
+ var existing = _.find( i._relations, function( rel ) {
+ return rel.key === k;
+ }, this );
+
+ if ( existing ) {
+ warn && console.warn( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.',
+ this, k, i, existing );
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ /**
+ * Set the related model(s) for this relation
+ * @param {Backbone.Model|Backbone.Collection} related
+ */
+ setRelated: function( related ) {
+ this.related = related;
+ this.instance.attributes[ this.key ] = related;
+ },
+
+ /**
+ * Determine if a relation (on a different RelationalModel) is the reverse
+ * relation of the current one.
+ * @param {Backbone.Relation} relation
+ * @return {Boolean}
+ */
+ _isReverseRelation: function( relation ) {
+ return relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key &&
+ this.key === relation.reverseRelation.key;
+ },
+
+ /**
+ * Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s).
+ * @param {Backbone.RelationalModel} [model] Get the reverse relations for a specific model.
+ * If not specified, 'this.related' is used.
+ * @return {Backbone.Relation[]}
+ */
+ getReverseRelations: function( model ) {
+ var reverseRelations = [];
+ // Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array.
+ var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] ),
+ relations = null,
+ relation = null;
+
+ for( var i = 0; i < ( models || [] ).length; i++ ) {
+ relations = models[ i ].getRelations() || [];
+
+ for( var j = 0; j < relations.length; j++ ) {
+ relation = relations[ j ];
+
+ if ( this._isReverseRelation( relation ) ) {
+ reverseRelations.push( relation );
+ }
+ }
+ }
+
+ return reverseRelations;
+ },
+
+ /**
+ * When `this.instance` is destroyed, cleanup our relations.
+ * Get reverse relation, call removeRelated on each.
+ */
+ destroy: function() {
+ this.stopListening();
+
+ if ( this instanceof Backbone.HasOne ) {
+ this.setRelated( null );
+ }
+ else if ( this instanceof Backbone.HasMany ) {
+ this.setRelated( this._prepareCollection() );
+ }
+
+ _.each( this.getReverseRelations(), function( relation ) {
+ relation.removeRelated( this.instance );
+ }, this );
+ }
+ });
+
+ Backbone.HasOne = Backbone.Relation.extend({
+ options: {
+ reverseRelation: { type: 'HasMany' }
+ },
+
+ initialize: function( opts ) {
+ this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange );
+
+ var related = this.findRelated( opts );
+ this.setRelated( related );
+
+ // Notify new 'related' object of the new relation.
+ _.each( this.getReverseRelations(), function( relation ) {
+ relation.addRelated( this.instance, opts );
+ }, this );
+ },
+
+ /**
+ * Find related Models.
+ * @param {Object} [options]
+ * @return {Backbone.Model}
+ */
+ findRelated: function( options ) {
+ var related = null;
+
+ options = _.defaults( { parse: this.options.parse }, options );
+
+ if ( this.keyContents instanceof this.relatedModel ) {
+ related = this.keyContents;
+ }
+ else if ( this.keyContents || this.keyContents === 0 ) { // since 0 can be a valid `id` as well
+ var opts = _.defaults( { create: this.options.createModels }, options );
+ related = this.relatedModel.findOrCreate( this.keyContents, opts );
+ }
+
+ // Nullify `keyId` if we have a related model; in case it was already part of the relation
+ if ( related ) {
+ this.keyId = null;
+ }
+
+ return related;
+ },
+
+ /**
+ * Normalize and reduce `keyContents` to an `id`, for easier comparison
+ * @param {String|Number|Backbone.Model} keyContents
+ */
+ setKeyContents: function( keyContents ) {
+ this.keyContents = keyContents;
+ this.keyId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, this.keyContents );
+ },
+
+ /**
+ * Event handler for `change:<key>`.
+ * If the key is changed, notify old & new reverse relations and initialize the new relation.
+ */
+ onChange: function( model, attr, options ) {
+ // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange)
+ if ( this.isLocked() ) {
+ return;
+ }
+ this.acquire();
+ options = options ? _.clone( options ) : {};
+
+ // 'options.__related' is set by 'addRelated'/'removeRelated'. If it is set, the change
+ // is the result of a call from a relation. If it's not, the change is the result of
+ // a 'set' call on this.instance.
+ var changed = _.isUndefined( options.__related ),
+ oldRelated = changed ? this.related : options.__related;
+
+ if ( changed ) {
+ this.setKeyContents( attr );
+ var related = this.findRelated( options );
+ this.setRelated( related );
+ }
+
+ // Notify old 'related' object of the terminated relation
+ if ( oldRelated && this.related !== oldRelated ) {
+ _.each( this.getReverseRelations( oldRelated ), function( relation ) {
+ relation.removeRelated( this.instance, null, options );
+ }, this );
+ }
+
+ // Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated;
+ // that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'.
+ // In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet.
+ _.each( this.getReverseRelations(), function( relation ) {
+ relation.addRelated( this.instance, options );
+ }, this );
+
+ // Fire the 'change:<key>' event if 'related' was updated
+ if ( !options.silent && this.related !== oldRelated ) {
+ var dit = this;
+ this.changed = true;
+ Backbone.Relational.eventQueue.add( function() {
+ dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true );
+ dit.changed = false;
+ });
+ }
+ this.release();
+ },
+
+ /**
+ * If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents'
+ */
+ tryAddRelated: function( model, coll, options ) {
+ if ( ( this.keyId || this.keyId === 0 ) && model.id === this.keyId ) { // since 0 can be a valid `id` as well
+ this.addRelated( model, options );
+ this.keyId = null;
+ }
+ },
+
+ addRelated: function( model, options ) {
+ // Allow 'model' to set up its relations before proceeding.
+ // (which can result in a call to 'addRelated' from a relation of 'model')
+ var dit = this;
+ model.queue( function() {
+ if ( model !== dit.related ) {
+ var oldRelated = dit.related || null;
+ dit.setRelated( model );
+ dit.onChange( dit.instance, model, _.defaults( { __related: oldRelated }, options ) );
+ }
+ });
+ },
+
+ removeRelated: function( model, coll, options ) {
+ if ( !this.related ) {
+ return;
+ }
+
+ if ( model === this.related ) {
+ var oldRelated = this.related || null;
+ this.setRelated( null );
+ this.onChange( this.instance, model, _.defaults( { __related: oldRelated }, options ) );
+ }
+ }
+ });
+
+ Backbone.HasMany = Backbone.Relation.extend({
+ collectionType: null,
+
+ options: {
+ reverseRelation: { type: 'HasOne' },
+ collectionType: Backbone.Collection,
+ collectionKey: true,
+ collectionOptions: {}
+ },
+
+ initialize: function( opts ) {
+ this.listenTo( this.instance, 'relational:change:' + this.key, this.onChange );
+
+ // Handle a custom 'collectionType'
+ this.collectionType = this.options.collectionType;
+ if ( _.isFunction( this.collectionType ) && this.collectionType !== Backbone.Collection && !( this.collectionType.prototype instanceof Backbone.Collection ) ) {
+ this.collectionType = _.result( this, 'collectionType' );
+ }
+ if ( _.isString( this.collectionType ) ) {
+ this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType );
+ }
+ if ( this.collectionType !== Backbone.Collection && !( this.collectionType.prototype instanceof Backbone.Collection ) ) {
+ throw new Error( '`collectionType` must inherit from Backbone.Collection' );
+ }
+
+ var related = this.findRelated( opts );
+ this.setRelated( related );
+ },
+
+ /**
+ * Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany.
+ * If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option.
+ * @param {Backbone.Collection} [collection]
+ * @return {Backbone.Collection}
+ */
+ _prepareCollection: function( collection ) {
+ if ( this.related ) {
+ this.stopListening( this.related );
+ }
+
+ if ( !collection || !( collection instanceof Backbone.Collection ) ) {
+ var options = _.isFunction( this.options.collectionOptions ) ?
+ this.options.collectionOptions( this.instance ) : this.options.collectionOptions;
+
+ collection = new this.collectionType( null, options );
+ }
+
+ collection.model = this.relatedModel;
+
+ if ( this.options.collectionKey ) {
+ var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey;
+
+ if ( collection[ key ] && collection[ key ] !== this.instance ) {
+ if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) {
+ console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey );
+ }
+ }
+ else if ( key ) {
+ collection[ key ] = this.instance;
+ }
+ }
+
+ this.listenTo( collection, 'relational:add', this.handleAddition )
+ .listenTo( collection, 'relational:remove', this.handleRemoval )
+ .listenTo( collection, 'relational:reset', this.handleReset );
+
+ return collection;
+ },
+
+ /**
+ * Find related Models.
+ * @param {Object} [options]
+ * @return {Backbone.Collection}
+ */
+ findRelated: function( options ) {
+ var related = null;
+
+ options = _.defaults( { parse: this.options.parse }, options );
+
+ // Replace 'this.related' by 'this.keyContents' if it is a Backbone.Collection
+ if ( this.keyContents instanceof Backbone.Collection ) {
+ this._prepareCollection( this.keyContents );
+ related = this.keyContents;
+ }
+ // Otherwise, 'this.keyContents' should be an array of related object ids.
+ // Re-use the current 'this.related' if it is a Backbone.Collection; otherwise, create a new collection.
+ else {
+ var toAdd = [];
+
+ _.each( this.keyContents, function( attributes ) {
+ var model = null;
+
+ if ( attributes instanceof this.relatedModel ) {
+ model = attributes;
+ }
+ else {
+ // If `merge` is true, update models here, instead of during update.
+ model = this.relatedModel.findOrCreate( attributes,
+ _.extend( { merge: true }, options, { create: this.options.createModels } )
+ );
+ }
+
+ model && toAdd.push( model );
+ }, this );
+
+ if ( this.related instanceof Backbone.Collection ) {
+ related = this.related;
+ }
+ else {
+ related = this._prepareCollection();
+ }
+
+ // By now, both `merge` and `parse` will already have been executed for models if they were specified.
+ // Disable them to prevent additional calls.
+ related.set( toAdd, _.defaults( { merge: false, parse: false }, options ) );
+ }
+
+ // Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged')
+ this.keyIds = _.difference( this.keyIds, _.pluck( related.models, 'id' ) );
+
+ return related;
+ },
+
+ /**
+ * Normalize and reduce `keyContents` to a list of `ids`, for easier comparison
+ * @param {String|Number|String[]|Number[]|Backbone.Collection} keyContents
+ */
+ setKeyContents: function( keyContents ) {
+ this.keyContents = keyContents instanceof Backbone.Collection ? keyContents : null;
+ this.keyIds = [];
+
+ if ( !this.keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well
+ // Handle cases the an API/user supplies just an Object/id instead of an Array
+ this.keyContents = _.isArray( keyContents ) ? keyContents : [ keyContents ];
+
+ _.each( this.keyContents, function( item ) {
+ var itemId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item );
+ if ( itemId || itemId === 0 ) {
+ this.keyIds.push( itemId );
+ }
+ }, this );
+ }
+ },
+
+ /**
+ * Event handler for `change:<key>`.
+ * If the contents of the key are changed, notify old & new reverse relations and initialize the new relation.
+ */
+ onChange: function( model, attr, options ) {
+ options = options ? _.clone( options ) : {};
+ this.setKeyContents( attr );
+ this.changed = false;
+
+ var related = this.findRelated( options );
+ this.setRelated( related );
+
+ if ( !options.silent ) {
+ var dit = this;
+ Backbone.Relational.eventQueue.add( function() {
+ // The `changed` flag can be set in `handleAddition` or `handleRemoval`
+ if ( dit.changed ) {
+ dit.instance.trigger( 'change:' + dit.key, dit.instance, dit.related, options, true );
+ dit.changed = false;
+ }
+ });
+ }
+ },
+
+ /**
+ * When a model is added to a 'HasMany', trigger 'add' on 'this.instance' and notify reverse relations.
+ * (should be 'HasOne', must set 'this.instance' as their related).
+ */
+ handleAddition: function( model, coll, options ) {
+ //console.debug('handleAddition called; args=%o', arguments);
+ options = options ? _.clone( options ) : {};
+ this.changed = true;
+
+ _.each( this.getReverseRelations( model ), function( relation ) {
+ relation.addRelated( this.instance, options );
+ }, this );
+
+ // Only trigger 'add' once the newly added model is initialized (so, has its relations set up)
+ var dit = this;
+ !options.silent && Backbone.Relational.eventQueue.add( function() {
+ dit.instance.trigger( 'add:' + dit.key, model, dit.related, options );
+ });
+ },
+
+ /**
+ * When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations.
+ * (should be 'HasOne', which should be nullified)
+ */
+ handleRemoval: function( model, coll, options ) {
+ //console.debug('handleRemoval called; args=%o', arguments);
+ options = options ? _.clone( options ) : {};
+ this.changed = true;
+
+ _.each( this.getReverseRelations( model ), function( relation ) {
+ relation.removeRelated( this.instance, null, options );
+ }, this );
+
+ var dit = this;
+ !options.silent && Backbone.Relational.eventQueue.add( function() {
+ dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options );
+ });
+ },
+
+ handleReset: function( coll, options ) {
+ var dit = this;
+ options = options ? _.clone( options ) : {};
+ !options.silent && Backbone.Relational.eventQueue.add( function() {
+ dit.instance.trigger( 'reset:' + dit.key, dit.related, options );
+ });
+ },
+
+ tryAddRelated: function( model, coll, options ) {
+ var item = _.contains( this.keyIds, model.id );
+
+ if ( item ) {
+ this.addRelated( model, options );
+ this.keyIds = _.without( this.keyIds, model.id );
+ }
+ },
+
+ addRelated: function( model, options ) {
+ // Allow 'model' to set up its relations before proceeding.
+ // (which can result in a call to 'addRelated' from a relation of 'model')
+ var dit = this;
+ model.queue( function() {
+ if ( dit.related && !dit.related.get( model ) ) {
+ dit.related.add( model, _.defaults( { parse: false }, options ) );
+ }
+ });
+ },
+
+ removeRelated: function( model, coll, options ) {
+ if ( this.related.get( model ) ) {
+ this.related.remove( model, options );
+ }
+ }
+ });
+
+ /**
+ * A type of Backbone.Model that also maintains relations to other models and collections.
+ * New events when compared to the original:
+ * - 'add:<key>' (model, related collection, options)
+ * - 'remove:<key>' (model, related collection, options)
+ * - 'change:<key>' (model, related model or collection, options)
+ */
+ Backbone.RelationalModel = Backbone.Model.extend({
+ relations: null, // Relation descriptions on the prototype
+ _relations: null, // Relation instances
+ _isInitialized: false,
+ _deferProcessing: false,
+ _queue: null,
+ _attributeChangeFired: false, // Keeps track of `change` event firing under some conditions (like nested `set`s)
+
+ subModelTypeAttribute: 'type',
+ subModelTypes: null,
+
+ constructor: function( attributes, options ) {
+ // Nasty hack, for cases like 'model.get( <HasMany key> ).add( item )'.
+ // Defer 'processQueue', so that when 'Relation.createModels' is used we trigger 'HasMany'
+ // collection events only after the model is really fully set up.
+ // Example: event for "p.on( 'add:jobs' )" -> "p.get('jobs').add( { company: c.id, person: p.id } )".
+ if ( options && options.collection ) {
+ var dit = this,
+ collection = this.collection = options.collection;
+
+ // Prevent `collection` from cascading down to nested models; they shouldn't go into this `if` clause.
+ delete options.collection;
+
+ this._deferProcessing = true;
+
+ var processQueue = function( model ) {
+ if ( model === dit ) {
+ dit._deferProcessing = false;
+ dit.processQueue();
+ collection.off( 'relational:add', processQueue );
+ }
+ };
+ collection.on( 'relational:add', processQueue );
+
+ // So we do process the queue eventually, regardless of whether this model actually gets added to 'options.collection'.
+ _.defer( function() {
+ processQueue( dit );
+ });
+ }
+
+ Backbone.Relational.store.processOrphanRelations();
+ Backbone.Relational.store.listenTo( this, 'relational:unregister', Backbone.Relational.store.unregister );
+
+ this._queue = new Backbone.BlockingQueue();
+ this._queue.block();
+ Backbone.Relational.eventQueue.block();
+
+ try {
+ Backbone.Model.apply( this, arguments );
+ }
+ finally {
+ // Try to run the global queue holding external events
+ Backbone.Relational.eventQueue.unblock();
+ }
+ },
+
+ /**
+ * Override 'trigger' to queue 'change' and 'change:*' events
+ */
+ trigger: function( eventName ) {
+ if ( eventName.length > 5 && eventName.indexOf( 'change' ) === 0 ) {
+ var dit = this,
+ args = arguments;
+
+ if ( !Backbone.Relational.eventQueue.isLocked() ) {
+ // If we're not in a more complicated nested scenario, fire the change event right away
+ Backbone.Model.prototype.trigger.apply( dit, args );
+ }
+ else {
+ Backbone.Relational.eventQueue.add( function() {
+ // Determine if the `change` event is still valid, now that all relations are populated
+ var changed = true;
+ if ( eventName === 'change' ) {
+ // `hasChanged` may have gotten reset by nested calls to `set`.
+ changed = dit.hasChanged() || dit._attributeChangeFired;
+ dit._attributeChangeFired = false;
+ }
+ else {
+ var attr = eventName.slice( 7 ),
+ rel = dit.getRelation( attr );
+
+ if ( rel ) {
+ // If `attr` is a relation, `change:attr` get triggered from `Relation.onChange`.
+ // These take precedence over `change:attr` events triggered by `Model.set`.
+ // The relation sets a fourth attribute to `true`. If this attribute is present,
+ // continue triggering this event; otherwise, it's from `Model.set` and should be stopped.
+ changed = ( args[ 4 ] === true );
+
+ // If this event was triggered by a relation, set the right value in `this.changed`
+ // (a Collection or Model instead of raw data).
+ if ( changed ) {
+ dit.changed[ attr ] = args[ 2 ];
+ }
+ // Otherwise, this event is from `Model.set`. If the relation doesn't report a change,
+ // remove attr from `dit.changed` so `hasChanged` doesn't take it into account.
+ else if ( !rel.changed ) {
+ delete dit.changed[ attr ];
+ }
+ }
+ else if ( changed ) {
+ dit._attributeChangeFired = true;
+ }
+ }
+
+ changed && Backbone.Model.prototype.trigger.apply( dit, args );
+ });
+ }
+ }
+ else if ( eventName === 'destroy' ) {
+ Backbone.Model.prototype.trigger.apply( this, arguments );
+ Backbone.Relational.store.unregister( this );
+ }
+ else {
+ Backbone.Model.prototype.trigger.apply( this, arguments );
+ }
+
+ return this;
+ },
+
+ /**
+ * Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance.
+ * Invoked in the first call so 'set' (which is made from the Backbone.Model constructor).
+ */
+ initializeRelations: function( options ) {
+ this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once
+ this._relations = {};
+
+ _.each( this.relations || [], function( rel ) {
+ Backbone.Relational.store.initializeRelation( this, rel, options );
+ }, this );
+
+ this._isInitialized = true;
+ this.release();
+ this.processQueue();
+ },
+
+ /**
+ * When new values are set, notify this model's relations (also if options.silent is set).
+ * (called from `set`; Relation.setRelated locks this model before calling 'set' on it to prevent loops)
+ * @param {Object} [changedAttrs]
+ * @param {Object} [options]
+ */
+ updateRelations: function( changedAttrs, options ) {
+ if ( this._isInitialized && !this.isLocked() ) {
+ _.each( this._relations, function( rel ) {
+ if ( !changedAttrs || ( rel.keySource in changedAttrs || rel.key in changedAttrs ) ) {
+ // Fetch data in `rel.keySource` if data got set in there, or `rel.key` otherwise
+ var value = this.attributes[ rel.keySource ] || this.attributes[ rel.key ],
+ attr = changedAttrs && ( changedAttrs[ rel.keySource ] || changedAttrs[ rel.key ] );
+
+ // Update a relation if its value differs from this model's attributes, or it's been explicitly nullified.
+ // Which can also happen before the originally intended related model has been found (`val` is null).
+ if ( rel.related !== value || ( value === null && attr === null ) ) {
+ this.trigger( 'relational:change:' + rel.key, this, value, options || {} );
+ }
+ }
+
+ // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
+ if ( rel.keySource !== rel.key ) {
+ delete this.attributes[ rel.keySource ];
+ }
+ }, this );
+ }
+ },
+
+ /**
+ * Either add to the queue (if we're not initialized yet), or execute right away.
+ */
+ queue: function( func ) {
+ this._queue.add( func );
+ },
+
+ /**
+ * Process _queue
+ */
+ processQueue: function() {
+ if ( this._isInitialized && !this._deferProcessing && this._queue.isBlocked() ) {
+ this._queue.unblock();
+ }
+ },
+
+ /**
+ * Get a specific relation.
+ * @param {string} attr The relation key to look for.
+ * @return {Backbone.Relation} An instance of 'Backbone.Relation', if a relation was found for 'attr', or null.
+ */
+ getRelation: function( attr ) {
+ return this._relations[ attr ];
+ },
+
+ /**
+ * Get all of the created relations.
+ * @return {Backbone.Relation[]}
+ */
+ getRelations: function() {
+ return _.values( this._relations );
+ },
+
+
+ /**
+ * Get a list of ids that will be fetched on a call to `getAsync`.
+ * @param {string|Backbone.Relation} attr The relation key to fetch models for.
+ * @param [refresh=false] Add ids for models that are already in the relation, refreshing them?
+ * @return {Array} An array of ids that need to be fetched.
+ */
+ getIdsToFetch: function( attr, refresh ) {
+ var rel = attr instanceof Backbone.Relation ? attr : this.getRelation( attr ),
+ ids = rel ? ( rel.keyIds && rel.keyIds.slice( 0 ) ) || ( ( rel.keyId || rel.keyId === 0 ) ? [ rel.keyId ] : [] ) : [];
+
+ // On `refresh`, add the ids for current models in the relation to `idsToFetch`
+ if ( refresh ) {
+ var models = rel.related && ( rel.related.models || [ rel.related ] );
+ _.each( models, function( model ) {
+ if ( model.id || model.id === 0 ) {
+ ids.push( model.id );
+ }
+ });
+ }
+
+ return ids;
+ },
+
+ /**
+ * Get related objects. Returns a single promise, which can either resolve immediately (if the related model[s])
+ * are already present locally, or after fetching the contents of the requested attribute.
+ * @param {string} attr The relation key to fetch models for.
+ * @param {Object} [options] Options for 'Backbone.Model.fetch' and 'Backbone.sync'.
+ * @param {Boolean} [options.refresh=false] Fetch existing models from the server as well (in order to update them).
+ * @return {jQuery.Deferred} A jQuery promise object. When resolved, its `done` callback will be called with
+ * contents of `attr`.
+ */
+ getAsync: function( attr, options ) {
+ // Set default `options` for fetch
+ options = _.extend( { add: true, remove: false, refresh: false }, options );
+
+ var dit = this,
+ requests = [],
+ rel = this.getRelation( attr ),
+ idsToFetch = rel && this.getIdsToFetch( rel, options.refresh ),
+ coll = rel.related instanceof Backbone.Collection ? rel.related : rel.relatedCollection;
+
+ if ( idsToFetch && idsToFetch.length ) {
+ var models = [],
+ createdModels = [],
+ setUrl,
+ createModels = function() {
+ // Find (or create) a model for each one that is to be fetched
+ models = _.map( idsToFetch, function( id ) {
+ var model = rel.relatedModel.findModel( id );
+
+ if ( !model ) {
+ var attrs = {};
+ attrs[ rel.relatedModel.prototype.idAttribute ] = id;
+ model = rel.relatedModel.findOrCreate( attrs, options );
+ createdModels.push( model );
+ }
+
+ return model;
+ }, this );
+ };
+
+ // Try if the 'collection' can provide a url to fetch a set of models in one request.
+ // This assumes that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
+ // To make sure it can, test if the url we got by supplying a list of models to fetch is different from
+ // the one supplied for the default fetch action (without args to 'url').
+ if ( coll instanceof Backbone.Collection && _.isFunction( coll.url ) ) {
+ var defaultUrl = coll.url();
+ setUrl = coll.url( idsToFetch );
+
+ if ( setUrl === defaultUrl ) {
+ createModels();
+ setUrl = coll.url( models );
+
+ if ( setUrl === defaultUrl ) {
+ setUrl = null;
+ }
+ }
+ }
+
+ if ( setUrl ) {
+ // Do a single request to fetch all models
+ var opts = _.defaults(
+ {
+ error: function() {
+ _.each( createdModels, function( model ) {
+ model.trigger( 'destroy', model, model.collection, options );
+ });
+
+ options.error && options.error.apply( models, arguments );
+ },
+ url: setUrl
+ },
+ options
+ );
+
+ requests = [ coll.fetch( opts ) ];
+ }
+ else {
+ // Make a request per model to fetch
+ if ( !models.length ) {
+ createModels();
+ }
+
+ requests = _.map( models, function( model ) {
+ var opts = _.defaults(
+ {
+ error: function() {
+ if ( _.contains( createdModels, model ) ) {
+ model.trigger( 'destroy', model, model.collection, options );
+ }
+ options.error && options.error.apply( models, arguments );
+ }
+ },
+ options
+ );
+ return model.fetch( opts );
+ }, this );
+ }
+ }
+
+ return $.when.apply( null, requests ).then(
+ function() {
+ return Backbone.Model.prototype.get.call( dit, attr );
+ }
+ );
+ },
+
+ set: function( key, value, options ) {
+ Backbone.Relational.eventQueue.block();
+
+ // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object
+ var attributes,
+ result;
+
+ if ( _.isObject( key ) || key == null ) {
+ attributes = key;
+ options = value;
+ }
+ else {
+ attributes = {};
+ attributes[ key ] = value;
+ }
+
+ try {
+ var id = this.id,
+ newId = attributes && this.idAttribute in attributes && attributes[ this.idAttribute ];
+
+ // Check if we're not setting a duplicate id before actually calling `set`.
+ Backbone.Relational.store.checkId( this, newId );
+
+ result = Backbone.Model.prototype.set.apply( this, arguments );
+
+ // Ideal place to set up relations, if this is the first time we're here for this model
+ if ( !this._isInitialized && !this.isLocked() ) {
+ this.constructor.initializeModelHierarchy();
+
+ // Only register models that have an id. A model will be registered when/if it gets an id later on.
+ if ( newId || newId === 0 ) {
+ Backbone.Relational.store.register( this );
+ }
+
+ this.initializeRelations( options );
+ }
+ // The store should know about an `id` update asap
+ else if ( newId && newId !== id ) {
+ Backbone.Relational.store.update( this );
+ }
+
+ if ( attributes ) {
+ this.updateRelations( attributes, options );
+ }
+ }
+ finally {
+ // Try to run the global queue holding external events
+ Backbone.Relational.eventQueue.unblock();
+ }
+
+ return result;
+ },
+
+ clone: function() {
+ var attributes = _.clone( this.attributes );
+ if ( !_.isUndefined( attributes[ this.idAttribute ] ) ) {
+ attributes[ this.idAttribute ] = null;
+ }
+
+ _.each( this.getRelations(), function( rel ) {
+ delete attributes[ rel.key ];
+ });
+
+ return new this.constructor( attributes );
+ },
+
+ /**
+ * Convert relations to JSON, omits them when required
+ */
+ toJSON: function( options ) {
+ // If this Model has already been fully serialized in this branch once, return to avoid loops
+ if ( this.isLocked() ) {
+ return this.id;
+ }
+
+ this.acquire();
+ var json = Backbone.Model.prototype.toJSON.call( this, options );
+
+ if ( this.constructor._superModel && !( this.constructor._subModelTypeAttribute in json ) ) {
+ json[ this.constructor._subModelTypeAttribute ] = this.constructor._subModelTypeValue;
+ }
+
+ _.each( this._relations, function( rel ) {
+ var related = json[ rel.key ],
+ includeInJSON = rel.options.includeInJSON,
+ value = null;
+
+ if ( includeInJSON === true ) {
+ if ( related && _.isFunction( related.toJSON ) ) {
+ value = related.toJSON( options );
+ }
+ }
+ else if ( _.isString( includeInJSON ) ) {
+ if ( related instanceof Backbone.Collection ) {
+ value = related.pluck( includeInJSON );
+ }
+ else if ( related instanceof Backbone.Model ) {
+ value = related.get( includeInJSON );
+ }
+
+ // Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute`
+ if ( includeInJSON === rel.relatedModel.prototype.idAttribute ) {
+ if ( rel instanceof Backbone.HasMany ) {
+ value = value.concat( rel.keyIds );
+ }
+ else if ( rel instanceof Backbone.HasOne ) {
+ value = value || rel.keyId;
+
+ if ( !value && !_.isObject( rel.keyContents ) ) {
+ value = rel.keyContents || null;
+ }
+ }
+ }
+ }
+ else if ( _.isArray( includeInJSON ) ) {
+ if ( related instanceof Backbone.Collection ) {
+ value = [];
+ related.each( function( model ) {
+ var curJson = {};
+ _.each( includeInJSON, function( key ) {
+ curJson[ key ] = model.get( key );
+ });
+ value.push( curJson );
+ });
+ }
+ else if ( related instanceof Backbone.Model ) {
+ value = {};
+ _.each( includeInJSON, function( key ) {
+ value[ key ] = related.get( key );
+ });
+ }
+ }
+ else {
+ delete json[ rel.key ];
+ }
+
+ // In case of `wait: true`, Backbone will simply push whatever's passed into `save` into attributes.
+ // We'll want to get this information into the JSON, even if it doesn't conform to our normal
+ // expectations of what's contained in it (no model/collection for a relation, etc).
+ if ( value === null && options && options.wait ) {
+ value = related;
+ }
+
+ if ( includeInJSON ) {
+ json[ rel.keyDestination ] = value;
+ }
+
+ if ( rel.keyDestination !== rel.key ) {
+ delete json[ rel.key ];
+ }
+ });
+
+ this.release();
+ return json;
+ }
+ },
+ {
+ /**
+ *
+ * @param superModel
+ * @returns {Backbone.RelationalModel.constructor}
+ */
+ setup: function( superModel ) {
+ // We don't want to share a relations array with a parent, as this will cause problems with reverse
+ // relations. Since `relations` may also be a property or function, only use slice if we have an array.
+ this.prototype.relations = ( this.prototype.relations || [] ).slice( 0 );
+
+ this._subModels = {};
+ this._superModel = null;
+
+ // If this model has 'subModelTypes' itself, remember them in the store
+ if ( this.prototype.hasOwnProperty( 'subModelTypes' ) ) {
+ Backbone.Relational.store.addSubModels( this.prototype.subModelTypes, this );
+ }
+ // The 'subModelTypes' property should not be inherited, so reset it.
+ else {
+ this.prototype.subModelTypes = null;
+ }
+
+ // Initialize all reverseRelations that belong to this new model.
+ _.each( this.prototype.relations || [], function( rel ) {
+ if ( !rel.model ) {
+ rel.model = this;
+ }
+
+ if ( rel.reverseRelation && rel.model === this ) {
+ var preInitialize = true;
+ if ( _.isString( rel.relatedModel ) ) {
+ /**
+ * The related model might not be defined for two reasons
+ * 1. it is related to itself
+ * 2. it never gets defined, e.g. a typo
+ * 3. the model hasn't been defined yet, but will be later
+ * In neither of these cases do we need to pre-initialize reverse relations.
+ * However, for 3. (which is, to us, indistinguishable from 2.), we do need to attempt
+ * setting up this relation again later, in case the related model is defined later.
+ */
+ var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel );
+ preInitialize = relatedModel && ( relatedModel.prototype instanceof Backbone.RelationalModel );
+ }
+
+ if ( preInitialize ) {
+ Backbone.Relational.store.initializeRelation( null, rel );
+ }
+ else if ( _.isString( rel.relatedModel ) ) {
+ Backbone.Relational.store.addOrphanRelation( rel );
+ }
+ }
+ }, this );
+
+ return this;
+ },
+
+ /**
+ * Create a 'Backbone.Model' instance based on 'attributes'.
+ * @param {Object} attributes
+ * @param {Object} [options]
+ * @return {Backbone.Model}
+ */
+ build: function( attributes, options ) {
+ // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet.
+ this.initializeModelHierarchy();
+
+ // Determine what type of (sub)model should be built if applicable.
+ var model = this._findSubModelType( this, attributes ) || this;
+
+ return new model( attributes, options );
+ },
+
+ /**
+ * Determines what type of (sub)model should be built if applicable.
+ * Looks up the proper subModelType in 'this._subModels', recursing into
+ * types until a match is found. Returns the applicable 'Backbone.Model'
+ * or null if no match is found.
+ * @param {Backbone.Model} type
+ * @param {Object} attributes
+ * @return {Backbone.Model}
+ */
+ _findSubModelType: function( type, attributes ) {
+ if ( type._subModels && type.prototype.subModelTypeAttribute in attributes ) {
+ var subModelTypeAttribute = attributes[ type.prototype.subModelTypeAttribute ];
+ var subModelType = type._subModels[ subModelTypeAttribute ];
+ if ( subModelType ) {
+ return subModelType;
+ }
+ else {
+ // Recurse into subModelTypes to find a match
+ for ( subModelTypeAttribute in type._subModels ) {
+ subModelType = this._findSubModelType( type._subModels[ subModelTypeAttribute ], attributes );
+ if ( subModelType ) {
+ return subModelType;
+ }
+ }
+ }
+ }
+
+ return null;
+ },
+
+ /**
+ *
+ */
+ initializeModelHierarchy: function() {
+ // Inherit any relations that have been defined in the parent model.
+ this.inheritRelations();
+
+ // If we came here through 'build' for a model that has 'subModelTypes' then try to initialize the ones that
+ // haven't been resolved yet.
+ if ( this.prototype.subModelTypes ) {
+ var resolvedSubModels = _.keys( this._subModels );
+ var unresolvedSubModels = _.omit( this.prototype.subModelTypes, resolvedSubModels );
+ _.each( unresolvedSubModels, function( subModelTypeName ) {
+ var subModelType = Backbone.Relational.store.getObjectByName( subModelTypeName );
+ subModelType && subModelType.initializeModelHierarchy();
+ });
+ }
+ },
+
+ inheritRelations: function() {
+ // Bail out if we've been here before.
+ if ( !_.isUndefined( this._superModel ) && !_.isNull( this._superModel ) ) {
+ return;
+ }
+ // Try to initialize the _superModel.
+ Backbone.Relational.store.setupSuperModel( this );
+
+ // If a superModel has been found, copy relations from the _superModel if they haven't been inherited automatically
+ // (due to a redefinition of 'relations').
+ if ( this._superModel ) {
+ // The _superModel needs a chance to initialize its own inherited relations before we attempt to inherit relations
+ // from the _superModel. You don't want to call 'initializeModelHierarchy' because that could cause sub-models of
+ // this class to inherit their relations before this class has had chance to inherit it's relations.
+ this._superModel.inheritRelations();
+ if ( this._superModel.prototype.relations ) {
+ // Find relations that exist on the '_superModel', but not yet on this model.
+ var inheritedRelations = _.filter( this._superModel.prototype.relations || [], function( superRel ) {
+ return !_.any( this.prototype.relations || [], function( rel ) {
+ return superRel.relatedModel === rel.relatedModel && superRel.key === rel.key;
+ }, this );
+ }, this );
+
+ this.prototype.relations = inheritedRelations.concat( this.prototype.relations );
+ }
+ }
+ // Otherwise, make sure we don't get here again for this type by making '_superModel' false so we fail the
+ // isUndefined/isNull check next time.
+ else {
+ this._superModel = false;
+ }
+ },
+
+ /**
+ * Find an instance of `this` type in 'Backbone.Relational.store'.
+ * A new model is created if no matching model is found, `attributes` is an object, and `options.create` is true.
+ * - If `attributes` is a string or a number, `findOrCreate` will query the `store` and return a model if found.
+ * - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.merge` is `false`.
+ * @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model.
+ * @param {Object} [options]
+ * @param {Boolean} [options.create=true]
+ * @param {Boolean} [options.merge=true]
+ * @param {Boolean} [options.parse=false]
+ * @return {Backbone.RelationalModel}
+ */
+ findOrCreate: function( attributes, options ) {
+ options || ( options = {} );
+ var parsedAttributes = ( _.isObject( attributes ) && options.parse && this.prototype.parse ) ?
+ this.prototype.parse( _.clone( attributes ) ) : attributes;
+
+ // If specified, use a custom `find` function to match up existing models to the given attributes.
+ // Otherwise, try to find an instance of 'this' model type in the store
+ var model = this.findModel( parsedAttributes );
+
+ // If we found an instance, update it with the data in 'item' (unless 'options.merge' is false).
+ // If not, create an instance (unless 'options.create' is false).
+ if ( _.isObject( attributes ) ) {
+ if ( model && options.merge !== false ) {
+ // Make sure `options.collection` and `options.url` doesn't cascade to nested models
+ delete options.collection;
+ delete options.url;
+
+ model.set( parsedAttributes, options );
+ }
+ else if ( !model && options.create !== false ) {
+ model = this.build( parsedAttributes, _.defaults( { parse: false }, options ) );
+ }
+ }
+
+ return model;
+ },
+
+ /**
+ * Find an instance of `this` type in 'Backbone.Relational.store'.
+ * - If `attributes` is a string or a number, `find` will query the `store` and return a model if found.
+ * - If `attributes` is an object and is found in the store, the model will be updated with `attributes` unless `options.merge` is `false`.
+ * @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model.
+ * @param {Object} [options]
+ * @param {Boolean} [options.merge=true]
+ * @param {Boolean} [options.parse=false]
+ * @return {Backbone.RelationalModel}
+ */
+ find: function( attributes, options ) {
+ options || ( options = {} );
+ options.create = false;
+ return this.findOrCreate( attributes, options );
+ },
+
+ /**
+ * A hook to override the matching when updating (or creating) a model.
+ * The default implementation is to look up the model by id in the store.
+ * @param {Object} attributes
+ * @returns {Backbone.RelationalModel}
+ */
+ findModel: function( attributes ) {
+ return Backbone.Relational.store.find( this, attributes );
+ }
+ });
+ _.extend( Backbone.RelationalModel.prototype, Backbone.Semaphore );
+
+ /**
+ * Override Backbone.Collection._prepareModel, so objects will be built using the correct type
+ * if the collection.model has subModels.
+ * Attempts to find a model for `attrs` in Backbone.store through `findOrCreate`
+ * (which sets the new properties on it if found), or instantiates a new model.
+ */
+ Backbone.Collection.prototype.__prepareModel = Backbone.Collection.prototype._prepareModel;
+ Backbone.Collection.prototype._prepareModel = function( attrs, options ) {
+ var model;
+
+ if ( attrs instanceof Backbone.Model ) {
+ if ( !attrs.collection ) {
+ attrs.collection = this;
+ }
+ model = attrs;
+ }
+ else {
+ options = options ? _.clone( options ) : {};
+ options.collection = this;
+
+ if ( typeof this.model.findOrCreate !== 'undefined' ) {
+ model = this.model.findOrCreate( attrs, options );
+ }
+ else {
+ model = new this.model( attrs, options );
+ }
+
+ if ( model && model.validationError ) {
+ this.trigger( 'invalid', this, attrs, options );
+ model = false;
+ }
+ }
+
+ return model;
+ };
+
+
+ /**
+ * Override Backbone.Collection.set, so we'll create objects from attributes where required,
+ * and update the existing models. Also, trigger 'relational:add'.
+ */
+ var set = Backbone.Collection.prototype.__set = Backbone.Collection.prototype.set;
+ Backbone.Collection.prototype.set = function( models, options ) {
+ // Short-circuit if this Collection doesn't hold RelationalModels
+ if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) {
+ return set.call( this, models, options );
+ }
+
+ if ( options && options.parse ) {
+ models = this.parse( models, options );
+ }
+
+ var singular = !_.isArray( models ),
+ newModels = [],
+ toAdd = [],
+ model = null;
+
+ models = singular ? ( models ? [ models ] : [] ) : _.clone( models );
+
+ //console.debug( 'calling add on coll=%o; model=%o, options=%o', this, models, options );
+ for ( var i = 0; i < models.length; i++ ) {
+ model = models[i];
+ if ( !( model instanceof Backbone.Model ) ) {
+ model = Backbone.Collection.prototype._prepareModel.call( this, model, options );
+ }
+ if ( model ) {
+ toAdd.push( model );
+ if ( !( this.get( model ) || this.get( model.cid ) ) ) {
+ newModels.push( model );
+ }
+ // If we arrive in `add` while performing a `set` (after a create, so the model gains an `id`),
+ // we may get here before `_onModelEvent` has had the chance to update `_byId`.
+ else if ( model.id !== null && model.id !== undefined ) {
+ this._byId[ model.id ] = model;
+ }
+ }
+ }
+
+ // Add 'models' in a single batch, so the original add will only be called once (and thus 'sort', etc).
+ // If `parse` was specified, the collection and contained models have been parsed now.
+ toAdd = singular ? ( toAdd.length ? toAdd[ 0 ] : null ) : toAdd;
+ var result = set.call( this, toAdd, _.defaults( { merge: false, parse: false }, options ) );
+
+ for ( i = 0; i < newModels.length; i++ ) {
+ model = newModels[i];
+ // Fire a `relational:add` event for any model in `newModels` that has actually been added to the collection.
+ if ( this.get( model ) || this.get( model.cid ) ) {
+ this.trigger( 'relational:add', model, this, options );
+ }
+ }
+
+ return result;
+ };
+
+ /**
+ * Override 'Backbone.Collection.remove' to trigger 'relational:remove'.
+ */
+ var remove = Backbone.Collection.prototype.__remove = Backbone.Collection.prototype.remove;
+ Backbone.Collection.prototype.remove = function( models, options ) {
+ // Short-circuit if this Collection doesn't hold RelationalModels
+ if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) {
+ return remove.call( this, models, options );
+ }
+
+ var singular = !_.isArray( models ),
+ toRemove = [];
+
+ models = singular ? ( models ? [ models ] : [] ) : _.clone( models );
+ options || ( options = {} );
+
+ //console.debug('calling remove on coll=%o; models=%o, options=%o', this, models, options );
+ _.each( models, function( model ) {
+ model = this.get( model ) || ( model && this.get( model.cid ) );
+ model && toRemove.push( model );
+ }, this );
+
+ var result = remove.call( this, singular ? ( toRemove.length ? toRemove[ 0 ] : null ) : toRemove, options );
+
+ _.each( toRemove, function( model ) {
+ this.trigger( 'relational:remove', model, this, options );
+ }, this );
+
+ return result;
+ };
+
+ /**
+ * Override 'Backbone.Collection.reset' to trigger 'relational:reset'.
+ */
+ var reset = Backbone.Collection.prototype.__reset = Backbone.Collection.prototype.reset;
+ Backbone.Collection.prototype.reset = function( models, options ) {
+ options = _.extend( { merge: true }, options );
+ var result = reset.call( this, models, options );
+
+ if ( this.model.prototype instanceof Backbone.RelationalModel ) {
+ this.trigger( 'relational:reset', this, options );
+ }
+
+ return result;
+ };
+
+ /**
+ * Override 'Backbone.Collection.sort' to trigger 'relational:reset'.
+ */
+ var sort = Backbone.Collection.prototype.__sort = Backbone.Collection.prototype.sort;
+ Backbone.Collection.prototype.sort = function( options ) {
+ var result = sort.call( this, options );
+
+ if ( this.model.prototype instanceof Backbone.RelationalModel ) {
+ this.trigger( 'relational:reset', this, options );
+ }
+
+ return result;
+ };
+
+ /**
+ * Override 'Backbone.Collection.trigger' so 'add', 'remove' and 'reset' events are queued until relations
+ * are ready.
+ */
+ var trigger = Backbone.Collection.prototype.__trigger = Backbone.Collection.prototype.trigger;
+ Backbone.Collection.prototype.trigger = function( eventName ) {
+ // Short-circuit if this Collection doesn't hold RelationalModels
+ if ( !( this.model.prototype instanceof Backbone.RelationalModel ) ) {
+ return trigger.apply( this, arguments );
+ }
+
+ if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' || eventName === 'sort' ) {
+ var dit = this,
+ args = arguments;
+
+ if ( _.isObject( args[ 3 ] ) ) {
+ args = _.toArray( args );
+ // the fourth argument is the option object.
+ // we need to clone it, as it could be modified while we wait on the eventQueue to be unblocked
+ args[ 3 ] = _.clone( args[ 3 ] );
+ }
+
+ Backbone.Relational.eventQueue.add( function() {
+ trigger.apply( dit, args );
+ });
+ }
+ else {
+ trigger.apply( this, arguments );
+ }
+
+ return this;
+ };
+
+ // Override .extend() to automatically call .setup()
+ Backbone.RelationalModel.extend = function( protoProps, classProps ) {
+ var child = Backbone.Model.extend.call( this, protoProps, classProps );
+
+ child.setup( this );
+
+ return child;
+ };
+}));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/backbone/backbone.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,1608 @@
+// Backbone.js 1.1.2
+
+// (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+// Backbone may be freely distributed under the MIT license.
+// For all details and documentation:
+// http://backbonejs.org
+
+(function(root, factory) {
+
+ // Set up Backbone appropriately for the environment. Start with AMD.
+ if (typeof define === 'function' && define.amd) {
+ define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
+ // Export global even in AMD case in case this script is loaded with
+ // others that may still expect a global Backbone.
+ root.Backbone = factory(root, exports, _, $);
+ });
+
+ // Next for Node.js or CommonJS. jQuery may not be needed as a module.
+ } else if (typeof exports !== 'undefined') {
+ var _ = require('underscore');
+ factory(root, exports, _);
+
+ // Finally, as a browser global.
+ } else {
+ root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
+ }
+
+}(this, function(root, Backbone, _, $) {
+
+ // Initial Setup
+ // -------------
+
+ // 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;
+
+ // Current version of the library. Keep in sync with `package.json`.
+ Backbone.VERSION = '1.1.2';
+
+ // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
+ // the `$` variable.
+ Backbone.$ = $;
+
+ // 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 `"PATCH"`, `"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 = void 0;
+ 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 listeningTo = this._listeningTo;
+ if (!listeningTo) return this;
+ var remove = !name && !callback;
+ if (!callback && typeof name === 'object') callback = this;
+ if (obj) (listeningTo = {})[obj._listenId] = obj;
+ for (var id in listeningTo) {
+ obj = listeningTo[id];
+ obj.off(name, callback, this);
+ if (remove || _.isEmpty(obj._events)) delete this._listeningTo[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); return;
+ }
+ };
+
+ 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 listeningTo = this._listeningTo || (this._listeningTo = {});
+ var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
+ listeningTo[id] = obj;
+ if (!callback && 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 attrs = attributes || {};
+ options || (options = {});
+ this.cid = _.uniqueId('c');
+ this.attributes = {};
+ if (options.collection) this.collection = options.collection;
+ if (options.parse) attrs = this.parse(attrs, options) || {};
+ attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
+ this.set(attrs, options);
+ this.changed = {};
+ this.initialize.apply(this, arguments);
+ };
+
+ // 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 = options;
+ 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) {
+ options = 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;
+ }
+
+ options = _.extend({validate: true}, options);
+
+ // If we're not waiting and attributes exist, save acts as
+ // `set(attr).save(null, opts)` with validation. Otherwise, check if
+ // the model will be valid when the attributes, if any, are set.
+ if (attrs && !options.wait) {
+ if (!this.set(attrs, options)) return false;
+ } else {
+ 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.replace(/([^\/])$/, '$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.has(this.idAttribute);
+ },
+
+ // 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.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, 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, _.extend({merge: false}, options, addOptions));
+ },
+
+ // Remove a model, or a list of models from the set.
+ remove: function(models, options) {
+ var singular = !_.isArray(models);
+ models = singular ? [models] : _.clone(models);
+ options || (options = {});
+ var i, l, index, model;
+ for (i = 0, l = models.length; i < l; i++) {
+ model = models[i] = 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, options);
+ }
+ return singular ? models[0] : models;
+ },
+
+ // 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);
+ var singular = !_.isArray(models);
+ models = singular ? (models ? [models] : []) : _.clone(models);
+ var i, l, id, model, attrs, existing, sort;
+ var at = options.at;
+ var targetModel = this.model;
+ var sortable = this.comparator && (at == null) && options.sort !== false;
+ var sortAttr = _.isString(this.comparator) ? this.comparator : null;
+ var toAdd = [], toRemove = [], modelMap = {};
+ var add = options.add, merge = options.merge, remove = options.remove;
+ var order = !sortable && add && remove ? [] : false;
+
+ // Turn bare objects into model references, and prevent invalid models
+ // from being added.
+ for (i = 0, l = models.length; i < l; i++) {
+ attrs = models[i] || {};
+ if (attrs instanceof Model) {
+ id = model = attrs;
+ } else {
+ id = attrs[targetModel.prototype.idAttribute || 'id'];
+ }
+
+ // If a duplicate is found, prevent it from being added and
+ // optionally merge it into the existing model.
+ if (existing = this.get(id)) {
+ if (remove) modelMap[existing.cid] = true;
+ if (merge) {
+ attrs = attrs === model ? model.attributes : attrs;
+ if (options.parse) attrs = existing.parse(attrs, options);
+ existing.set(attrs, options);
+ if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
+ }
+ models[i] = existing;
+
+ // If this is a new, valid model, push it to the `toAdd` list.
+ } else if (add) {
+ model = models[i] = this._prepareModel(attrs, options);
+ if (!model) continue;
+ toAdd.push(model);
+ this._addReference(model, options);
+ }
+
+ // Do not add multiple models with the same `id`.
+ model = existing || model;
+ if (order && (model.isNew() || !modelMap[model.id])) order.push(model);
+ modelMap[model.id] = true;
+ }
+
+ // Remove nonexistent models if appropriate.
+ if (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 || (order && order.length)) {
+ if (sortable) sort = true;
+ this.length += toAdd.length;
+ if (at != null) {
+ for (i = 0, l = toAdd.length; i < l; i++) {
+ this.models.splice(at + i, 0, toAdd[i]);
+ }
+ } else {
+ if (order) this.models.length = 0;
+ var orderedModels = order || toAdd;
+ for (i = 0, l = orderedModels.length; i < l; i++) {
+ this.models.push(orderedModels[i]);
+ }
+ }
+ }
+
+ // Silently sort the collection if appropriate.
+ if (sort) this.sort({silent: true});
+
+ // Unless silenced, it's time to fire all appropriate add/sort events.
+ if (!options.silent) {
+ for (i = 0, l = toAdd.length; i < l; i++) {
+ (model = toAdd[i]).trigger('add', model, this, options);
+ }
+ if (sort || (order && order.length)) this.trigger('sort', this, options);
+ }
+
+ // Return the added (or merged) model (or models).
+ return singular ? models[0] : models;
+ },
+
+ // 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);
+ }
+ options.previousModels = this.models;
+ this._reset();
+ models = this.add(models, _.extend({silent: true}, options));
+ if (!options.silent) this.trigger('reset', this, options);
+ return models;
+ },
+
+ // Add a model to the end of the collection.
+ push: function(model, options) {
+ return this.add(model, _.extend({at: this.length}, options));
+ },
+
+ // 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) {
+ return this.add(model, _.extend({at: 0}, options));
+ },
+
+ // 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() {
+ return slice.apply(this.models, arguments);
+ },
+
+ // Get a model from the set by id.
+ get: function(obj) {
+ if (obj == null) return void 0;
+ return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid];
+ },
+
+ // 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;
+ },
+
+ // 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(model, 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) return attrs;
+ options = options ? _.clone(options) : {};
+ options.collection = this;
+ var model = new this.model(attrs, options);
+ if (!model.validationError) return model;
+ this.trigger('invalid', this, model.validationError, options);
+ return false;
+ },
+
+ // Internal method to create a model's ties to a collection.
+ _addReference: function(model, options) {
+ this._byId[model.cid] = model;
+ if (model.id != null) this._byId[model.id] = model;
+ if (!model.collection) model.collection = this;
+ model.on('all', this._onModelEvent, this);
+ },
+
+ // Internal method to sever a model's ties to a collection.
+ _removeReference: function(model, options) {
+ 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', 'difference', 'indexOf', 'shuffle',
+ 'lastIndexOf', 'isEmpty', 'chain', 'sample'];
+
+ // 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', 'indexBy'];
+
+ // 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');
+ options || (options = {});
+ _.extend(this, _.pick(options, viewOptions));
+ 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 preferred 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;
+ },
+
+ // 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' && noXhrPatch) {
+ 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;
+ };
+
+ var noXhrPatch =
+ typeof window !== 'undefined' && !!window.ActiveXObject &&
+ !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
+
+ // 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);
+ router.execute(callback, args);
+ router.trigger.apply(router, ['route:' + name].concat(args));
+ router.trigger('route', name, args);
+ Backbone.history.trigger('route', router, name, args);
+ });
+ return this;
+ },
+
+ // Execute a route handler with the provided parameters. This is an
+ // excellent place to do pre-route setup or post-route cleanup.
+ execute: function(callback, args) {
+ if (callback) callback.apply(this, args);
+ },
+
+ // 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 + '(?:\\?([\\s\\S]*))?$');
+ },
+
+ // 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, i) {
+ // Don't decode the search params.
+ if (i === params.length - 1) return param || null;
+ 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 = /\/$/;
+
+ // Cached regex for stripping urls of hash.
+ var pathStripper = /#.*$/;
+
+ // 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,
+
+ // Are we at the app root?
+ atRoot: function() {
+ return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root;
+ },
+
+ // 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 = decodeURI(this.location.pathname + this.location.search);
+ var root = this.root.replace(trailingSlash, '');
+ if (!fragment.indexOf(root)) fragment = fragment.slice(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) {
+ var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">');
+ this.iframe = frame.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;
+
+ // Transition from hashChange to pushState or vice versa if both are
+ // requested.
+ if (this._wantsHashChange && this._wantsPushState) {
+
+ // 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._hasPushState && !this.atRoot()) {
+ this.fragment = this.getFragment(null, true);
+ this.location.replace(this.root + '#' + 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._hasPushState && this.atRoot() && loc.hash) {
+ this.fragment = this.getHash().replace(routeStripper, '');
+ this.history.replaceState({}, document.title, this.root + this.fragment);
+ }
+
+ }
+
+ 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);
+ if (this._checkUrlInterval) 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();
+ },
+
+ // 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(fragment) {
+ fragment = this.fragment = this.getFragment(fragment);
+ return _.any(this.handlers, function(handler) {
+ if (handler.route.test(fragment)) {
+ handler.callback(fragment);
+ return true;
+ }
+ });
+ },
+
+ // 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};
+
+ var url = this.root + (fragment = this.getFragment(fragment || ''));
+
+ // Strip the hash for matching.
+ fragment = fragment.replace(pathStripper, '');
+
+ if (this.fragment === fragment) return;
+ this.fragment = fragment;
+
+ // Don't include a trailing slash on the root.
+ if (fragment === '' && url !== '/') url = url.slice(0, -1);
+
+ // 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) return 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);
+ };
+ };
+
+ return Backbone;
+
+}));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/jquery-mousewheel/jquery.mousewheel.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,221 @@
+/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
+ * Licensed under the MIT License (LICENSE.txt).
+ *
+ * Version: 3.1.12
+ *
+ * Requires: jQuery 1.2.2+
+ */
+
+(function (factory) {
+ if ( typeof define === 'function' && define.amd ) {
+ // AMD. Register as an anonymous module.
+ define(['jquery'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS style for Browserify
+ module.exports = factory;
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
+}(function ($) {
+
+ var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
+ toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
+ ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
+ slice = Array.prototype.slice,
+ nullLowestDeltaTimeout, lowestDelta;
+
+ if ( $.event.fixHooks ) {
+ for ( var i = toFix.length; i; ) {
+ $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
+ }
+ }
+
+ var special = $.event.special.mousewheel = {
+ version: '3.1.12',
+
+ setup: function() {
+ if ( this.addEventListener ) {
+ for ( var i = toBind.length; i; ) {
+ this.addEventListener( toBind[--i], handler, false );
+ }
+ } else {
+ this.onmousewheel = handler;
+ }
+ // Store the line height and page height for this particular element
+ $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
+ $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
+ },
+
+ teardown: function() {
+ if ( this.removeEventListener ) {
+ for ( var i = toBind.length; i; ) {
+ this.removeEventListener( toBind[--i], handler, false );
+ }
+ } else {
+ this.onmousewheel = null;
+ }
+ // Clean up the data we added to the element
+ $.removeData(this, 'mousewheel-line-height');
+ $.removeData(this, 'mousewheel-page-height');
+ },
+
+ getLineHeight: function(elem) {
+ var $elem = $(elem),
+ $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
+ if (!$parent.length) {
+ $parent = $('body');
+ }
+ return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
+ },
+
+ getPageHeight: function(elem) {
+ return $(elem).height();
+ },
+
+ settings: {
+ adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
+ normalizeOffset: true // calls getBoundingClientRect for each event
+ }
+ };
+
+ $.fn.extend({
+ mousewheel: function(fn) {
+ return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
+ },
+
+ unmousewheel: function(fn) {
+ return this.unbind('mousewheel', fn);
+ }
+ });
+
+
+ function handler(event) {
+ var orgEvent = event || window.event,
+ args = slice.call(arguments, 1),
+ delta = 0,
+ deltaX = 0,
+ deltaY = 0,
+ absDelta = 0,
+ offsetX = 0,
+ offsetY = 0;
+ event = $.event.fix(orgEvent);
+ event.type = 'mousewheel';
+
+ // Old school scrollwheel delta
+ if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; }
+ if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; }
+ if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; }
+ if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }
+
+ // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
+ if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
+ deltaX = deltaY * -1;
+ deltaY = 0;
+ }
+
+ // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
+ delta = deltaY === 0 ? deltaX : deltaY;
+
+ // New school wheel delta (wheel event)
+ if ( 'deltaY' in orgEvent ) {
+ deltaY = orgEvent.deltaY * -1;
+ delta = deltaY;
+ }
+ if ( 'deltaX' in orgEvent ) {
+ deltaX = orgEvent.deltaX;
+ if ( deltaY === 0 ) { delta = deltaX * -1; }
+ }
+
+ // No change actually happened, no reason to go any further
+ if ( deltaY === 0 && deltaX === 0 ) { return; }
+
+ // Need to convert lines and pages to pixels if we aren't already in pixels
+ // There are three delta modes:
+ // * deltaMode 0 is by pixels, nothing to do
+ // * deltaMode 1 is by lines
+ // * deltaMode 2 is by pages
+ if ( orgEvent.deltaMode === 1 ) {
+ var lineHeight = $.data(this, 'mousewheel-line-height');
+ delta *= lineHeight;
+ deltaY *= lineHeight;
+ deltaX *= lineHeight;
+ } else if ( orgEvent.deltaMode === 2 ) {
+ var pageHeight = $.data(this, 'mousewheel-page-height');
+ delta *= pageHeight;
+ deltaY *= pageHeight;
+ deltaX *= pageHeight;
+ }
+
+ // Store lowest absolute delta to normalize the delta values
+ absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
+
+ if ( !lowestDelta || absDelta < lowestDelta ) {
+ lowestDelta = absDelta;
+
+ // Adjust older deltas if necessary
+ if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
+ lowestDelta /= 40;
+ }
+ }
+
+ // Adjust older deltas if necessary
+ if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
+ // Divide all the things by 40!
+ delta /= 40;
+ deltaX /= 40;
+ deltaY /= 40;
+ }
+
+ // Get a whole, normalized value for the deltas
+ delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta);
+ deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
+ deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);
+
+ // Normalise offsetX and offsetY properties
+ if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
+ var boundingRect = this.getBoundingClientRect();
+ offsetX = event.clientX - boundingRect.left;
+ offsetY = event.clientY - boundingRect.top;
+ }
+
+ // Add information to the event object
+ event.deltaX = deltaX;
+ event.deltaY = deltaY;
+ event.deltaFactor = lowestDelta;
+ event.offsetX = offsetX;
+ event.offsetY = offsetY;
+ // Go ahead and set deltaMode to 0 since we converted to pixels
+ // Although this is a little odd since we overwrite the deltaX/Y
+ // properties with normalized deltas.
+ event.deltaMode = 0;
+
+ // Add event and delta to the front of the arguments
+ args.unshift(event, delta, deltaX, deltaY);
+
+ // Clearout lowestDelta after sometime to better
+ // handle multiple device types that give different
+ // a different lowestDelta
+ // Ex: trackpad = 3 and mouse wheel = 120
+ if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
+ nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
+
+ return ($.event.dispatch || $.event.handle).apply(this, args);
+ }
+
+ function nullLowestDelta() {
+ lowestDelta = null;
+ }
+
+ function shouldAdjustOldDeltas(orgEvent, absDelta) {
+ // If this is an older event and the delta is divisable by 120,
+ // then we are assuming that the browser is treating this as an
+ // older mouse wheel event and that we should divide the deltas
+ // by 40 to try and get a more usable deltaFactor.
+ // Side note, this actually impacts the reported scroll distance
+ // in older browsers and can cause scrolling to be slower than native.
+ // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
+ return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
+ }
+
+}));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/jquery-ui/jquery-ui.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,16582 @@
+/*! jQuery UI - v1.11.2 - 2014-10-16
+* http://jqueryui.com
+* Includes: core.js, widget.js, mouse.js, position.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, draggable.js, droppable.js, effect.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js, menu.js, progressbar.js, resizable.js, selectable.js, selectmenu.js, slider.js, sortable.js, spinner.js, tabs.js, tooltip.js
+* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
+
+(function( factory ) {
+ if ( typeof define === "function" && define.amd ) {
+
+ // AMD. Register as an anonymous module.
+ define([ "jquery" ], factory );
+ } else {
+
+ // Browser globals
+ factory( jQuery );
+ }
+}(function( $ ) {
+/*!
+ * jQuery UI Core 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/category/ui-core/
+ */
+
+
+// $.ui might exist from components with no dependencies, e.g., $.ui.position
+$.ui = $.ui || {};
+
+$.extend( $.ui, {
+ version: "1.11.2",
+
+ keyCode: {
+ BACKSPACE: 8,
+ COMMA: 188,
+ DELETE: 46,
+ DOWN: 40,
+ END: 35,
+ ENTER: 13,
+ ESCAPE: 27,
+ HOME: 36,
+ LEFT: 37,
+ PAGE_DOWN: 34,
+ PAGE_UP: 33,
+ PERIOD: 190,
+ RIGHT: 39,
+ SPACE: 32,
+ TAB: 9,
+ UP: 38
+ }
+});
+
+// plugins
+$.fn.extend({
+ scrollParent: function( includeHidden ) {
+ var position = this.css( "position" ),
+ excludeStaticParent = position === "absolute",
+ overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
+ scrollParent = this.parents().filter( function() {
+ var parent = $( this );
+ if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
+ return false;
+ }
+ return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
+ }).eq( 0 );
+
+ return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
+ },
+
+ uniqueId: (function() {
+ var uuid = 0;
+
+ return function() {
+ return this.each(function() {
+ if ( !this.id ) {
+ this.id = "ui-id-" + ( ++uuid );
+ }
+ });
+ };
+ })(),
+
+ removeUniqueId: function() {
+ return this.each(function() {
+ if ( /^ui-id-\d+$/.test( this.id ) ) {
+ $( this ).removeAttr( "id" );
+ }
+ });
+ }
+});
+
+// selectors
+function focusable( element, isTabIndexNotNaN ) {
+ var map, mapName, img,
+ nodeName = element.nodeName.toLowerCase();
+ if ( "area" === nodeName ) {
+ map = element.parentNode;
+ mapName = map.name;
+ if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
+ return false;
+ }
+ img = $( "img[usemap='#" + mapName + "']" )[ 0 ];
+ return !!img && visible( img );
+ }
+ return ( /input|select|textarea|button|object/.test( nodeName ) ?
+ !element.disabled :
+ "a" === nodeName ?
+ element.href || isTabIndexNotNaN :
+ isTabIndexNotNaN) &&
+ // the element and all of its ancestors must be visible
+ visible( element );
+}
+
+function visible( element ) {
+ return $.expr.filters.visible( element ) &&
+ !$( element ).parents().addBack().filter(function() {
+ return $.css( this, "visibility" ) === "hidden";
+ }).length;
+}
+
+$.extend( $.expr[ ":" ], {
+ data: $.expr.createPseudo ?
+ $.expr.createPseudo(function( dataName ) {
+ return function( elem ) {
+ return !!$.data( elem, dataName );
+ };
+ }) :
+ // support: jQuery <1.8
+ function( elem, i, match ) {
+ return !!$.data( elem, match[ 3 ] );
+ },
+
+ focusable: function( element ) {
+ return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
+ },
+
+ tabbable: function( element ) {
+ var tabIndex = $.attr( element, "tabindex" ),
+ isTabIndexNaN = isNaN( tabIndex );
+ return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
+ }
+});
+
+// support: jQuery <1.8
+if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
+ $.each( [ "Width", "Height" ], function( i, name ) {
+ var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
+ type = name.toLowerCase(),
+ orig = {
+ innerWidth: $.fn.innerWidth,
+ innerHeight: $.fn.innerHeight,
+ outerWidth: $.fn.outerWidth,
+ outerHeight: $.fn.outerHeight
+ };
+
+ function reduce( elem, size, border, margin ) {
+ $.each( side, function() {
+ size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
+ if ( border ) {
+ size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
+ }
+ if ( margin ) {
+ size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
+ }
+ });
+ return size;
+ }
+
+ $.fn[ "inner" + name ] = function( size ) {
+ if ( size === undefined ) {
+ return orig[ "inner" + name ].call( this );
+ }
+
+ return this.each(function() {
+ $( this ).css( type, reduce( this, size ) + "px" );
+ });
+ };
+
+ $.fn[ "outer" + name] = function( size, margin ) {
+ if ( typeof size !== "number" ) {
+ return orig[ "outer" + name ].call( this, size );
+ }
+
+ return this.each(function() {
+ $( this).css( type, reduce( this, size, true, margin ) + "px" );
+ });
+ };
+ });
+}
+
+// support: jQuery <1.8
+if ( !$.fn.addBack ) {
+ $.fn.addBack = function( selector ) {
+ return this.add( selector == null ?
+ this.prevObject : this.prevObject.filter( selector )
+ );
+ };
+}
+
+// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
+if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
+ $.fn.removeData = (function( removeData ) {
+ return function( key ) {
+ if ( arguments.length ) {
+ return removeData.call( this, $.camelCase( key ) );
+ } else {
+ return removeData.call( this );
+ }
+ };
+ })( $.fn.removeData );
+}
+
+// deprecated
+$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
+
+$.fn.extend({
+ focus: (function( orig ) {
+ return function( delay, fn ) {
+ return typeof delay === "number" ?
+ this.each(function() {
+ var elem = this;
+ setTimeout(function() {
+ $( elem ).focus();
+ if ( fn ) {
+ fn.call( elem );
+ }
+ }, delay );
+ }) :
+ orig.apply( this, arguments );
+ };
+ })( $.fn.focus ),
+
+ disableSelection: (function() {
+ var eventType = "onselectstart" in document.createElement( "div" ) ?
+ "selectstart" :
+ "mousedown";
+
+ return function() {
+ return this.bind( eventType + ".ui-disableSelection", function( event ) {
+ event.preventDefault();
+ });
+ };
+ })(),
+
+ enableSelection: function() {
+ return this.unbind( ".ui-disableSelection" );
+ },
+
+ zIndex: function( zIndex ) {
+ if ( zIndex !== undefined ) {
+ return this.css( "zIndex", zIndex );
+ }
+
+ if ( this.length ) {
+ var elem = $( this[ 0 ] ), position, value;
+ while ( elem.length && elem[ 0 ] !== document ) {
+ // Ignore z-index if position is set to a value where z-index is ignored by the browser
+ // This makes behavior of this function consistent across browsers
+ // WebKit always returns auto if the element is positioned
+ position = elem.css( "position" );
+ if ( position === "absolute" || position === "relative" || position === "fixed" ) {
+ // IE returns 0 when zIndex is not specified
+ // other browsers return a string
+ // we ignore the case of nested elements with an explicit value of 0
+ // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
+ value = parseInt( elem.css( "zIndex" ), 10 );
+ if ( !isNaN( value ) && value !== 0 ) {
+ return value;
+ }
+ }
+ elem = elem.parent();
+ }
+ }
+
+ return 0;
+ }
+});
+
+// $.ui.plugin is deprecated. Use $.widget() extensions instead.
+$.ui.plugin = {
+ add: function( module, option, set ) {
+ var i,
+ proto = $.ui[ module ].prototype;
+ for ( i in set ) {
+ proto.plugins[ i ] = proto.plugins[ i ] || [];
+ proto.plugins[ i ].push( [ option, set[ i ] ] );
+ }
+ },
+ call: function( instance, name, args, allowDisconnected ) {
+ var i,
+ set = instance.plugins[ name ];
+
+ if ( !set ) {
+ return;
+ }
+
+ if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
+ return;
+ }
+
+ for ( i = 0; i < set.length; i++ ) {
+ if ( instance.options[ set[ i ][ 0 ] ] ) {
+ set[ i ][ 1 ].apply( instance.element, args );
+ }
+ }
+ }
+};
+
+
+/*!
+ * jQuery UI Widget 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/jQuery.widget/
+ */
+
+
+var widget_uuid = 0,
+ widget_slice = Array.prototype.slice;
+
+$.cleanData = (function( orig ) {
+ return function( elems ) {
+ var events, elem, i;
+ for ( i = 0; (elem = elems[i]) != null; i++ ) {
+ try {
+
+ // Only trigger remove when necessary to save time
+ events = $._data( elem, "events" );
+ if ( events && events.remove ) {
+ $( elem ).triggerHandler( "remove" );
+ }
+
+ // http://bugs.jquery.com/ticket/8235
+ } catch ( e ) {}
+ }
+ orig( elems );
+ };
+})( $.cleanData );
+
+$.widget = function( name, base, prototype ) {
+ var fullName, existingConstructor, constructor, basePrototype,
+ // proxiedPrototype allows the provided prototype to remain unmodified
+ // so that it can be used as a mixin for multiple widgets (#8876)
+ proxiedPrototype = {},
+ namespace = name.split( "." )[ 0 ];
+
+ name = name.split( "." )[ 1 ];
+ fullName = namespace + "-" + name;
+
+ if ( !prototype ) {
+ prototype = base;
+ base = $.Widget;
+ }
+
+ // create selector for plugin
+ $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
+ return !!$.data( elem, fullName );
+ };
+
+ $[ namespace ] = $[ namespace ] || {};
+ existingConstructor = $[ namespace ][ name ];
+ constructor = $[ namespace ][ name ] = function( options, element ) {
+ // allow instantiation without "new" keyword
+ if ( !this._createWidget ) {
+ return new constructor( options, element );
+ }
+
+ // allow instantiation without initializing for simple inheritance
+ // must use "new" keyword (the code above always passes args)
+ if ( arguments.length ) {
+ this._createWidget( options, element );
+ }
+ };
+ // extend with the existing constructor to carry over any static properties
+ $.extend( constructor, existingConstructor, {
+ version: prototype.version,
+ // copy the object used to create the prototype in case we need to
+ // redefine the widget later
+ _proto: $.extend( {}, prototype ),
+ // track widgets that inherit from this widget in case this widget is
+ // redefined after a widget inherits from it
+ _childConstructors: []
+ });
+
+ basePrototype = new base();
+ // we need to make the options hash a property directly on the new instance
+ // otherwise we'll modify the options hash on the prototype that we're
+ // inheriting from
+ basePrototype.options = $.widget.extend( {}, basePrototype.options );
+ $.each( prototype, function( prop, value ) {
+ if ( !$.isFunction( value ) ) {
+ proxiedPrototype[ prop ] = value;
+ return;
+ }
+ proxiedPrototype[ prop ] = (function() {
+ var _super = function() {
+ return base.prototype[ prop ].apply( this, arguments );
+ },
+ _superApply = function( args ) {
+ return base.prototype[ prop ].apply( this, args );
+ };
+ return function() {
+ var __super = this._super,
+ __superApply = this._superApply,
+ returnValue;
+
+ this._super = _super;
+ this._superApply = _superApply;
+
+ returnValue = value.apply( this, arguments );
+
+ this._super = __super;
+ this._superApply = __superApply;
+
+ return returnValue;
+ };
+ })();
+ });
+ constructor.prototype = $.widget.extend( basePrototype, {
+ // TODO: remove support for widgetEventPrefix
+ // always use the name + a colon as the prefix, e.g., draggable:start
+ // don't prefix for widgets that aren't DOM-based
+ widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
+ }, proxiedPrototype, {
+ constructor: constructor,
+ namespace: namespace,
+ widgetName: name,
+ widgetFullName: fullName
+ });
+
+ // If this widget is being redefined then we need to find all widgets that
+ // are inheriting from it and redefine all of them so that they inherit from
+ // the new version of this widget. We're essentially trying to replace one
+ // level in the prototype chain.
+ if ( existingConstructor ) {
+ $.each( existingConstructor._childConstructors, function( i, child ) {
+ var childPrototype = child.prototype;
+
+ // redefine the child widget using the same prototype that was
+ // originally used, but inherit from the new version of the base
+ $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
+ });
+ // remove the list of existing child constructors from the old constructor
+ // so the old child constructors can be garbage collected
+ delete existingConstructor._childConstructors;
+ } else {
+ base._childConstructors.push( constructor );
+ }
+
+ $.widget.bridge( name, constructor );
+
+ return constructor;
+};
+
+$.widget.extend = function( target ) {
+ var input = widget_slice.call( arguments, 1 ),
+ inputIndex = 0,
+ inputLength = input.length,
+ key,
+ value;
+ for ( ; inputIndex < inputLength; inputIndex++ ) {
+ for ( key in input[ inputIndex ] ) {
+ value = input[ inputIndex ][ key ];
+ if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
+ // Clone objects
+ if ( $.isPlainObject( value ) ) {
+ target[ key ] = $.isPlainObject( target[ key ] ) ?
+ $.widget.extend( {}, target[ key ], value ) :
+ // Don't extend strings, arrays, etc. with objects
+ $.widget.extend( {}, value );
+ // Copy everything else by reference
+ } else {
+ target[ key ] = value;
+ }
+ }
+ }
+ }
+ return target;
+};
+
+$.widget.bridge = function( name, object ) {
+ var fullName = object.prototype.widgetFullName || name;
+ $.fn[ name ] = function( options ) {
+ var isMethodCall = typeof options === "string",
+ args = widget_slice.call( arguments, 1 ),
+ returnValue = this;
+
+ // allow multiple hashes to be passed on init
+ options = !isMethodCall && args.length ?
+ $.widget.extend.apply( null, [ options ].concat(args) ) :
+ options;
+
+ if ( isMethodCall ) {
+ this.each(function() {
+ var methodValue,
+ instance = $.data( this, fullName );
+ if ( options === "instance" ) {
+ returnValue = instance;
+ return false;
+ }
+ if ( !instance ) {
+ return $.error( "cannot call methods on " + name + " prior to initialization; " +
+ "attempted to call method '" + options + "'" );
+ }
+ if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
+ return $.error( "no such method '" + options + "' for " + name + " widget instance" );
+ }
+ methodValue = instance[ options ].apply( instance, args );
+ if ( methodValue !== instance && methodValue !== undefined ) {
+ returnValue = methodValue && methodValue.jquery ?
+ returnValue.pushStack( methodValue.get() ) :
+ methodValue;
+ return false;
+ }
+ });
+ } else {
+ this.each(function() {
+ var instance = $.data( this, fullName );
+ if ( instance ) {
+ instance.option( options || {} );
+ if ( instance._init ) {
+ instance._init();
+ }
+ } else {
+ $.data( this, fullName, new object( options, this ) );
+ }
+ });
+ }
+
+ return returnValue;
+ };
+};
+
+$.Widget = function( /* options, element */ ) {};
+$.Widget._childConstructors = [];
+
+$.Widget.prototype = {
+ widgetName: "widget",
+ widgetEventPrefix: "",
+ defaultElement: "<div>",
+ options: {
+ disabled: false,
+
+ // callbacks
+ create: null
+ },
+ _createWidget: function( options, element ) {
+ element = $( element || this.defaultElement || this )[ 0 ];
+ this.element = $( element );
+ this.uuid = widget_uuid++;
+ this.eventNamespace = "." + this.widgetName + this.uuid;
+
+ this.bindings = $();
+ this.hoverable = $();
+ this.focusable = $();
+
+ if ( element !== this ) {
+ $.data( element, this.widgetFullName, this );
+ this._on( true, this.element, {
+ remove: function( event ) {
+ if ( event.target === element ) {
+ this.destroy();
+ }
+ }
+ });
+ this.document = $( element.style ?
+ // element within the document
+ element.ownerDocument :
+ // element is window or document
+ element.document || element );
+ this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
+ }
+
+ this.options = $.widget.extend( {},
+ this.options,
+ this._getCreateOptions(),
+ options );
+
+ this._create();
+ this._trigger( "create", null, this._getCreateEventData() );
+ this._init();
+ },
+ _getCreateOptions: $.noop,
+ _getCreateEventData: $.noop,
+ _create: $.noop,
+ _init: $.noop,
+
+ destroy: function() {
+ this._destroy();
+ // we can probably remove the unbind calls in 2.0
+ // all event bindings should go through this._on()
+ this.element
+ .unbind( this.eventNamespace )
+ .removeData( this.widgetFullName )
+ // support: jquery <1.6.3
+ // http://bugs.jquery.com/ticket/9413
+ .removeData( $.camelCase( this.widgetFullName ) );
+ this.widget()
+ .unbind( this.eventNamespace )
+ .removeAttr( "aria-disabled" )
+ .removeClass(
+ this.widgetFullName + "-disabled " +
+ "ui-state-disabled" );
+
+ // clean up events and states
+ this.bindings.unbind( this.eventNamespace );
+ this.hoverable.removeClass( "ui-state-hover" );
+ this.focusable.removeClass( "ui-state-focus" );
+ },
+ _destroy: $.noop,
+
+ widget: function() {
+ return this.element;
+ },
+
+ option: function( key, value ) {
+ var options = key,
+ parts,
+ curOption,
+ i;
+
+ if ( arguments.length === 0 ) {
+ // don't return a reference to the internal hash
+ return $.widget.extend( {}, this.options );
+ }
+
+ if ( typeof key === "string" ) {
+ // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
+ options = {};
+ parts = key.split( "." );
+ key = parts.shift();
+ if ( parts.length ) {
+ curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
+ for ( i = 0; i < parts.length - 1; i++ ) {
+ curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
+ curOption = curOption[ parts[ i ] ];
+ }
+ key = parts.pop();
+ if ( arguments.length === 1 ) {
+ return curOption[ key ] === undefined ? null : curOption[ key ];
+ }
+ curOption[ key ] = value;
+ } else {
+ if ( arguments.length === 1 ) {
+ return this.options[ key ] === undefined ? null : this.options[ key ];
+ }
+ options[ key ] = value;
+ }
+ }
+
+ this._setOptions( options );
+
+ return this;
+ },
+ _setOptions: function( options ) {
+ var key;
+
+ for ( key in options ) {
+ this._setOption( key, options[ key ] );
+ }
+
+ return this;
+ },
+ _setOption: function( key, value ) {
+ this.options[ key ] = value;
+
+ if ( key === "disabled" ) {
+ this.widget()
+ .toggleClass( this.widgetFullName + "-disabled", !!value );
+
+ // If the widget is becoming disabled, then nothing is interactive
+ if ( value ) {
+ this.hoverable.removeClass( "ui-state-hover" );
+ this.focusable.removeClass( "ui-state-focus" );
+ }
+ }
+
+ return this;
+ },
+
+ enable: function() {
+ return this._setOptions({ disabled: false });
+ },
+ disable: function() {
+ return this._setOptions({ disabled: true });
+ },
+
+ _on: function( suppressDisabledCheck, element, handlers ) {
+ var delegateElement,
+ instance = this;
+
+ // no suppressDisabledCheck flag, shuffle arguments
+ if ( typeof suppressDisabledCheck !== "boolean" ) {
+ handlers = element;
+ element = suppressDisabledCheck;
+ suppressDisabledCheck = false;
+ }
+
+ // no element argument, shuffle and use this.element
+ if ( !handlers ) {
+ handlers = element;
+ element = this.element;
+ delegateElement = this.widget();
+ } else {
+ element = delegateElement = $( element );
+ this.bindings = this.bindings.add( element );
+ }
+
+ $.each( handlers, function( event, handler ) {
+ function handlerProxy() {
+ // allow widgets to customize the disabled handling
+ // - disabled as an array instead of boolean
+ // - disabled class as method for disabling individual parts
+ if ( !suppressDisabledCheck &&
+ ( instance.options.disabled === true ||
+ $( this ).hasClass( "ui-state-disabled" ) ) ) {
+ return;
+ }
+ return ( typeof handler === "string" ? instance[ handler ] : handler )
+ .apply( instance, arguments );
+ }
+
+ // copy the guid so direct unbinding works
+ if ( typeof handler !== "string" ) {
+ handlerProxy.guid = handler.guid =
+ handler.guid || handlerProxy.guid || $.guid++;
+ }
+
+ var match = event.match( /^([\w:-]*)\s*(.*)$/ ),
+ eventName = match[1] + instance.eventNamespace,
+ selector = match[2];
+ if ( selector ) {
+ delegateElement.delegate( selector, eventName, handlerProxy );
+ } else {
+ element.bind( eventName, handlerProxy );
+ }
+ });
+ },
+
+ _off: function( element, eventName ) {
+ eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) +
+ this.eventNamespace;
+ element.unbind( eventName ).undelegate( eventName );
+
+ // Clear the stack to avoid memory leaks (#10056)
+ this.bindings = $( this.bindings.not( element ).get() );
+ this.focusable = $( this.focusable.not( element ).get() );
+ this.hoverable = $( this.hoverable.not( element ).get() );
+ },
+
+ _delay: function( handler, delay ) {
+ function handlerProxy() {
+ return ( typeof handler === "string" ? instance[ handler ] : handler )
+ .apply( instance, arguments );
+ }
+ var instance = this;
+ return setTimeout( handlerProxy, delay || 0 );
+ },
+
+ _hoverable: function( element ) {
+ this.hoverable = this.hoverable.add( element );
+ this._on( element, {
+ mouseenter: function( event ) {
+ $( event.currentTarget ).addClass( "ui-state-hover" );
+ },
+ mouseleave: function( event ) {
+ $( event.currentTarget ).removeClass( "ui-state-hover" );
+ }
+ });
+ },
+
+ _focusable: function( element ) {
+ this.focusable = this.focusable.add( element );
+ this._on( element, {
+ focusin: function( event ) {
+ $( event.currentTarget ).addClass( "ui-state-focus" );
+ },
+ focusout: function( event ) {
+ $( event.currentTarget ).removeClass( "ui-state-focus" );
+ }
+ });
+ },
+
+ _trigger: function( type, event, data ) {
+ var prop, orig,
+ callback = this.options[ type ];
+
+ data = data || {};
+ event = $.Event( event );
+ event.type = ( type === this.widgetEventPrefix ?
+ type :
+ this.widgetEventPrefix + type ).toLowerCase();
+ // the original event may come from any element
+ // so we need to reset the target on the new event
+ event.target = this.element[ 0 ];
+
+ // copy original event properties over to the new event
+ orig = event.originalEvent;
+ if ( orig ) {
+ for ( prop in orig ) {
+ if ( !( prop in event ) ) {
+ event[ prop ] = orig[ prop ];
+ }
+ }
+ }
+
+ this.element.trigger( event, data );
+ return !( $.isFunction( callback ) &&
+ callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
+ event.isDefaultPrevented() );
+ }
+};
+
+$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
+ $.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
+ if ( typeof options === "string" ) {
+ options = { effect: options };
+ }
+ var hasOptions,
+ effectName = !options ?
+ method :
+ options === true || typeof options === "number" ?
+ defaultEffect :
+ options.effect || defaultEffect;
+ options = options || {};
+ if ( typeof options === "number" ) {
+ options = { duration: options };
+ }
+ hasOptions = !$.isEmptyObject( options );
+ options.complete = callback;
+ if ( options.delay ) {
+ element.delay( options.delay );
+ }
+ if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
+ element[ method ]( options );
+ } else if ( effectName !== method && element[ effectName ] ) {
+ element[ effectName ]( options.duration, options.easing, callback );
+ } else {
+ element.queue(function( next ) {
+ $( this )[ method ]();
+ if ( callback ) {
+ callback.call( element[ 0 ] );
+ }
+ next();
+ });
+ }
+ };
+});
+
+var widget = $.widget;
+
+
+/*!
+ * jQuery UI Mouse 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/mouse/
+ */
+
+
+var mouseHandled = false;
+$( document ).mouseup( function() {
+ mouseHandled = false;
+});
+
+var mouse = $.widget("ui.mouse", {
+ version: "1.11.2",
+ options: {
+ cancel: "input,textarea,button,select,option",
+ distance: 1,
+ delay: 0
+ },
+ _mouseInit: function() {
+ var that = this;
+
+ this.element
+ .bind("mousedown." + this.widgetName, function(event) {
+ return that._mouseDown(event);
+ })
+ .bind("click." + this.widgetName, function(event) {
+ if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
+ $.removeData(event.target, that.widgetName + ".preventClickEvent");
+ event.stopImmediatePropagation();
+ return false;
+ }
+ });
+
+ this.started = false;
+ },
+
+ // TODO: make sure destroying one instance of mouse doesn't mess with
+ // other instances of mouse
+ _mouseDestroy: function() {
+ this.element.unbind("." + this.widgetName);
+ if ( this._mouseMoveDelegate ) {
+ this.document
+ .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate)
+ .unbind("mouseup." + this.widgetName, this._mouseUpDelegate);
+ }
+ },
+
+ _mouseDown: function(event) {
+ // don't let more than one widget handle mouseStart
+ if ( mouseHandled ) {
+ return;
+ }
+
+ this._mouseMoved = false;
+
+ // we may have missed mouseup (out of window)
+ (this._mouseStarted && this._mouseUp(event));
+
+ this._mouseDownEvent = event;
+
+ var that = this,
+ btnIsLeft = (event.which === 1),
+ // event.target.nodeName works around a bug in IE 8 with
+ // disabled inputs (#7620)
+ elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
+ if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
+ return true;
+ }
+
+ this.mouseDelayMet = !this.options.delay;
+ if (!this.mouseDelayMet) {
+ this._mouseDelayTimer = setTimeout(function() {
+ that.mouseDelayMet = true;
+ }, this.options.delay);
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted = (this._mouseStart(event) !== false);
+ if (!this._mouseStarted) {
+ event.preventDefault();
+ return true;
+ }
+ }
+
+ // Click event may never have fired (Gecko & Opera)
+ if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
+ $.removeData(event.target, this.widgetName + ".preventClickEvent");
+ }
+
+ // these delegates are required to keep context
+ this._mouseMoveDelegate = function(event) {
+ return that._mouseMove(event);
+ };
+ this._mouseUpDelegate = function(event) {
+ return that._mouseUp(event);
+ };
+
+ this.document
+ .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
+ .bind( "mouseup." + this.widgetName, this._mouseUpDelegate );
+
+ event.preventDefault();
+
+ mouseHandled = true;
+ return true;
+ },
+
+ _mouseMove: function(event) {
+ // Only check for mouseups outside the document if you've moved inside the document
+ // at least once. This prevents the firing of mouseup in the case of IE<9, which will
+ // fire a mousemove event if content is placed under the cursor. See #7778
+ // Support: IE <9
+ if ( this._mouseMoved ) {
+ // IE mouseup check - mouseup happened when mouse was out of window
+ if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
+ return this._mouseUp(event);
+
+ // Iframe mouseup check - mouseup occurred in another document
+ } else if ( !event.which ) {
+ return this._mouseUp( event );
+ }
+ }
+
+ if ( event.which || event.button ) {
+ this._mouseMoved = true;
+ }
+
+ if (this._mouseStarted) {
+ this._mouseDrag(event);
+ return event.preventDefault();
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted =
+ (this._mouseStart(this._mouseDownEvent, event) !== false);
+ (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
+ }
+
+ return !this._mouseStarted;
+ },
+
+ _mouseUp: function(event) {
+ this.document
+ .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
+ .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate );
+
+ if (this._mouseStarted) {
+ this._mouseStarted = false;
+
+ if (event.target === this._mouseDownEvent.target) {
+ $.data(event.target, this.widgetName + ".preventClickEvent", true);
+ }
+
+ this._mouseStop(event);
+ }
+
+ mouseHandled = false;
+ return false;
+ },
+
+ _mouseDistanceMet: function(event) {
+ return (Math.max(
+ Math.abs(this._mouseDownEvent.pageX - event.pageX),
+ Math.abs(this._mouseDownEvent.pageY - event.pageY)
+ ) >= this.options.distance
+ );
+ },
+
+ _mouseDelayMet: function(/* event */) {
+ return this.mouseDelayMet;
+ },
+
+ // These are placeholder methods, to be overriden by extending plugin
+ _mouseStart: function(/* event */) {},
+ _mouseDrag: function(/* event */) {},
+ _mouseStop: function(/* event */) {},
+ _mouseCapture: function(/* event */) { return true; }
+});
+
+
+/*!
+ * jQuery UI Position 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/position/
+ */
+
+(function() {
+
+$.ui = $.ui || {};
+
+var cachedScrollbarWidth, supportsOffsetFractions,
+ max = Math.max,
+ abs = Math.abs,
+ round = Math.round,
+ rhorizontal = /left|center|right/,
+ rvertical = /top|center|bottom/,
+ roffset = /[\+\-]\d+(\.[\d]+)?%?/,
+ rposition = /^\w+/,
+ rpercent = /%$/,
+ _position = $.fn.position;
+
+function getOffsets( offsets, width, height ) {
+ return [
+ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
+ parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
+ ];
+}
+
+function parseCss( element, property ) {
+ return parseInt( $.css( element, property ), 10 ) || 0;
+}
+
+function getDimensions( elem ) {
+ var raw = elem[0];
+ if ( raw.nodeType === 9 ) {
+ return {
+ width: elem.width(),
+ height: elem.height(),
+ offset: { top: 0, left: 0 }
+ };
+ }
+ if ( $.isWindow( raw ) ) {
+ return {
+ width: elem.width(),
+ height: elem.height(),
+ offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
+ };
+ }
+ if ( raw.preventDefault ) {
+ return {
+ width: 0,
+ height: 0,
+ offset: { top: raw.pageY, left: raw.pageX }
+ };
+ }
+ return {
+ width: elem.outerWidth(),
+ height: elem.outerHeight(),
+ offset: elem.offset()
+ };
+}
+
+$.position = {
+ scrollbarWidth: function() {
+ if ( cachedScrollbarWidth !== undefined ) {
+ return cachedScrollbarWidth;
+ }
+ var w1, w2,
+ div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
+ innerDiv = div.children()[0];
+
+ $( "body" ).append( div );
+ w1 = innerDiv.offsetWidth;
+ div.css( "overflow", "scroll" );
+
+ w2 = innerDiv.offsetWidth;
+
+ if ( w1 === w2 ) {
+ w2 = div[0].clientWidth;
+ }
+
+ div.remove();
+
+ return (cachedScrollbarWidth = w1 - w2);
+ },
+ getScrollInfo: function( within ) {
+ var overflowX = within.isWindow || within.isDocument ? "" :
+ within.element.css( "overflow-x" ),
+ overflowY = within.isWindow || within.isDocument ? "" :
+ within.element.css( "overflow-y" ),
+ hasOverflowX = overflowX === "scroll" ||
+ ( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
+ hasOverflowY = overflowY === "scroll" ||
+ ( overflowY === "auto" && within.height < within.element[0].scrollHeight );
+ return {
+ width: hasOverflowY ? $.position.scrollbarWidth() : 0,
+ height: hasOverflowX ? $.position.scrollbarWidth() : 0
+ };
+ },
+ getWithinInfo: function( element ) {
+ var withinElement = $( element || window ),
+ isWindow = $.isWindow( withinElement[0] ),
+ isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
+ return {
+ element: withinElement,
+ isWindow: isWindow,
+ isDocument: isDocument,
+ offset: withinElement.offset() || { left: 0, top: 0 },
+ scrollLeft: withinElement.scrollLeft(),
+ scrollTop: withinElement.scrollTop(),
+
+ // support: jQuery 1.6.x
+ // jQuery 1.6 doesn't support .outerWidth/Height() on documents or windows
+ width: isWindow || isDocument ? withinElement.width() : withinElement.outerWidth(),
+ height: isWindow || isDocument ? withinElement.height() : withinElement.outerHeight()
+ };
+ }
+};
+
+$.fn.position = function( options ) {
+ if ( !options || !options.of ) {
+ return _position.apply( this, arguments );
+ }
+
+ // make a copy, we don't want to modify arguments
+ options = $.extend( {}, options );
+
+ var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
+ target = $( options.of ),
+ within = $.position.getWithinInfo( options.within ),
+ scrollInfo = $.position.getScrollInfo( within ),
+ collision = ( options.collision || "flip" ).split( " " ),
+ offsets = {};
+
+ dimensions = getDimensions( target );
+ if ( target[0].preventDefault ) {
+ // force left top to allow flipping
+ options.at = "left top";
+ }
+ targetWidth = dimensions.width;
+ targetHeight = dimensions.height;
+ targetOffset = dimensions.offset;
+ // clone to reuse original targetOffset later
+ basePosition = $.extend( {}, targetOffset );
+
+ // force my and at to have valid horizontal and vertical positions
+ // if a value is missing or invalid, it will be converted to center
+ $.each( [ "my", "at" ], function() {
+ var pos = ( options[ this ] || "" ).split( " " ),
+ horizontalOffset,
+ verticalOffset;
+
+ if ( pos.length === 1) {
+ pos = rhorizontal.test( pos[ 0 ] ) ?
+ pos.concat( [ "center" ] ) :
+ rvertical.test( pos[ 0 ] ) ?
+ [ "center" ].concat( pos ) :
+ [ "center", "center" ];
+ }
+ pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
+ pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
+
+ // calculate offsets
+ horizontalOffset = roffset.exec( pos[ 0 ] );
+ verticalOffset = roffset.exec( pos[ 1 ] );
+ offsets[ this ] = [
+ horizontalOffset ? horizontalOffset[ 0 ] : 0,
+ verticalOffset ? verticalOffset[ 0 ] : 0
+ ];
+
+ // reduce to just the positions without the offsets
+ options[ this ] = [
+ rposition.exec( pos[ 0 ] )[ 0 ],
+ rposition.exec( pos[ 1 ] )[ 0 ]
+ ];
+ });
+
+ // normalize collision option
+ if ( collision.length === 1 ) {
+ collision[ 1 ] = collision[ 0 ];
+ }
+
+ if ( options.at[ 0 ] === "right" ) {
+ basePosition.left += targetWidth;
+ } else if ( options.at[ 0 ] === "center" ) {
+ basePosition.left += targetWidth / 2;
+ }
+
+ if ( options.at[ 1 ] === "bottom" ) {
+ basePosition.top += targetHeight;
+ } else if ( options.at[ 1 ] === "center" ) {
+ basePosition.top += targetHeight / 2;
+ }
+
+ atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
+ basePosition.left += atOffset[ 0 ];
+ basePosition.top += atOffset[ 1 ];
+
+ return this.each(function() {
+ var collisionPosition, using,
+ elem = $( this ),
+ elemWidth = elem.outerWidth(),
+ elemHeight = elem.outerHeight(),
+ marginLeft = parseCss( this, "marginLeft" ),
+ marginTop = parseCss( this, "marginTop" ),
+ collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
+ collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
+ position = $.extend( {}, basePosition ),
+ myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
+
+ if ( options.my[ 0 ] === "right" ) {
+ position.left -= elemWidth;
+ } else if ( options.my[ 0 ] === "center" ) {
+ position.left -= elemWidth / 2;
+ }
+
+ if ( options.my[ 1 ] === "bottom" ) {
+ position.top -= elemHeight;
+ } else if ( options.my[ 1 ] === "center" ) {
+ position.top -= elemHeight / 2;
+ }
+
+ position.left += myOffset[ 0 ];
+ position.top += myOffset[ 1 ];
+
+ // if the browser doesn't support fractions, then round for consistent results
+ if ( !supportsOffsetFractions ) {
+ position.left = round( position.left );
+ position.top = round( position.top );
+ }
+
+ collisionPosition = {
+ marginLeft: marginLeft,
+ marginTop: marginTop
+ };
+
+ $.each( [ "left", "top" ], function( i, dir ) {
+ if ( $.ui.position[ collision[ i ] ] ) {
+ $.ui.position[ collision[ i ] ][ dir ]( position, {
+ targetWidth: targetWidth,
+ targetHeight: targetHeight,
+ elemWidth: elemWidth,
+ elemHeight: elemHeight,
+ collisionPosition: collisionPosition,
+ collisionWidth: collisionWidth,
+ collisionHeight: collisionHeight,
+ offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
+ my: options.my,
+ at: options.at,
+ within: within,
+ elem: elem
+ });
+ }
+ });
+
+ if ( options.using ) {
+ // adds feedback as second argument to using callback, if present
+ using = function( props ) {
+ var left = targetOffset.left - position.left,
+ right = left + targetWidth - elemWidth,
+ top = targetOffset.top - position.top,
+ bottom = top + targetHeight - elemHeight,
+ feedback = {
+ target: {
+ element: target,
+ left: targetOffset.left,
+ top: targetOffset.top,
+ width: targetWidth,
+ height: targetHeight
+ },
+ element: {
+ element: elem,
+ left: position.left,
+ top: position.top,
+ width: elemWidth,
+ height: elemHeight
+ },
+ horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
+ vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
+ };
+ if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
+ feedback.horizontal = "center";
+ }
+ if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
+ feedback.vertical = "middle";
+ }
+ if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
+ feedback.important = "horizontal";
+ } else {
+ feedback.important = "vertical";
+ }
+ options.using.call( this, props, feedback );
+ };
+ }
+
+ elem.offset( $.extend( position, { using: using } ) );
+ });
+};
+
+$.ui.position = {
+ fit: {
+ left: function( position, data ) {
+ var within = data.within,
+ withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
+ outerWidth = within.width,
+ collisionPosLeft = position.left - data.collisionPosition.marginLeft,
+ overLeft = withinOffset - collisionPosLeft,
+ overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
+ newOverRight;
+
+ // element is wider than within
+ if ( data.collisionWidth > outerWidth ) {
+ // element is initially over the left side of within
+ if ( overLeft > 0 && overRight <= 0 ) {
+ newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
+ position.left += overLeft - newOverRight;
+ // element is initially over right side of within
+ } else if ( overRight > 0 && overLeft <= 0 ) {
+ position.left = withinOffset;
+ // element is initially over both left and right sides of within
+ } else {
+ if ( overLeft > overRight ) {
+ position.left = withinOffset + outerWidth - data.collisionWidth;
+ } else {
+ position.left = withinOffset;
+ }
+ }
+ // too far left -> align with left edge
+ } else if ( overLeft > 0 ) {
+ position.left += overLeft;
+ // too far right -> align with right edge
+ } else if ( overRight > 0 ) {
+ position.left -= overRight;
+ // adjust based on position and margin
+ } else {
+ position.left = max( position.left - collisionPosLeft, position.left );
+ }
+ },
+ top: function( position, data ) {
+ var within = data.within,
+ withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
+ outerHeight = data.within.height,
+ collisionPosTop = position.top - data.collisionPosition.marginTop,
+ overTop = withinOffset - collisionPosTop,
+ overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
+ newOverBottom;
+
+ // element is taller than within
+ if ( data.collisionHeight > outerHeight ) {
+ // element is initially over the top of within
+ if ( overTop > 0 && overBottom <= 0 ) {
+ newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
+ position.top += overTop - newOverBottom;
+ // element is initially over bottom of within
+ } else if ( overBottom > 0 && overTop <= 0 ) {
+ position.top = withinOffset;
+ // element is initially over both top and bottom of within
+ } else {
+ if ( overTop > overBottom ) {
+ position.top = withinOffset + outerHeight - data.collisionHeight;
+ } else {
+ position.top = withinOffset;
+ }
+ }
+ // too far up -> align with top
+ } else if ( overTop > 0 ) {
+ position.top += overTop;
+ // too far down -> align with bottom edge
+ } else if ( overBottom > 0 ) {
+ position.top -= overBottom;
+ // adjust based on position and margin
+ } else {
+ position.top = max( position.top - collisionPosTop, position.top );
+ }
+ }
+ },
+ flip: {
+ left: function( position, data ) {
+ var within = data.within,
+ withinOffset = within.offset.left + within.scrollLeft,
+ outerWidth = within.width,
+ offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
+ collisionPosLeft = position.left - data.collisionPosition.marginLeft,
+ overLeft = collisionPosLeft - offsetLeft,
+ overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
+ myOffset = data.my[ 0 ] === "left" ?
+ -data.elemWidth :
+ data.my[ 0 ] === "right" ?
+ data.elemWidth :
+ 0,
+ atOffset = data.at[ 0 ] === "left" ?
+ data.targetWidth :
+ data.at[ 0 ] === "right" ?
+ -data.targetWidth :
+ 0,
+ offset = -2 * data.offset[ 0 ],
+ newOverRight,
+ newOverLeft;
+
+ if ( overLeft < 0 ) {
+ newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
+ if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
+ position.left += myOffset + atOffset + offset;
+ }
+ } else if ( overRight > 0 ) {
+ newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
+ if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
+ position.left += myOffset + atOffset + offset;
+ }
+ }
+ },
+ top: function( position, data ) {
+ var within = data.within,
+ withinOffset = within.offset.top + within.scrollTop,
+ outerHeight = within.height,
+ offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
+ collisionPosTop = position.top - data.collisionPosition.marginTop,
+ overTop = collisionPosTop - offsetTop,
+ overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
+ top = data.my[ 1 ] === "top",
+ myOffset = top ?
+ -data.elemHeight :
+ data.my[ 1 ] === "bottom" ?
+ data.elemHeight :
+ 0,
+ atOffset = data.at[ 1 ] === "top" ?
+ data.targetHeight :
+ data.at[ 1 ] === "bottom" ?
+ -data.targetHeight :
+ 0,
+ offset = -2 * data.offset[ 1 ],
+ newOverTop,
+ newOverBottom;
+ if ( overTop < 0 ) {
+ newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
+ if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
+ position.top += myOffset + atOffset + offset;
+ }
+ } else if ( overBottom > 0 ) {
+ newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
+ if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
+ position.top += myOffset + atOffset + offset;
+ }
+ }
+ }
+ },
+ flipfit: {
+ left: function() {
+ $.ui.position.flip.left.apply( this, arguments );
+ $.ui.position.fit.left.apply( this, arguments );
+ },
+ top: function() {
+ $.ui.position.flip.top.apply( this, arguments );
+ $.ui.position.fit.top.apply( this, arguments );
+ }
+ }
+};
+
+// fraction support test
+(function() {
+ var testElement, testElementParent, testElementStyle, offsetLeft, i,
+ body = document.getElementsByTagName( "body" )[ 0 ],
+ div = document.createElement( "div" );
+
+ //Create a "fake body" for testing based on method used in jQuery.support
+ testElement = document.createElement( body ? "div" : "body" );
+ testElementStyle = {
+ visibility: "hidden",
+ width: 0,
+ height: 0,
+ border: 0,
+ margin: 0,
+ background: "none"
+ };
+ if ( body ) {
+ $.extend( testElementStyle, {
+ position: "absolute",
+ left: "-1000px",
+ top: "-1000px"
+ });
+ }
+ for ( i in testElementStyle ) {
+ testElement.style[ i ] = testElementStyle[ i ];
+ }
+ testElement.appendChild( div );
+ testElementParent = body || document.documentElement;
+ testElementParent.insertBefore( testElement, testElementParent.firstChild );
+
+ div.style.cssText = "position: absolute; left: 10.7432222px;";
+
+ offsetLeft = $( div ).offset().left;
+ supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11;
+
+ testElement.innerHTML = "";
+ testElementParent.removeChild( testElement );
+})();
+
+})();
+
+var position = $.ui.position;
+
+
+/*!
+ * jQuery UI Accordion 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/accordion/
+ */
+
+
+var accordion = $.widget( "ui.accordion", {
+ version: "1.11.2",
+ options: {
+ active: 0,
+ animate: {},
+ collapsible: false,
+ event: "click",
+ header: "> li > :first-child,> :not(li):even",
+ heightStyle: "auto",
+ icons: {
+ activeHeader: "ui-icon-triangle-1-s",
+ header: "ui-icon-triangle-1-e"
+ },
+
+ // callbacks
+ activate: null,
+ beforeActivate: null
+ },
+
+ hideProps: {
+ borderTopWidth: "hide",
+ borderBottomWidth: "hide",
+ paddingTop: "hide",
+ paddingBottom: "hide",
+ height: "hide"
+ },
+
+ showProps: {
+ borderTopWidth: "show",
+ borderBottomWidth: "show",
+ paddingTop: "show",
+ paddingBottom: "show",
+ height: "show"
+ },
+
+ _create: function() {
+ var options = this.options;
+ this.prevShow = this.prevHide = $();
+ this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
+ // ARIA
+ .attr( "role", "tablist" );
+
+ // don't allow collapsible: false and active: false / null
+ if ( !options.collapsible && (options.active === false || options.active == null) ) {
+ options.active = 0;
+ }
+
+ this._processPanels();
+ // handle negative values
+ if ( options.active < 0 ) {
+ options.active += this.headers.length;
+ }
+ this._refresh();
+ },
+
+ _getCreateEventData: function() {
+ return {
+ header: this.active,
+ panel: !this.active.length ? $() : this.active.next()
+ };
+ },
+
+ _createIcons: function() {
+ var icons = this.options.icons;
+ if ( icons ) {
+ $( "<span>" )
+ .addClass( "ui-accordion-header-icon ui-icon " + icons.header )
+ .prependTo( this.headers );
+ this.active.children( ".ui-accordion-header-icon" )
+ .removeClass( icons.header )
+ .addClass( icons.activeHeader );
+ this.headers.addClass( "ui-accordion-icons" );
+ }
+ },
+
+ _destroyIcons: function() {
+ this.headers
+ .removeClass( "ui-accordion-icons" )
+ .children( ".ui-accordion-header-icon" )
+ .remove();
+ },
+
+ _destroy: function() {
+ var contents;
+
+ // clean up main element
+ this.element
+ .removeClass( "ui-accordion ui-widget ui-helper-reset" )
+ .removeAttr( "role" );
+
+ // clean up headers
+ this.headers
+ .removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default " +
+ "ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
+ .removeAttr( "role" )
+ .removeAttr( "aria-expanded" )
+ .removeAttr( "aria-selected" )
+ .removeAttr( "aria-controls" )
+ .removeAttr( "tabIndex" )
+ .removeUniqueId();
+
+ this._destroyIcons();
+
+ // clean up content panels
+ contents = this.headers.next()
+ .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom " +
+ "ui-accordion-content ui-accordion-content-active ui-state-disabled" )
+ .css( "display", "" )
+ .removeAttr( "role" )
+ .removeAttr( "aria-hidden" )
+ .removeAttr( "aria-labelledby" )
+ .removeUniqueId();
+
+ if ( this.options.heightStyle !== "content" ) {
+ contents.css( "height", "" );
+ }
+ },
+
+ _setOption: function( key, value ) {
+ if ( key === "active" ) {
+ // _activate() will handle invalid values and update this.options
+ this._activate( value );
+ return;
+ }
+
+ if ( key === "event" ) {
+ if ( this.options.event ) {
+ this._off( this.headers, this.options.event );
+ }
+ this._setupEvents( value );
+ }
+
+ this._super( key, value );
+
+ // setting collapsible: false while collapsed; open first panel
+ if ( key === "collapsible" && !value && this.options.active === false ) {
+ this._activate( 0 );
+ }
+
+ if ( key === "icons" ) {
+ this._destroyIcons();
+ if ( value ) {
+ this._createIcons();
+ }
+ }
+
+ // #5332 - opacity doesn't cascade to positioned elements in IE
+ // so we need to add the disabled class to the headers and panels
+ if ( key === "disabled" ) {
+ this.element
+ .toggleClass( "ui-state-disabled", !!value )
+ .attr( "aria-disabled", value );
+ this.headers.add( this.headers.next() )
+ .toggleClass( "ui-state-disabled", !!value );
+ }
+ },
+
+ _keydown: function( event ) {
+ if ( event.altKey || event.ctrlKey ) {
+ return;
+ }
+
+ var keyCode = $.ui.keyCode,
+ length = this.headers.length,
+ currentIndex = this.headers.index( event.target ),
+ toFocus = false;
+
+ switch ( event.keyCode ) {
+ case keyCode.RIGHT:
+ case keyCode.DOWN:
+ toFocus = this.headers[ ( currentIndex + 1 ) % length ];
+ break;
+ case keyCode.LEFT:
+ case keyCode.UP:
+ toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
+ break;
+ case keyCode.SPACE:
+ case keyCode.ENTER:
+ this._eventHandler( event );
+ break;
+ case keyCode.HOME:
+ toFocus = this.headers[ 0 ];
+ break;
+ case keyCode.END:
+ toFocus = this.headers[ length - 1 ];
+ break;
+ }
+
+ if ( toFocus ) {
+ $( event.target ).attr( "tabIndex", -1 );
+ $( toFocus ).attr( "tabIndex", 0 );
+ toFocus.focus();
+ event.preventDefault();
+ }
+ },
+
+ _panelKeyDown: function( event ) {
+ if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
+ $( event.currentTarget ).prev().focus();
+ }
+ },
+
+ refresh: function() {
+ var options = this.options;
+ this._processPanels();
+
+ // was collapsed or no panel
+ if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
+ options.active = false;
+ this.active = $();
+ // active false only when collapsible is true
+ } else if ( options.active === false ) {
+ this._activate( 0 );
+ // was active, but active panel is gone
+ } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
+ // all remaining panel are disabled
+ if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
+ options.active = false;
+ this.active = $();
+ // activate previous panel
+ } else {
+ this._activate( Math.max( 0, options.active - 1 ) );
+ }
+ // was active, active panel still exists
+ } else {
+ // make sure active index is correct
+ options.active = this.headers.index( this.active );
+ }
+
+ this._destroyIcons();
+
+ this._refresh();
+ },
+
+ _processPanels: function() {
+ var prevHeaders = this.headers,
+ prevPanels = this.panels;
+
+ this.headers = this.element.find( this.options.header )
+ .addClass( "ui-accordion-header ui-state-default ui-corner-all" );
+
+ this.panels = this.headers.next()
+ .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
+ .filter( ":not(.ui-accordion-content-active)" )
+ .hide();
+
+ // Avoid memory leaks (#10056)
+ if ( prevPanels ) {
+ this._off( prevHeaders.not( this.headers ) );
+ this._off( prevPanels.not( this.panels ) );
+ }
+ },
+
+ _refresh: function() {
+ var maxHeight,
+ options = this.options,
+ heightStyle = options.heightStyle,
+ parent = this.element.parent();
+
+ this.active = this._findActive( options.active )
+ .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
+ .removeClass( "ui-corner-all" );
+ this.active.next()
+ .addClass( "ui-accordion-content-active" )
+ .show();
+
+ this.headers
+ .attr( "role", "tab" )
+ .each(function() {
+ var header = $( this ),
+ headerId = header.uniqueId().attr( "id" ),
+ panel = header.next(),
+ panelId = panel.uniqueId().attr( "id" );
+ header.attr( "aria-controls", panelId );
+ panel.attr( "aria-labelledby", headerId );
+ })
+ .next()
+ .attr( "role", "tabpanel" );
+
+ this.headers
+ .not( this.active )
+ .attr({
+ "aria-selected": "false",
+ "aria-expanded": "false",
+ tabIndex: -1
+ })
+ .next()
+ .attr({
+ "aria-hidden": "true"
+ })
+ .hide();
+
+ // make sure at least one header is in the tab order
+ if ( !this.active.length ) {
+ this.headers.eq( 0 ).attr( "tabIndex", 0 );
+ } else {
+ this.active.attr({
+ "aria-selected": "true",
+ "aria-expanded": "true",
+ tabIndex: 0
+ })
+ .next()
+ .attr({
+ "aria-hidden": "false"
+ });
+ }
+
+ this._createIcons();
+
+ this._setupEvents( options.event );
+
+ if ( heightStyle === "fill" ) {
+ maxHeight = parent.height();
+ this.element.siblings( ":visible" ).each(function() {
+ var elem = $( this ),
+ position = elem.css( "position" );
+
+ if ( position === "absolute" || position === "fixed" ) {
+ return;
+ }
+ maxHeight -= elem.outerHeight( true );
+ });
+
+ this.headers.each(function() {
+ maxHeight -= $( this ).outerHeight( true );
+ });
+
+ this.headers.next()
+ .each(function() {
+ $( this ).height( Math.max( 0, maxHeight -
+ $( this ).innerHeight() + $( this ).height() ) );
+ })
+ .css( "overflow", "auto" );
+ } else if ( heightStyle === "auto" ) {
+ maxHeight = 0;
+ this.headers.next()
+ .each(function() {
+ maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
+ })
+ .height( maxHeight );
+ }
+ },
+
+ _activate: function( index ) {
+ var active = this._findActive( index )[ 0 ];
+
+ // trying to activate the already active panel
+ if ( active === this.active[ 0 ] ) {
+ return;
+ }
+
+ // trying to collapse, simulate a click on the currently active header
+ active = active || this.active[ 0 ];
+
+ this._eventHandler({
+ target: active,
+ currentTarget: active,
+ preventDefault: $.noop
+ });
+ },
+
+ _findActive: function( selector ) {
+ return typeof selector === "number" ? this.headers.eq( selector ) : $();
+ },
+
+ _setupEvents: function( event ) {
+ var events = {
+ keydown: "_keydown"
+ };
+ if ( event ) {
+ $.each( event.split( " " ), function( index, eventName ) {
+ events[ eventName ] = "_eventHandler";
+ });
+ }
+
+ this._off( this.headers.add( this.headers.next() ) );
+ this._on( this.headers, events );
+ this._on( this.headers.next(), { keydown: "_panelKeyDown" });
+ this._hoverable( this.headers );
+ this._focusable( this.headers );
+ },
+
+ _eventHandler: function( event ) {
+ var options = this.options,
+ active = this.active,
+ clicked = $( event.currentTarget ),
+ clickedIsActive = clicked[ 0 ] === active[ 0 ],
+ collapsing = clickedIsActive && options.collapsible,
+ toShow = collapsing ? $() : clicked.next(),
+ toHide = active.next(),
+ eventData = {
+ oldHeader: active,
+ oldPanel: toHide,
+ newHeader: collapsing ? $() : clicked,
+ newPanel: toShow
+ };
+
+ event.preventDefault();
+
+ if (
+ // click on active header, but not collapsible
+ ( clickedIsActive && !options.collapsible ) ||
+ // allow canceling activation
+ ( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
+ return;
+ }
+
+ options.active = collapsing ? false : this.headers.index( clicked );
+
+ // when the call to ._toggle() comes after the class changes
+ // it causes a very odd bug in IE 8 (see #6720)
+ this.active = clickedIsActive ? $() : clicked;
+ this._toggle( eventData );
+
+ // switch classes
+ // corner classes on the previously active header stay after the animation
+ active.removeClass( "ui-accordion-header-active ui-state-active" );
+ if ( options.icons ) {
+ active.children( ".ui-accordion-header-icon" )
+ .removeClass( options.icons.activeHeader )
+ .addClass( options.icons.header );
+ }
+
+ if ( !clickedIsActive ) {
+ clicked
+ .removeClass( "ui-corner-all" )
+ .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
+ if ( options.icons ) {
+ clicked.children( ".ui-accordion-header-icon" )
+ .removeClass( options.icons.header )
+ .addClass( options.icons.activeHeader );
+ }
+
+ clicked
+ .next()
+ .addClass( "ui-accordion-content-active" );
+ }
+ },
+
+ _toggle: function( data ) {
+ var toShow = data.newPanel,
+ toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
+
+ // handle activating a panel during the animation for another activation
+ this.prevShow.add( this.prevHide ).stop( true, true );
+ this.prevShow = toShow;
+ this.prevHide = toHide;
+
+ if ( this.options.animate ) {
+ this._animate( toShow, toHide, data );
+ } else {
+ toHide.hide();
+ toShow.show();
+ this._toggleComplete( data );
+ }
+
+ toHide.attr({
+ "aria-hidden": "true"
+ });
+ toHide.prev().attr( "aria-selected", "false" );
+ // if we're switching panels, remove the old header from the tab order
+ // if we're opening from collapsed state, remove the previous header from the tab order
+ // if we're collapsing, then keep the collapsing header in the tab order
+ if ( toShow.length && toHide.length ) {
+ toHide.prev().attr({
+ "tabIndex": -1,
+ "aria-expanded": "false"
+ });
+ } else if ( toShow.length ) {
+ this.headers.filter(function() {
+ return $( this ).attr( "tabIndex" ) === 0;
+ })
+ .attr( "tabIndex", -1 );
+ }
+
+ toShow
+ .attr( "aria-hidden", "false" )
+ .prev()
+ .attr({
+ "aria-selected": "true",
+ tabIndex: 0,
+ "aria-expanded": "true"
+ });
+ },
+
+ _animate: function( toShow, toHide, data ) {
+ var total, easing, duration,
+ that = this,
+ adjust = 0,
+ down = toShow.length &&
+ ( !toHide.length || ( toShow.index() < toHide.index() ) ),
+ animate = this.options.animate || {},
+ options = down && animate.down || animate,
+ complete = function() {
+ that._toggleComplete( data );
+ };
+
+ if ( typeof options === "number" ) {
+ duration = options;
+ }
+ if ( typeof options === "string" ) {
+ easing = options;
+ }
+ // fall back from options to animation in case of partial down settings
+ easing = easing || options.easing || animate.easing;
+ duration = duration || options.duration || animate.duration;
+
+ if ( !toHide.length ) {
+ return toShow.animate( this.showProps, duration, easing, complete );
+ }
+ if ( !toShow.length ) {
+ return toHide.animate( this.hideProps, duration, easing, complete );
+ }
+
+ total = toShow.show().outerHeight();
+ toHide.animate( this.hideProps, {
+ duration: duration,
+ easing: easing,
+ step: function( now, fx ) {
+ fx.now = Math.round( now );
+ }
+ });
+ toShow
+ .hide()
+ .animate( this.showProps, {
+ duration: duration,
+ easing: easing,
+ complete: complete,
+ step: function( now, fx ) {
+ fx.now = Math.round( now );
+ if ( fx.prop !== "height" ) {
+ adjust += fx.now;
+ } else if ( that.options.heightStyle !== "content" ) {
+ fx.now = Math.round( total - toHide.outerHeight() - adjust );
+ adjust = 0;
+ }
+ }
+ });
+ },
+
+ _toggleComplete: function( data ) {
+ var toHide = data.oldPanel;
+
+ toHide
+ .removeClass( "ui-accordion-content-active" )
+ .prev()
+ .removeClass( "ui-corner-top" )
+ .addClass( "ui-corner-all" );
+
+ // Work around for rendering bug in IE (#5421)
+ if ( toHide.length ) {
+ toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className;
+ }
+ this._trigger( "activate", null, data );
+ }
+});
+
+
+/*!
+ * jQuery UI Menu 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/menu/
+ */
+
+
+var menu = $.widget( "ui.menu", {
+ version: "1.11.2",
+ defaultElement: "<ul>",
+ delay: 300,
+ options: {
+ icons: {
+ submenu: "ui-icon-carat-1-e"
+ },
+ items: "> *",
+ menus: "ul",
+ position: {
+ my: "left-1 top",
+ at: "right top"
+ },
+ role: "menu",
+
+ // callbacks
+ blur: null,
+ focus: null,
+ select: null
+ },
+
+ _create: function() {
+ this.activeMenu = this.element;
+
+ // Flag used to prevent firing of the click handler
+ // as the event bubbles up through nested menus
+ this.mouseHandled = false;
+ this.element
+ .uniqueId()
+ .addClass( "ui-menu ui-widget ui-widget-content" )
+ .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
+ .attr({
+ role: this.options.role,
+ tabIndex: 0
+ });
+
+ if ( this.options.disabled ) {
+ this.element
+ .addClass( "ui-state-disabled" )
+ .attr( "aria-disabled", "true" );
+ }
+
+ this._on({
+ // Prevent focus from sticking to links inside menu after clicking
+ // them (focus should always stay on UL during navigation).
+ "mousedown .ui-menu-item": function( event ) {
+ event.preventDefault();
+ },
+ "click .ui-menu-item": function( event ) {
+ var target = $( event.target );
+ if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
+ this.select( event );
+
+ // Only set the mouseHandled flag if the event will bubble, see #9469.
+ if ( !event.isPropagationStopped() ) {
+ this.mouseHandled = true;
+ }
+
+ // Open submenu on click
+ if ( target.has( ".ui-menu" ).length ) {
+ this.expand( event );
+ } else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) {
+
+ // Redirect focus to the menu
+ this.element.trigger( "focus", [ true ] );
+
+ // If the active item is on the top level, let it stay active.
+ // Otherwise, blur the active item since it is no longer visible.
+ if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
+ clearTimeout( this.timer );
+ }
+ }
+ }
+ },
+ "mouseenter .ui-menu-item": function( event ) {
+ // Ignore mouse events while typeahead is active, see #10458.
+ // Prevents focusing the wrong item when typeahead causes a scroll while the mouse
+ // is over an item in the menu
+ if ( this.previousFilter ) {
+ return;
+ }
+ var target = $( event.currentTarget );
+ // Remove ui-state-active class from siblings of the newly focused menu item
+ // to avoid a jump caused by adjacent elements both having a class with a border
+ target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" );
+ this.focus( event, target );
+ },
+ mouseleave: "collapseAll",
+ "mouseleave .ui-menu": "collapseAll",
+ focus: function( event, keepActiveItem ) {
+ // If there's already an active item, keep it active
+ // If not, activate the first item
+ var item = this.active || this.element.find( this.options.items ).eq( 0 );
+
+ if ( !keepActiveItem ) {
+ this.focus( event, item );
+ }
+ },
+ blur: function( event ) {
+ this._delay(function() {
+ if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
+ this.collapseAll( event );
+ }
+ });
+ },
+ keydown: "_keydown"
+ });
+
+ this.refresh();
+
+ // Clicks outside of a menu collapse any open menus
+ this._on( this.document, {
+ click: function( event ) {
+ if ( this._closeOnDocumentClick( event ) ) {
+ this.collapseAll( event );
+ }
+
+ // Reset the mouseHandled flag
+ this.mouseHandled = false;
+ }
+ });
+ },
+
+ _destroy: function() {
+ // Destroy (sub)menus
+ this.element
+ .removeAttr( "aria-activedescendant" )
+ .find( ".ui-menu" ).addBack()
+ .removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" )
+ .removeAttr( "role" )
+ .removeAttr( "tabIndex" )
+ .removeAttr( "aria-labelledby" )
+ .removeAttr( "aria-expanded" )
+ .removeAttr( "aria-hidden" )
+ .removeAttr( "aria-disabled" )
+ .removeUniqueId()
+ .show();
+
+ // Destroy menu items
+ this.element.find( ".ui-menu-item" )
+ .removeClass( "ui-menu-item" )
+ .removeAttr( "role" )
+ .removeAttr( "aria-disabled" )
+ .removeUniqueId()
+ .removeClass( "ui-state-hover" )
+ .removeAttr( "tabIndex" )
+ .removeAttr( "role" )
+ .removeAttr( "aria-haspopup" )
+ .children().each( function() {
+ var elem = $( this );
+ if ( elem.data( "ui-menu-submenu-carat" ) ) {
+ elem.remove();
+ }
+ });
+
+ // Destroy menu dividers
+ this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
+ },
+
+ _keydown: function( event ) {
+ var match, prev, character, skip,
+ preventDefault = true;
+
+ switch ( event.keyCode ) {
+ case $.ui.keyCode.PAGE_UP:
+ this.previousPage( event );
+ break;
+ case $.ui.keyCode.PAGE_DOWN:
+ this.nextPage( event );
+ break;
+ case $.ui.keyCode.HOME:
+ this._move( "first", "first", event );
+ break;
+ case $.ui.keyCode.END:
+ this._move( "last", "last", event );
+ break;
+ case $.ui.keyCode.UP:
+ this.previous( event );
+ break;
+ case $.ui.keyCode.DOWN:
+ this.next( event );
+ break;
+ case $.ui.keyCode.LEFT:
+ this.collapse( event );
+ break;
+ case $.ui.keyCode.RIGHT:
+ if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
+ this.expand( event );
+ }
+ break;
+ case $.ui.keyCode.ENTER:
+ case $.ui.keyCode.SPACE:
+ this._activate( event );
+ break;
+ case $.ui.keyCode.ESCAPE:
+ this.collapse( event );
+ break;
+ default:
+ preventDefault = false;
+ prev = this.previousFilter || "";
+ character = String.fromCharCode( event.keyCode );
+ skip = false;
+
+ clearTimeout( this.filterTimer );
+
+ if ( character === prev ) {
+ skip = true;
+ } else {
+ character = prev + character;
+ }
+
+ match = this._filterMenuItems( character );
+ match = skip && match.index( this.active.next() ) !== -1 ?
+ this.active.nextAll( ".ui-menu-item" ) :
+ match;
+
+ // If no matches on the current filter, reset to the last character pressed
+ // to move down the menu to the first item that starts with that character
+ if ( !match.length ) {
+ character = String.fromCharCode( event.keyCode );
+ match = this._filterMenuItems( character );
+ }
+
+ if ( match.length ) {
+ this.focus( event, match );
+ this.previousFilter = character;
+ this.filterTimer = this._delay(function() {
+ delete this.previousFilter;
+ }, 1000 );
+ } else {
+ delete this.previousFilter;
+ }
+ }
+
+ if ( preventDefault ) {
+ event.preventDefault();
+ }
+ },
+
+ _activate: function( event ) {
+ if ( !this.active.is( ".ui-state-disabled" ) ) {
+ if ( this.active.is( "[aria-haspopup='true']" ) ) {
+ this.expand( event );
+ } else {
+ this.select( event );
+ }
+ }
+ },
+
+ refresh: function() {
+ var menus, items,
+ that = this,
+ icon = this.options.icons.submenu,
+ submenus = this.element.find( this.options.menus );
+
+ this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length );
+
+ // Initialize nested menus
+ submenus.filter( ":not(.ui-menu)" )
+ .addClass( "ui-menu ui-widget ui-widget-content ui-front" )
+ .hide()
+ .attr({
+ role: this.options.role,
+ "aria-hidden": "true",
+ "aria-expanded": "false"
+ })
+ .each(function() {
+ var menu = $( this ),
+ item = menu.parent(),
+ submenuCarat = $( "<span>" )
+ .addClass( "ui-menu-icon ui-icon " + icon )
+ .data( "ui-menu-submenu-carat", true );
+
+ item
+ .attr( "aria-haspopup", "true" )
+ .prepend( submenuCarat );
+ menu.attr( "aria-labelledby", item.attr( "id" ) );
+ });
+
+ menus = submenus.add( this.element );
+ items = menus.find( this.options.items );
+
+ // Initialize menu-items containing spaces and/or dashes only as dividers
+ items.not( ".ui-menu-item" ).each(function() {
+ var item = $( this );
+ if ( that._isDivider( item ) ) {
+ item.addClass( "ui-widget-content ui-menu-divider" );
+ }
+ });
+
+ // Don't refresh list items that are already adapted
+ items.not( ".ui-menu-item, .ui-menu-divider" )
+ .addClass( "ui-menu-item" )
+ .uniqueId()
+ .attr({
+ tabIndex: -1,
+ role: this._itemRole()
+ });
+
+ // Add aria-disabled attribute to any disabled menu item
+ items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
+
+ // If the active item has been removed, blur the menu
+ if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
+ this.blur();
+ }
+ },
+
+ _itemRole: function() {
+ return {
+ menu: "menuitem",
+ listbox: "option"
+ }[ this.options.role ];
+ },
+
+ _setOption: function( key, value ) {
+ if ( key === "icons" ) {
+ this.element.find( ".ui-menu-icon" )
+ .removeClass( this.options.icons.submenu )
+ .addClass( value.submenu );
+ }
+ if ( key === "disabled" ) {
+ this.element
+ .toggleClass( "ui-state-disabled", !!value )
+ .attr( "aria-disabled", value );
+ }
+ this._super( key, value );
+ },
+
+ focus: function( event, item ) {
+ var nested, focused;
+ this.blur( event, event && event.type === "focus" );
+
+ this._scrollIntoView( item );
+
+ this.active = item.first();
+ focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" );
+ // Only update aria-activedescendant if there's a role
+ // otherwise we assume focus is managed elsewhere
+ if ( this.options.role ) {
+ this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
+ }
+
+ // Highlight active parent menu item, if any
+ this.active
+ .parent()
+ .closest( ".ui-menu-item" )
+ .addClass( "ui-state-active" );
+
+ if ( event && event.type === "keydown" ) {
+ this._close();
+ } else {
+ this.timer = this._delay(function() {
+ this._close();
+ }, this.delay );
+ }
+
+ nested = item.children( ".ui-menu" );
+ if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
+ this._startOpening(nested);
+ }
+ this.activeMenu = item.parent();
+
+ this._trigger( "focus", event, { item: item } );
+ },
+
+ _scrollIntoView: function( item ) {
+ var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
+ if ( this._hasScroll() ) {
+ borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
+ paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
+ offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
+ scroll = this.activeMenu.scrollTop();
+ elementHeight = this.activeMenu.height();
+ itemHeight = item.outerHeight();
+
+ if ( offset < 0 ) {
+ this.activeMenu.scrollTop( scroll + offset );
+ } else if ( offset + itemHeight > elementHeight ) {
+ this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
+ }
+ }
+ },
+
+ blur: function( event, fromFocus ) {
+ if ( !fromFocus ) {
+ clearTimeout( this.timer );
+ }
+
+ if ( !this.active ) {
+ return;
+ }
+
+ this.active.removeClass( "ui-state-focus" );
+ this.active = null;
+
+ this._trigger( "blur", event, { item: this.active } );
+ },
+
+ _startOpening: function( submenu ) {
+ clearTimeout( this.timer );
+
+ // Don't open if already open fixes a Firefox bug that caused a .5 pixel
+ // shift in the submenu position when mousing over the carat icon
+ if ( submenu.attr( "aria-hidden" ) !== "true" ) {
+ return;
+ }
+
+ this.timer = this._delay(function() {
+ this._close();
+ this._open( submenu );
+ }, this.delay );
+ },
+
+ _open: function( submenu ) {
+ var position = $.extend({
+ of: this.active
+ }, this.options.position );
+
+ clearTimeout( this.timer );
+ this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
+ .hide()
+ .attr( "aria-hidden", "true" );
+
+ submenu
+ .show()
+ .removeAttr( "aria-hidden" )
+ .attr( "aria-expanded", "true" )
+ .position( position );
+ },
+
+ collapseAll: function( event, all ) {
+ clearTimeout( this.timer );
+ this.timer = this._delay(function() {
+ // If we were passed an event, look for the submenu that contains the event
+ var currentMenu = all ? this.element :
+ $( event && event.target ).closest( this.element.find( ".ui-menu" ) );
+
+ // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
+ if ( !currentMenu.length ) {
+ currentMenu = this.element;
+ }
+
+ this._close( currentMenu );
+
+ this.blur( event );
+ this.activeMenu = currentMenu;
+ }, this.delay );
+ },
+
+ // With no arguments, closes the currently active menu - if nothing is active
+ // it closes all menus. If passed an argument, it will search for menus BELOW
+ _close: function( startMenu ) {
+ if ( !startMenu ) {
+ startMenu = this.active ? this.active.parent() : this.element;
+ }
+
+ startMenu
+ .find( ".ui-menu" )
+ .hide()
+ .attr( "aria-hidden", "true" )
+ .attr( "aria-expanded", "false" )
+ .end()
+ .find( ".ui-state-active" ).not( ".ui-state-focus" )
+ .removeClass( "ui-state-active" );
+ },
+
+ _closeOnDocumentClick: function( event ) {
+ return !$( event.target ).closest( ".ui-menu" ).length;
+ },
+
+ _isDivider: function( item ) {
+
+ // Match hyphen, em dash, en dash
+ return !/[^\-\u2014\u2013\s]/.test( item.text() );
+ },
+
+ collapse: function( event ) {
+ var newItem = this.active &&
+ this.active.parent().closest( ".ui-menu-item", this.element );
+ if ( newItem && newItem.length ) {
+ this._close();
+ this.focus( event, newItem );
+ }
+ },
+
+ expand: function( event ) {
+ var newItem = this.active &&
+ this.active
+ .children( ".ui-menu " )
+ .find( this.options.items )
+ .first();
+
+ if ( newItem && newItem.length ) {
+ this._open( newItem.parent() );
+
+ // Delay so Firefox will not hide activedescendant change in expanding submenu from AT
+ this._delay(function() {
+ this.focus( event, newItem );
+ });
+ }
+ },
+
+ next: function( event ) {
+ this._move( "next", "first", event );
+ },
+
+ previous: function( event ) {
+ this._move( "prev", "last", event );
+ },
+
+ isFirstItem: function() {
+ return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
+ },
+
+ isLastItem: function() {
+ return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
+ },
+
+ _move: function( direction, filter, event ) {
+ var next;
+ if ( this.active ) {
+ if ( direction === "first" || direction === "last" ) {
+ next = this.active
+ [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
+ .eq( -1 );
+ } else {
+ next = this.active
+ [ direction + "All" ]( ".ui-menu-item" )
+ .eq( 0 );
+ }
+ }
+ if ( !next || !next.length || !this.active ) {
+ next = this.activeMenu.find( this.options.items )[ filter ]();
+ }
+
+ this.focus( event, next );
+ },
+
+ nextPage: function( event ) {
+ var item, base, height;
+
+ if ( !this.active ) {
+ this.next( event );
+ return;
+ }
+ if ( this.isLastItem() ) {
+ return;
+ }
+ if ( this._hasScroll() ) {
+ base = this.active.offset().top;
+ height = this.element.height();
+ this.active.nextAll( ".ui-menu-item" ).each(function() {
+ item = $( this );
+ return item.offset().top - base - height < 0;
+ });
+
+ this.focus( event, item );
+ } else {
+ this.focus( event, this.activeMenu.find( this.options.items )
+ [ !this.active ? "first" : "last" ]() );
+ }
+ },
+
+ previousPage: function( event ) {
+ var item, base, height;
+ if ( !this.active ) {
+ this.next( event );
+ return;
+ }
+ if ( this.isFirstItem() ) {
+ return;
+ }
+ if ( this._hasScroll() ) {
+ base = this.active.offset().top;
+ height = this.element.height();
+ this.active.prevAll( ".ui-menu-item" ).each(function() {
+ item = $( this );
+ return item.offset().top - base + height > 0;
+ });
+
+ this.focus( event, item );
+ } else {
+ this.focus( event, this.activeMenu.find( this.options.items ).first() );
+ }
+ },
+
+ _hasScroll: function() {
+ return this.element.outerHeight() < this.element.prop( "scrollHeight" );
+ },
+
+ select: function( event ) {
+ // TODO: It should never be possible to not have an active item at this
+ // point, but the tests don't trigger mouseenter before click.
+ this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
+ var ui = { item: this.active };
+ if ( !this.active.has( ".ui-menu" ).length ) {
+ this.collapseAll( event, true );
+ }
+ this._trigger( "select", event, ui );
+ },
+
+ _filterMenuItems: function(character) {
+ var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
+ regex = new RegExp( "^" + escapedCharacter, "i" );
+
+ return this.activeMenu
+ .find( this.options.items )
+
+ // Only match on items, not dividers or other content (#10571)
+ .filter( ".ui-menu-item" )
+ .filter(function() {
+ return regex.test( $.trim( $( this ).text() ) );
+ });
+ }
+});
+
+
+/*!
+ * jQuery UI Autocomplete 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/autocomplete/
+ */
+
+
+$.widget( "ui.autocomplete", {
+ version: "1.11.2",
+ defaultElement: "<input>",
+ options: {
+ appendTo: null,
+ autoFocus: false,
+ delay: 300,
+ minLength: 1,
+ position: {
+ my: "left top",
+ at: "left bottom",
+ collision: "none"
+ },
+ source: null,
+
+ // callbacks
+ change: null,
+ close: null,
+ focus: null,
+ open: null,
+ response: null,
+ search: null,
+ select: null
+ },
+
+ requestIndex: 0,
+ pending: 0,
+
+ _create: function() {
+ // Some browsers only repeat keydown events, not keypress events,
+ // so we use the suppressKeyPress flag to determine if we've already
+ // handled the keydown event. #7269
+ // Unfortunately the code for & in keypress is the same as the up arrow,
+ // so we use the suppressKeyPressRepeat flag to avoid handling keypress
+ // events when we know the keydown event was used to modify the
+ // search term. #7799
+ var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
+ nodeName = this.element[ 0 ].nodeName.toLowerCase(),
+ isTextarea = nodeName === "textarea",
+ isInput = nodeName === "input";
+
+ this.isMultiLine =
+ // Textareas are always multi-line
+ isTextarea ? true :
+ // Inputs are always single-line, even if inside a contentEditable element
+ // IE also treats inputs as contentEditable
+ isInput ? false :
+ // All other element types are determined by whether or not they're contentEditable
+ this.element.prop( "isContentEditable" );
+
+ this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
+ this.isNewMenu = true;
+
+ this.element
+ .addClass( "ui-autocomplete-input" )
+ .attr( "autocomplete", "off" );
+
+ this._on( this.element, {
+ keydown: function( event ) {
+ if ( this.element.prop( "readOnly" ) ) {
+ suppressKeyPress = true;
+ suppressInput = true;
+ suppressKeyPressRepeat = true;
+ return;
+ }
+
+ suppressKeyPress = false;
+ suppressInput = false;
+ suppressKeyPressRepeat = false;
+ var keyCode = $.ui.keyCode;
+ switch ( event.keyCode ) {
+ case keyCode.PAGE_UP:
+ suppressKeyPress = true;
+ this._move( "previousPage", event );
+ break;
+ case keyCode.PAGE_DOWN:
+ suppressKeyPress = true;
+ this._move( "nextPage", event );
+ break;
+ case keyCode.UP:
+ suppressKeyPress = true;
+ this._keyEvent( "previous", event );
+ break;
+ case keyCode.DOWN:
+ suppressKeyPress = true;
+ this._keyEvent( "next", event );
+ break;
+ case keyCode.ENTER:
+ // when menu is open and has focus
+ if ( this.menu.active ) {
+ // #6055 - Opera still allows the keypress to occur
+ // which causes forms to submit
+ suppressKeyPress = true;
+ event.preventDefault();
+ this.menu.select( event );
+ }
+ break;
+ case keyCode.TAB:
+ if ( this.menu.active ) {
+ this.menu.select( event );
+ }
+ break;
+ case keyCode.ESCAPE:
+ if ( this.menu.element.is( ":visible" ) ) {
+ if ( !this.isMultiLine ) {
+ this._value( this.term );
+ }
+ this.close( event );
+ // Different browsers have different default behavior for escape
+ // Single press can mean undo or clear
+ // Double press in IE means clear the whole form
+ event.preventDefault();
+ }
+ break;
+ default:
+ suppressKeyPressRepeat = true;
+ // search timeout should be triggered before the input value is changed
+ this._searchTimeout( event );
+ break;
+ }
+ },
+ keypress: function( event ) {
+ if ( suppressKeyPress ) {
+ suppressKeyPress = false;
+ if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
+ event.preventDefault();
+ }
+ return;
+ }
+ if ( suppressKeyPressRepeat ) {
+ return;
+ }
+
+ // replicate some key handlers to allow them to repeat in Firefox and Opera
+ var keyCode = $.ui.keyCode;
+ switch ( event.keyCode ) {
+ case keyCode.PAGE_UP:
+ this._move( "previousPage", event );
+ break;
+ case keyCode.PAGE_DOWN:
+ this._move( "nextPage", event );
+ break;
+ case keyCode.UP:
+ this._keyEvent( "previous", event );
+ break;
+ case keyCode.DOWN:
+ this._keyEvent( "next", event );
+ break;
+ }
+ },
+ input: function( event ) {
+ if ( suppressInput ) {
+ suppressInput = false;
+ event.preventDefault();
+ return;
+ }
+ this._searchTimeout( event );
+ },
+ focus: function() {
+ this.selectedItem = null;
+ this.previous = this._value();
+ },
+ blur: function( event ) {
+ if ( this.cancelBlur ) {
+ delete this.cancelBlur;
+ return;
+ }
+
+ clearTimeout( this.searching );
+ this.close( event );
+ this._change( event );
+ }
+ });
+
+ this._initSource();
+ this.menu = $( "<ul>" )
+ .addClass( "ui-autocomplete ui-front" )
+ .appendTo( this._appendTo() )
+ .menu({
+ // disable ARIA support, the live region takes care of that
+ role: null
+ })
+ .hide()
+ .menu( "instance" );
+
+ this._on( this.menu.element, {
+ mousedown: function( event ) {
+ // prevent moving focus out of the text field
+ event.preventDefault();
+
+ // IE doesn't prevent moving focus even with event.preventDefault()
+ // so we set a flag to know when we should ignore the blur event
+ this.cancelBlur = true;
+ this._delay(function() {
+ delete this.cancelBlur;
+ });
+
+ // clicking on the scrollbar causes focus to shift to the body
+ // but we can't detect a mouseup or a click immediately afterward
+ // so we have to track the next mousedown and close the menu if
+ // the user clicks somewhere outside of the autocomplete
+ var menuElement = this.menu.element[ 0 ];
+ if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
+ this._delay(function() {
+ var that = this;
+ this.document.one( "mousedown", function( event ) {
+ if ( event.target !== that.element[ 0 ] &&
+ event.target !== menuElement &&
+ !$.contains( menuElement, event.target ) ) {
+ that.close();
+ }
+ });
+ });
+ }
+ },
+ menufocus: function( event, ui ) {
+ var label, item;
+ // support: Firefox
+ // Prevent accidental activation of menu items in Firefox (#7024 #9118)
+ if ( this.isNewMenu ) {
+ this.isNewMenu = false;
+ if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
+ this.menu.blur();
+
+ this.document.one( "mousemove", function() {
+ $( event.target ).trigger( event.originalEvent );
+ });
+
+ return;
+ }
+ }
+
+ item = ui.item.data( "ui-autocomplete-item" );
+ if ( false !== this._trigger( "focus", event, { item: item } ) ) {
+ // use value to match what will end up in the input, if it was a key event
+ if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
+ this._value( item.value );
+ }
+ }
+
+ // Announce the value in the liveRegion
+ label = ui.item.attr( "aria-label" ) || item.value;
+ if ( label && $.trim( label ).length ) {
+ this.liveRegion.children().hide();
+ $( "<div>" ).text( label ).appendTo( this.liveRegion );
+ }
+ },
+ menuselect: function( event, ui ) {
+ var item = ui.item.data( "ui-autocomplete-item" ),
+ previous = this.previous;
+
+ // only trigger when focus was lost (click on menu)
+ if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) {
+ this.element.focus();
+ this.previous = previous;
+ // #6109 - IE triggers two focus events and the second
+ // is asynchronous, so we need to reset the previous
+ // term synchronously and asynchronously :-(
+ this._delay(function() {
+ this.previous = previous;
+ this.selectedItem = item;
+ });
+ }
+
+ if ( false !== this._trigger( "select", event, { item: item } ) ) {
+ this._value( item.value );
+ }
+ // reset the term after the select event
+ // this allows custom select handling to work properly
+ this.term = this._value();
+
+ this.close( event );
+ this.selectedItem = item;
+ }
+ });
+
+ this.liveRegion = $( "<span>", {
+ role: "status",
+ "aria-live": "assertive",
+ "aria-relevant": "additions"
+ })
+ .addClass( "ui-helper-hidden-accessible" )
+ .appendTo( this.document[ 0 ].body );
+
+ // turning off autocomplete prevents the browser from remembering the
+ // value when navigating through history, so we re-enable autocomplete
+ // if the page is unloaded before the widget is destroyed. #7790
+ this._on( this.window, {
+ beforeunload: function() {
+ this.element.removeAttr( "autocomplete" );
+ }
+ });
+ },
+
+ _destroy: function() {
+ clearTimeout( this.searching );
+ this.element
+ .removeClass( "ui-autocomplete-input" )
+ .removeAttr( "autocomplete" );
+ this.menu.element.remove();
+ this.liveRegion.remove();
+ },
+
+ _setOption: function( key, value ) {
+ this._super( key, value );
+ if ( key === "source" ) {
+ this._initSource();
+ }
+ if ( key === "appendTo" ) {
+ this.menu.element.appendTo( this._appendTo() );
+ }
+ if ( key === "disabled" && value && this.xhr ) {
+ this.xhr.abort();
+ }
+ },
+
+ _appendTo: function() {
+ var element = this.options.appendTo;
+
+ if ( element ) {
+ element = element.jquery || element.nodeType ?
+ $( element ) :
+ this.document.find( element ).eq( 0 );
+ }
+
+ if ( !element || !element[ 0 ] ) {
+ element = this.element.closest( ".ui-front" );
+ }
+
+ if ( !element.length ) {
+ element = this.document[ 0 ].body;
+ }
+
+ return element;
+ },
+
+ _initSource: function() {
+ var array, url,
+ that = this;
+ if ( $.isArray( this.options.source ) ) {
+ array = this.options.source;
+ this.source = function( request, response ) {
+ response( $.ui.autocomplete.filter( array, request.term ) );
+ };
+ } else if ( typeof this.options.source === "string" ) {
+ url = this.options.source;
+ this.source = function( request, response ) {
+ if ( that.xhr ) {
+ that.xhr.abort();
+ }
+ that.xhr = $.ajax({
+ url: url,
+ data: request,
+ dataType: "json",
+ success: function( data ) {
+ response( data );
+ },
+ error: function() {
+ response([]);
+ }
+ });
+ };
+ } else {
+ this.source = this.options.source;
+ }
+ },
+
+ _searchTimeout: function( event ) {
+ clearTimeout( this.searching );
+ this.searching = this._delay(function() {
+
+ // Search if the value has changed, or if the user retypes the same value (see #7434)
+ var equalValues = this.term === this._value(),
+ menuVisible = this.menu.element.is( ":visible" ),
+ modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
+
+ if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
+ this.selectedItem = null;
+ this.search( null, event );
+ }
+ }, this.options.delay );
+ },
+
+ search: function( value, event ) {
+ value = value != null ? value : this._value();
+
+ // always save the actual value, not the one passed as an argument
+ this.term = this._value();
+
+ if ( value.length < this.options.minLength ) {
+ return this.close( event );
+ }
+
+ if ( this._trigger( "search", event ) === false ) {
+ return;
+ }
+
+ return this._search( value );
+ },
+
+ _search: function( value ) {
+ this.pending++;
+ this.element.addClass( "ui-autocomplete-loading" );
+ this.cancelSearch = false;
+
+ this.source( { term: value }, this._response() );
+ },
+
+ _response: function() {
+ var index = ++this.requestIndex;
+
+ return $.proxy(function( content ) {
+ if ( index === this.requestIndex ) {
+ this.__response( content );
+ }
+
+ this.pending--;
+ if ( !this.pending ) {
+ this.element.removeClass( "ui-autocomplete-loading" );
+ }
+ }, this );
+ },
+
+ __response: function( content ) {
+ if ( content ) {
+ content = this._normalize( content );
+ }
+ this._trigger( "response", null, { content: content } );
+ if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
+ this._suggest( content );
+ this._trigger( "open" );
+ } else {
+ // use ._close() instead of .close() so we don't cancel future searches
+ this._close();
+ }
+ },
+
+ close: function( event ) {
+ this.cancelSearch = true;
+ this._close( event );
+ },
+
+ _close: function( event ) {
+ if ( this.menu.element.is( ":visible" ) ) {
+ this.menu.element.hide();
+ this.menu.blur();
+ this.isNewMenu = true;
+ this._trigger( "close", event );
+ }
+ },
+
+ _change: function( event ) {
+ if ( this.previous !== this._value() ) {
+ this._trigger( "change", event, { item: this.selectedItem } );
+ }
+ },
+
+ _normalize: function( items ) {
+ // assume all items have the right format when the first item is complete
+ if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
+ return items;
+ }
+ return $.map( items, function( item ) {
+ if ( typeof item === "string" ) {
+ return {
+ label: item,
+ value: item
+ };
+ }
+ return $.extend( {}, item, {
+ label: item.label || item.value,
+ value: item.value || item.label
+ });
+ });
+ },
+
+ _suggest: function( items ) {
+ var ul = this.menu.element.empty();
+ this._renderMenu( ul, items );
+ this.isNewMenu = true;
+ this.menu.refresh();
+
+ // size and position menu
+ ul.show();
+ this._resizeMenu();
+ ul.position( $.extend({
+ of: this.element
+ }, this.options.position ) );
+
+ if ( this.options.autoFocus ) {
+ this.menu.next();
+ }
+ },
+
+ _resizeMenu: function() {
+ var ul = this.menu.element;
+ ul.outerWidth( Math.max(
+ // Firefox wraps long text (possibly a rounding bug)
+ // so we add 1px to avoid the wrapping (#7513)
+ ul.width( "" ).outerWidth() + 1,
+ this.element.outerWidth()
+ ) );
+ },
+
+ _renderMenu: function( ul, items ) {
+ var that = this;
+ $.each( items, function( index, item ) {
+ that._renderItemData( ul, item );
+ });
+ },
+
+ _renderItemData: function( ul, item ) {
+ return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
+ },
+
+ _renderItem: function( ul, item ) {
+ return $( "<li>" ).text( item.label ).appendTo( ul );
+ },
+
+ _move: function( direction, event ) {
+ if ( !this.menu.element.is( ":visible" ) ) {
+ this.search( null, event );
+ return;
+ }
+ if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
+ this.menu.isLastItem() && /^next/.test( direction ) ) {
+
+ if ( !this.isMultiLine ) {
+ this._value( this.term );
+ }
+
+ this.menu.blur();
+ return;
+ }
+ this.menu[ direction ]( event );
+ },
+
+ widget: function() {
+ return this.menu.element;
+ },
+
+ _value: function() {
+ return this.valueMethod.apply( this.element, arguments );
+ },
+
+ _keyEvent: function( keyEvent, event ) {
+ if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
+ this._move( keyEvent, event );
+
+ // prevents moving cursor to beginning/end of the text field in some browsers
+ event.preventDefault();
+ }
+ }
+});
+
+$.extend( $.ui.autocomplete, {
+ escapeRegex: function( value ) {
+ return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
+ },
+ filter: function( array, term ) {
+ var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
+ return $.grep( array, function( value ) {
+ return matcher.test( value.label || value.value || value );
+ });
+ }
+});
+
+// live region extension, adding a `messages` option
+// NOTE: This is an experimental API. We are still investigating
+// a full solution for string manipulation and internationalization.
+$.widget( "ui.autocomplete", $.ui.autocomplete, {
+ options: {
+ messages: {
+ noResults: "No search results.",
+ results: function( amount ) {
+ return amount + ( amount > 1 ? " results are" : " result is" ) +
+ " available, use up and down arrow keys to navigate.";
+ }
+ }
+ },
+
+ __response: function( content ) {
+ var message;
+ this._superApply( arguments );
+ if ( this.options.disabled || this.cancelSearch ) {
+ return;
+ }
+ if ( content && content.length ) {
+ message = this.options.messages.results( content.length );
+ } else {
+ message = this.options.messages.noResults;
+ }
+ this.liveRegion.children().hide();
+ $( "<div>" ).text( message ).appendTo( this.liveRegion );
+ }
+});
+
+var autocomplete = $.ui.autocomplete;
+
+
+/*!
+ * jQuery UI Button 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/button/
+ */
+
+
+var lastActive,
+ baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
+ typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
+ formResetHandler = function() {
+ var form = $( this );
+ setTimeout(function() {
+ form.find( ":ui-button" ).button( "refresh" );
+ }, 1 );
+ },
+ radioGroup = function( radio ) {
+ var name = radio.name,
+ form = radio.form,
+ radios = $( [] );
+ if ( name ) {
+ name = name.replace( /'/g, "\\'" );
+ if ( form ) {
+ radios = $( form ).find( "[name='" + name + "'][type=radio]" );
+ } else {
+ radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument )
+ .filter(function() {
+ return !this.form;
+ });
+ }
+ }
+ return radios;
+ };
+
+$.widget( "ui.button", {
+ version: "1.11.2",
+ defaultElement: "<button>",
+ options: {
+ disabled: null,
+ text: true,
+ label: null,
+ icons: {
+ primary: null,
+ secondary: null
+ }
+ },
+ _create: function() {
+ this.element.closest( "form" )
+ .unbind( "reset" + this.eventNamespace )
+ .bind( "reset" + this.eventNamespace, formResetHandler );
+
+ if ( typeof this.options.disabled !== "boolean" ) {
+ this.options.disabled = !!this.element.prop( "disabled" );
+ } else {
+ this.element.prop( "disabled", this.options.disabled );
+ }
+
+ this._determineButtonType();
+ this.hasTitle = !!this.buttonElement.attr( "title" );
+
+ var that = this,
+ options = this.options,
+ toggleButton = this.type === "checkbox" || this.type === "radio",
+ activeClass = !toggleButton ? "ui-state-active" : "";
+
+ if ( options.label === null ) {
+ options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
+ }
+
+ this._hoverable( this.buttonElement );
+
+ this.buttonElement
+ .addClass( baseClasses )
+ .attr( "role", "button" )
+ .bind( "mouseenter" + this.eventNamespace, function() {
+ if ( options.disabled ) {
+ return;
+ }
+ if ( this === lastActive ) {
+ $( this ).addClass( "ui-state-active" );
+ }
+ })
+ .bind( "mouseleave" + this.eventNamespace, function() {
+ if ( options.disabled ) {
+ return;
+ }
+ $( this ).removeClass( activeClass );
+ })
+ .bind( "click" + this.eventNamespace, function( event ) {
+ if ( options.disabled ) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ });
+
+ // Can't use _focusable() because the element that receives focus
+ // and the element that gets the ui-state-focus class are different
+ this._on({
+ focus: function() {
+ this.buttonElement.addClass( "ui-state-focus" );
+ },
+ blur: function() {
+ this.buttonElement.removeClass( "ui-state-focus" );
+ }
+ });
+
+ if ( toggleButton ) {
+ this.element.bind( "change" + this.eventNamespace, function() {
+ that.refresh();
+ });
+ }
+
+ if ( this.type === "checkbox" ) {
+ this.buttonElement.bind( "click" + this.eventNamespace, function() {
+ if ( options.disabled ) {
+ return false;
+ }
+ });
+ } else if ( this.type === "radio" ) {
+ this.buttonElement.bind( "click" + this.eventNamespace, function() {
+ if ( options.disabled ) {
+ return false;
+ }
+ $( this ).addClass( "ui-state-active" );
+ that.buttonElement.attr( "aria-pressed", "true" );
+
+ var radio = that.element[ 0 ];
+ radioGroup( radio )
+ .not( radio )
+ .map(function() {
+ return $( this ).button( "widget" )[ 0 ];
+ })
+ .removeClass( "ui-state-active" )
+ .attr( "aria-pressed", "false" );
+ });
+ } else {
+ this.buttonElement
+ .bind( "mousedown" + this.eventNamespace, function() {
+ if ( options.disabled ) {
+ return false;
+ }
+ $( this ).addClass( "ui-state-active" );
+ lastActive = this;
+ that.document.one( "mouseup", function() {
+ lastActive = null;
+ });
+ })
+ .bind( "mouseup" + this.eventNamespace, function() {
+ if ( options.disabled ) {
+ return false;
+ }
+ $( this ).removeClass( "ui-state-active" );
+ })
+ .bind( "keydown" + this.eventNamespace, function(event) {
+ if ( options.disabled ) {
+ return false;
+ }
+ if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
+ $( this ).addClass( "ui-state-active" );
+ }
+ })
+ // see #8559, we bind to blur here in case the button element loses
+ // focus between keydown and keyup, it would be left in an "active" state
+ .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
+ $( this ).removeClass( "ui-state-active" );
+ });
+
+ if ( this.buttonElement.is("a") ) {
+ this.buttonElement.keyup(function(event) {
+ if ( event.keyCode === $.ui.keyCode.SPACE ) {
+ // TODO pass through original event correctly (just as 2nd argument doesn't work)
+ $( this ).click();
+ }
+ });
+ }
+ }
+
+ this._setOption( "disabled", options.disabled );
+ this._resetButton();
+ },
+
+ _determineButtonType: function() {
+ var ancestor, labelSelector, checked;
+
+ if ( this.element.is("[type=checkbox]") ) {
+ this.type = "checkbox";
+ } else if ( this.element.is("[type=radio]") ) {
+ this.type = "radio";
+ } else if ( this.element.is("input") ) {
+ this.type = "input";
+ } else {
+ this.type = "button";
+ }
+
+ if ( this.type === "checkbox" || this.type === "radio" ) {
+ // we don't search against the document in case the element
+ // is disconnected from the DOM
+ ancestor = this.element.parents().last();
+ labelSelector = "label[for='" + this.element.attr("id") + "']";
+ this.buttonElement = ancestor.find( labelSelector );
+ if ( !this.buttonElement.length ) {
+ ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
+ this.buttonElement = ancestor.filter( labelSelector );
+ if ( !this.buttonElement.length ) {
+ this.buttonElement = ancestor.find( labelSelector );
+ }
+ }
+ this.element.addClass( "ui-helper-hidden-accessible" );
+
+ checked = this.element.is( ":checked" );
+ if ( checked ) {
+ this.buttonElement.addClass( "ui-state-active" );
+ }
+ this.buttonElement.prop( "aria-pressed", checked );
+ } else {
+ this.buttonElement = this.element;
+ }
+ },
+
+ widget: function() {
+ return this.buttonElement;
+ },
+
+ _destroy: function() {
+ this.element
+ .removeClass( "ui-helper-hidden-accessible" );
+ this.buttonElement
+ .removeClass( baseClasses + " ui-state-active " + typeClasses )
+ .removeAttr( "role" )
+ .removeAttr( "aria-pressed" )
+ .html( this.buttonElement.find(".ui-button-text").html() );
+
+ if ( !this.hasTitle ) {
+ this.buttonElement.removeAttr( "title" );
+ }
+ },
+
+ _setOption: function( key, value ) {
+ this._super( key, value );
+ if ( key === "disabled" ) {
+ this.widget().toggleClass( "ui-state-disabled", !!value );
+ this.element.prop( "disabled", !!value );
+ if ( value ) {
+ if ( this.type === "checkbox" || this.type === "radio" ) {
+ this.buttonElement.removeClass( "ui-state-focus" );
+ } else {
+ this.buttonElement.removeClass( "ui-state-focus ui-state-active" );
+ }
+ }
+ return;
+ }
+ this._resetButton();
+ },
+
+ refresh: function() {
+ //See #8237 & #8828
+ var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );
+
+ if ( isDisabled !== this.options.disabled ) {
+ this._setOption( "disabled", isDisabled );
+ }
+ if ( this.type === "radio" ) {
+ radioGroup( this.element[0] ).each(function() {
+ if ( $( this ).is( ":checked" ) ) {
+ $( this ).button( "widget" )
+ .addClass( "ui-state-active" )
+ .attr( "aria-pressed", "true" );
+ } else {
+ $( this ).button( "widget" )
+ .removeClass( "ui-state-active" )
+ .attr( "aria-pressed", "false" );
+ }
+ });
+ } else if ( this.type === "checkbox" ) {
+ if ( this.element.is( ":checked" ) ) {
+ this.buttonElement
+ .addClass( "ui-state-active" )
+ .attr( "aria-pressed", "true" );
+ } else {
+ this.buttonElement
+ .removeClass( "ui-state-active" )
+ .attr( "aria-pressed", "false" );
+ }
+ }
+ },
+
+ _resetButton: function() {
+ if ( this.type === "input" ) {
+ if ( this.options.label ) {
+ this.element.val( this.options.label );
+ }
+ return;
+ }
+ var buttonElement = this.buttonElement.removeClass( typeClasses ),
+ buttonText = $( "<span></span>", this.document[0] )
+ .addClass( "ui-button-text" )
+ .html( this.options.label )
+ .appendTo( buttonElement.empty() )
+ .text(),
+ icons = this.options.icons,
+ multipleIcons = icons.primary && icons.secondary,
+ buttonClasses = [];
+
+ if ( icons.primary || icons.secondary ) {
+ if ( this.options.text ) {
+ buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
+ }
+
+ if ( icons.primary ) {
+ buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
+ }
+
+ if ( icons.secondary ) {
+ buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
+ }
+
+ if ( !this.options.text ) {
+ buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );
+
+ if ( !this.hasTitle ) {
+ buttonElement.attr( "title", $.trim( buttonText ) );
+ }
+ }
+ } else {
+ buttonClasses.push( "ui-button-text-only" );
+ }
+ buttonElement.addClass( buttonClasses.join( " " ) );
+ }
+});
+
+$.widget( "ui.buttonset", {
+ version: "1.11.2",
+ options: {
+ items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
+ },
+
+ _create: function() {
+ this.element.addClass( "ui-buttonset" );
+ },
+
+ _init: function() {
+ this.refresh();
+ },
+
+ _setOption: function( key, value ) {
+ if ( key === "disabled" ) {
+ this.buttons.button( "option", key, value );
+ }
+
+ this._super( key, value );
+ },
+
+ refresh: function() {
+ var rtl = this.element.css( "direction" ) === "rtl",
+ allButtons = this.element.find( this.options.items ),
+ existingButtons = allButtons.filter( ":ui-button" );
+
+ // Initialize new buttons
+ allButtons.not( ":ui-button" ).button();
+
+ // Refresh existing buttons
+ existingButtons.button( "refresh" );
+
+ this.buttons = allButtons
+ .map(function() {
+ return $( this ).button( "widget" )[ 0 ];
+ })
+ .removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
+ .filter( ":first" )
+ .addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
+ .end()
+ .filter( ":last" )
+ .addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
+ .end()
+ .end();
+ },
+
+ _destroy: function() {
+ this.element.removeClass( "ui-buttonset" );
+ this.buttons
+ .map(function() {
+ return $( this ).button( "widget" )[ 0 ];
+ })
+ .removeClass( "ui-corner-left ui-corner-right" )
+ .end()
+ .button( "destroy" );
+ }
+});
+
+var button = $.ui.button;
+
+
+/*!
+ * jQuery UI Datepicker 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/datepicker/
+ */
+
+
+$.extend($.ui, { datepicker: { version: "1.11.2" } });
+
+var datepicker_instActive;
+
+function datepicker_getZindex( elem ) {
+ var position, value;
+ while ( elem.length && elem[ 0 ] !== document ) {
+ // Ignore z-index if position is set to a value where z-index is ignored by the browser
+ // This makes behavior of this function consistent across browsers
+ // WebKit always returns auto if the element is positioned
+ position = elem.css( "position" );
+ if ( position === "absolute" || position === "relative" || position === "fixed" ) {
+ // IE returns 0 when zIndex is not specified
+ // other browsers return a string
+ // we ignore the case of nested elements with an explicit value of 0
+ // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
+ value = parseInt( elem.css( "zIndex" ), 10 );
+ if ( !isNaN( value ) && value !== 0 ) {
+ return value;
+ }
+ }
+ elem = elem.parent();
+ }
+
+ return 0;
+}
+/* Date picker manager.
+ Use the singleton instance of this class, $.datepicker, to interact with the date picker.
+ Settings for (groups of) date pickers are maintained in an instance object,
+ allowing multiple different settings on the same page. */
+
+function Datepicker() {
+ this._curInst = null; // The current instance in use
+ this._keyEvent = false; // If the last event was a key event
+ this._disabledInputs = []; // List of date picker inputs that have been disabled
+ this._datepickerShowing = false; // True if the popup picker is showing , false if not
+ this._inDialog = false; // True if showing within a "dialog", false if not
+ this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
+ this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
+ this._appendClass = "ui-datepicker-append"; // The name of the append marker class
+ this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
+ this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
+ this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
+ this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
+ this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
+ this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
+ this.regional = []; // Available regional settings, indexed by language code
+ this.regional[""] = { // Default regional settings
+ closeText: "Done", // Display text for close link
+ prevText: "Prev", // Display text for previous month link
+ nextText: "Next", // Display text for next month link
+ currentText: "Today", // Display text for current month link
+ monthNames: ["January","February","March","April","May","June",
+ "July","August","September","October","November","December"], // Names of months for drop-down and formatting
+ monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
+ dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
+ dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
+ dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
+ weekHeader: "Wk", // Column header for week of the year
+ dateFormat: "mm/dd/yy", // See format options on parseDate
+ firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
+ isRTL: false, // True if right-to-left language, false if left-to-right
+ showMonthAfterYear: false, // True if the year select precedes month, false for month then year
+ yearSuffix: "" // Additional text to append to the year in the month headers
+ };
+ this._defaults = { // Global defaults for all the date picker instances
+ showOn: "focus", // "focus" for popup on focus,
+ // "button" for trigger button, or "both" for either
+ showAnim: "fadeIn", // Name of jQuery animation for popup
+ showOptions: {}, // Options for enhanced animations
+ defaultDate: null, // Used when field is blank: actual date,
+ // +/-number for offset from today, null for today
+ appendText: "", // Display text following the input box, e.g. showing the format
+ buttonText: "...", // Text for trigger button
+ buttonImage: "", // URL for trigger button image
+ buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
+ hideIfNoPrevNext: false, // True to hide next/previous month links
+ // if not applicable, false to just disable them
+ navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
+ gotoCurrent: false, // True if today link goes back to current selection instead
+ changeMonth: false, // True if month can be selected directly, false if only prev/next
+ changeYear: false, // True if year can be selected directly, false if only prev/next
+ yearRange: "c-10:c+10", // Range of years to display in drop-down,
+ // either relative to today's year (-nn:+nn), relative to currently displayed year
+ // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
+ showOtherMonths: false, // True to show dates in other months, false to leave blank
+ selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
+ showWeek: false, // True to show week of the year, false to not show it
+ calculateWeek: this.iso8601Week, // How to calculate the week of the year,
+ // takes a Date and returns the number of the week for it
+ shortYearCutoff: "+10", // Short year values < this are in the current century,
+ // > this are in the previous century,
+ // string value starting with "+" for current year + value
+ minDate: null, // The earliest selectable date, or null for no limit
+ maxDate: null, // The latest selectable date, or null for no limit
+ duration: "fast", // Duration of display/closure
+ beforeShowDay: null, // Function that takes a date and returns an array with
+ // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
+ // [2] = cell title (optional), e.g. $.datepicker.noWeekends
+ beforeShow: null, // Function that takes an input field and
+ // returns a set of custom settings for the date picker
+ onSelect: null, // Define a callback function when a date is selected
+ onChangeMonthYear: null, // Define a callback function when the month or year is changed
+ onClose: null, // Define a callback function when the datepicker is closed
+ numberOfMonths: 1, // Number of months to show at a time
+ showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
+ stepMonths: 1, // Number of months to step back/forward
+ stepBigMonths: 12, // Number of months to step back/forward for the big links
+ altField: "", // Selector for an alternate field to store selected dates into
+ altFormat: "", // The date format to use for the alternate field
+ constrainInput: true, // The input is constrained by the current date format
+ showButtonPanel: false, // True to show button panel, false to not show it
+ autoSize: false, // True to size the input for the date format, false to leave as is
+ disabled: false // The initial disabled state
+ };
+ $.extend(this._defaults, this.regional[""]);
+ this.regional.en = $.extend( true, {}, this.regional[ "" ]);
+ this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
+ this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
+}
+
+$.extend(Datepicker.prototype, {
+ /* Class name added to elements to indicate already configured with a date picker. */
+ markerClassName: "hasDatepicker",
+
+ //Keep track of the maximum number of rows displayed (see #7043)
+ maxRows: 4,
+
+ // TODO rename to "widget" when switching to widget factory
+ _widgetDatepicker: function() {
+ return this.dpDiv;
+ },
+
+ /* Override the default settings for all instances of the date picker.
+ * @param settings object - the new settings to use as defaults (anonymous object)
+ * @return the manager object
+ */
+ setDefaults: function(settings) {
+ datepicker_extendRemove(this._defaults, settings || {});
+ return this;
+ },
+
+ /* Attach the date picker to a jQuery selection.
+ * @param target element - the target input field or division or span
+ * @param settings object - the new settings to use for this date picker instance (anonymous)
+ */
+ _attachDatepicker: function(target, settings) {
+ var nodeName, inline, inst;
+ nodeName = target.nodeName.toLowerCase();
+ inline = (nodeName === "div" || nodeName === "span");
+ if (!target.id) {
+ this.uuid += 1;
+ target.id = "dp" + this.uuid;
+ }
+ inst = this._newInst($(target), inline);
+ inst.settings = $.extend({}, settings || {});
+ if (nodeName === "input") {
+ this._connectDatepicker(target, inst);
+ } else if (inline) {
+ this._inlineDatepicker(target, inst);
+ }
+ },
+
+ /* Create a new instance object. */
+ _newInst: function(target, inline) {
+ var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
+ return {id: id, input: target, // associated target
+ selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
+ drawMonth: 0, drawYear: 0, // month being drawn
+ inline: inline, // is datepicker inline or not
+ dpDiv: (!inline ? this.dpDiv : // presentation div
+ datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
+ },
+
+ /* Attach the date picker to an input field. */
+ _connectDatepicker: function(target, inst) {
+ var input = $(target);
+ inst.append = $([]);
+ inst.trigger = $([]);
+ if (input.hasClass(this.markerClassName)) {
+ return;
+ }
+ this._attachments(input, inst);
+ input.addClass(this.markerClassName).keydown(this._doKeyDown).
+ keypress(this._doKeyPress).keyup(this._doKeyUp);
+ this._autoSize(inst);
+ $.data(target, "datepicker", inst);
+ //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
+ if( inst.settings.disabled ) {
+ this._disableDatepicker( target );
+ }
+ },
+
+ /* Make attachments based on settings. */
+ _attachments: function(input, inst) {
+ var showOn, buttonText, buttonImage,
+ appendText = this._get(inst, "appendText"),
+ isRTL = this._get(inst, "isRTL");
+
+ if (inst.append) {
+ inst.append.remove();
+ }
+ if (appendText) {
+ inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
+ input[isRTL ? "before" : "after"](inst.append);
+ }
+
+ input.unbind("focus", this._showDatepicker);
+
+ if (inst.trigger) {
+ inst.trigger.remove();
+ }
+
+ showOn = this._get(inst, "showOn");
+ if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
+ input.focus(this._showDatepicker);
+ }
+ if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
+ buttonText = this._get(inst, "buttonText");
+ buttonImage = this._get(inst, "buttonImage");
+ inst.trigger = $(this._get(inst, "buttonImageOnly") ?
+ $("<img/>").addClass(this._triggerClass).
+ attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
+ $("<button type='button'></button>").addClass(this._triggerClass).
+ html(!buttonImage ? buttonText : $("<img/>").attr(
+ { src:buttonImage, alt:buttonText, title:buttonText })));
+ input[isRTL ? "before" : "after"](inst.trigger);
+ inst.trigger.click(function() {
+ if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
+ $.datepicker._hideDatepicker();
+ } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
+ $.datepicker._hideDatepicker();
+ $.datepicker._showDatepicker(input[0]);
+ } else {
+ $.datepicker._showDatepicker(input[0]);
+ }
+ return false;
+ });
+ }
+ },
+
+ /* Apply the maximum length for the date format. */
+ _autoSize: function(inst) {
+ if (this._get(inst, "autoSize") && !inst.inline) {
+ var findMax, max, maxI, i,
+ date = new Date(2009, 12 - 1, 20), // Ensure double digits
+ dateFormat = this._get(inst, "dateFormat");
+
+ if (dateFormat.match(/[DM]/)) {
+ findMax = function(names) {
+ max = 0;
+ maxI = 0;
+ for (i = 0; i < names.length; i++) {
+ if (names[i].length > max) {
+ max = names[i].length;
+ maxI = i;
+ }
+ }
+ return maxI;
+ };
+ date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
+ "monthNames" : "monthNamesShort"))));
+ date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
+ "dayNames" : "dayNamesShort"))) + 20 - date.getDay());
+ }
+ inst.input.attr("size", this._formatDate(inst, date).length);
+ }
+ },
+
+ /* Attach an inline date picker to a div. */
+ _inlineDatepicker: function(target, inst) {
+ var divSpan = $(target);
+ if (divSpan.hasClass(this.markerClassName)) {
+ return;
+ }
+ divSpan.addClass(this.markerClassName).append(inst.dpDiv);
+ $.data(target, "datepicker", inst);
+ this._setDate(inst, this._getDefaultDate(inst), true);
+ this._updateDatepicker(inst);
+ this._updateAlternate(inst);
+ //If disabled option is true, disable the datepicker before showing it (see ticket #5665)
+ if( inst.settings.disabled ) {
+ this._disableDatepicker( target );
+ }
+ // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
+ // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
+ inst.dpDiv.css( "display", "block" );
+ },
+
+ /* Pop-up the date picker in a "dialog" box.
+ * @param input element - ignored
+ * @param date string or Date - the initial date to display
+ * @param onSelect function - the function to call when a date is selected
+ * @param settings object - update the dialog date picker instance's settings (anonymous object)
+ * @param pos int[2] - coordinates for the dialog's position within the screen or
+ * event - with x/y coordinates or
+ * leave empty for default (screen centre)
+ * @return the manager object
+ */
+ _dialogDatepicker: function(input, date, onSelect, settings, pos) {
+ var id, browserWidth, browserHeight, scrollX, scrollY,
+ inst = this._dialogInst; // internal instance
+
+ if (!inst) {
+ this.uuid += 1;
+ id = "dp" + this.uuid;
+ this._dialogInput = $("<input type='text' id='" + id +
+ "' style='position: absolute; top: -100px; width: 0px;'/>");
+ this._dialogInput.keydown(this._doKeyDown);
+ $("body").append(this._dialogInput);
+ inst = this._dialogInst = this._newInst(this._dialogInput, false);
+ inst.settings = {};
+ $.data(this._dialogInput[0], "datepicker", inst);
+ }
+ datepicker_extendRemove(inst.settings, settings || {});
+ date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
+ this._dialogInput.val(date);
+
+ this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
+ if (!this._pos) {
+ browserWidth = document.documentElement.clientWidth;
+ browserHeight = document.documentElement.clientHeight;
+ scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
+ scrollY = document.documentElement.scrollTop || document.body.scrollTop;
+ this._pos = // should use actual width/height below
+ [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
+ }
+
+ // move input on screen for focus, but hidden behind dialog
+ this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
+ inst.settings.onSelect = onSelect;
+ this._inDialog = true;
+ this.dpDiv.addClass(this._dialogClass);
+ this._showDatepicker(this._dialogInput[0]);
+ if ($.blockUI) {
+ $.blockUI(this.dpDiv);
+ }
+ $.data(this._dialogInput[0], "datepicker", inst);
+ return this;
+ },
+
+ /* Detach a datepicker from its control.
+ * @param target element - the target input field or division or span
+ */
+ _destroyDatepicker: function(target) {
+ var nodeName,
+ $target = $(target),
+ inst = $.data(target, "datepicker");
+
+ if (!$target.hasClass(this.markerClassName)) {
+ return;
+ }
+
+ nodeName = target.nodeName.toLowerCase();
+ $.removeData(target, "datepicker");
+ if (nodeName === "input") {
+ inst.append.remove();
+ inst.trigger.remove();
+ $target.removeClass(this.markerClassName).
+ unbind("focus", this._showDatepicker).
+ unbind("keydown", this._doKeyDown).
+ unbind("keypress", this._doKeyPress).
+ unbind("keyup", this._doKeyUp);
+ } else if (nodeName === "div" || nodeName === "span") {
+ $target.removeClass(this.markerClassName).empty();
+ }
+ },
+
+ /* Enable the date picker to a jQuery selection.
+ * @param target element - the target input field or division or span
+ */
+ _enableDatepicker: function(target) {
+ var nodeName, inline,
+ $target = $(target),
+ inst = $.data(target, "datepicker");
+
+ if (!$target.hasClass(this.markerClassName)) {
+ return;
+ }
+
+ nodeName = target.nodeName.toLowerCase();
+ if (nodeName === "input") {
+ target.disabled = false;
+ inst.trigger.filter("button").
+ each(function() { this.disabled = false; }).end().
+ filter("img").css({opacity: "1.0", cursor: ""});
+ } else if (nodeName === "div" || nodeName === "span") {
+ inline = $target.children("." + this._inlineClass);
+ inline.children().removeClass("ui-state-disabled");
+ inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
+ prop("disabled", false);
+ }
+ this._disabledInputs = $.map(this._disabledInputs,
+ function(value) { return (value === target ? null : value); }); // delete entry
+ },
+
+ /* Disable the date picker to a jQuery selection.
+ * @param target element - the target input field or division or span
+ */
+ _disableDatepicker: function(target) {
+ var nodeName, inline,
+ $target = $(target),
+ inst = $.data(target, "datepicker");
+
+ if (!$target.hasClass(this.markerClassName)) {
+ return;
+ }
+
+ nodeName = target.nodeName.toLowerCase();
+ if (nodeName === "input") {
+ target.disabled = true;
+ inst.trigger.filter("button").
+ each(function() { this.disabled = true; }).end().
+ filter("img").css({opacity: "0.5", cursor: "default"});
+ } else if (nodeName === "div" || nodeName === "span") {
+ inline = $target.children("." + this._inlineClass);
+ inline.children().addClass("ui-state-disabled");
+ inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
+ prop("disabled", true);
+ }
+ this._disabledInputs = $.map(this._disabledInputs,
+ function(value) { return (value === target ? null : value); }); // delete entry
+ this._disabledInputs[this._disabledInputs.length] = target;
+ },
+
+ /* Is the first field in a jQuery collection disabled as a datepicker?
+ * @param target element - the target input field or division or span
+ * @return boolean - true if disabled, false if enabled
+ */
+ _isDisabledDatepicker: function(target) {
+ if (!target) {
+ return false;
+ }
+ for (var i = 0; i < this._disabledInputs.length; i++) {
+ if (this._disabledInputs[i] === target) {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ /* Retrieve the instance data for the target control.
+ * @param target element - the target input field or division or span
+ * @return object - the associated instance data
+ * @throws error if a jQuery problem getting data
+ */
+ _getInst: function(target) {
+ try {
+ return $.data(target, "datepicker");
+ }
+ catch (err) {
+ throw "Missing instance data for this datepicker";
+ }
+ },
+
+ /* Update or retrieve the settings for a date picker attached to an input field or division.
+ * @param target element - the target input field or division or span
+ * @param name object - the new settings to update or
+ * string - the name of the setting to change or retrieve,
+ * when retrieving also "all" for all instance settings or
+ * "defaults" for all global defaults
+ * @param value any - the new value for the setting
+ * (omit if above is an object or to retrieve a value)
+ */
+ _optionDatepicker: function(target, name, value) {
+ var settings, date, minDate, maxDate,
+ inst = this._getInst(target);
+
+ if (arguments.length === 2 && typeof name === "string") {
+ return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
+ (inst ? (name === "all" ? $.extend({}, inst.settings) :
+ this._get(inst, name)) : null));
+ }
+
+ settings = name || {};
+ if (typeof name === "string") {
+ settings = {};
+ settings[name] = value;
+ }
+
+ if (inst) {
+ if (this._curInst === inst) {
+ this._hideDatepicker();
+ }
+
+ date = this._getDateDatepicker(target, true);
+ minDate = this._getMinMaxDate(inst, "min");
+ maxDate = this._getMinMaxDate(inst, "max");
+ datepicker_extendRemove(inst.settings, settings);
+ // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
+ if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
+ inst.settings.minDate = this._formatDate(inst, minDate);
+ }
+ if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
+ inst.settings.maxDate = this._formatDate(inst, maxDate);
+ }
+ if ( "disabled" in settings ) {
+ if ( settings.disabled ) {
+ this._disableDatepicker(target);
+ } else {
+ this._enableDatepicker(target);
+ }
+ }
+ this._attachments($(target), inst);
+ this._autoSize(inst);
+ this._setDate(inst, date);
+ this._updateAlternate(inst);
+ this._updateDatepicker(inst);
+ }
+ },
+
+ // change method deprecated
+ _changeDatepicker: function(target, name, value) {
+ this._optionDatepicker(target, name, value);
+ },
+
+ /* Redraw the date picker attached to an input field or division.
+ * @param target element - the target input field or division or span
+ */
+ _refreshDatepicker: function(target) {
+ var inst = this._getInst(target);
+ if (inst) {
+ this._updateDatepicker(inst);
+ }
+ },
+
+ /* Set the dates for a jQuery selection.
+ * @param target element - the target input field or division or span
+ * @param date Date - the new date
+ */
+ _setDateDatepicker: function(target, date) {
+ var inst = this._getInst(target);
+ if (inst) {
+ this._setDate(inst, date);
+ this._updateDatepicker(inst);
+ this._updateAlternate(inst);
+ }
+ },
+
+ /* Get the date(s) for the first entry in a jQuery selection.
+ * @param target element - the target input field or division or span
+ * @param noDefault boolean - true if no default date is to be used
+ * @return Date - the current date
+ */
+ _getDateDatepicker: function(target, noDefault) {
+ var inst = this._getInst(target);
+ if (inst && !inst.inline) {
+ this._setDateFromField(inst, noDefault);
+ }
+ return (inst ? this._getDate(inst) : null);
+ },
+
+ /* Handle keystrokes. */
+ _doKeyDown: function(event) {
+ var onSelect, dateStr, sel,
+ inst = $.datepicker._getInst(event.target),
+ handled = true,
+ isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
+
+ inst._keyEvent = true;
+ if ($.datepicker._datepickerShowing) {
+ switch (event.keyCode) {
+ case 9: $.datepicker._hideDatepicker();
+ handled = false;
+ break; // hide on tab out
+ case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
+ $.datepicker._currentClass + ")", inst.dpDiv);
+ if (sel[0]) {
+ $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
+ }
+
+ onSelect = $.datepicker._get(inst, "onSelect");
+ if (onSelect) {
+ dateStr = $.datepicker._formatDate(inst);
+
+ // trigger custom callback
+ onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
+ } else {
+ $.datepicker._hideDatepicker();
+ }
+
+ return false; // don't submit the form
+ case 27: $.datepicker._hideDatepicker();
+ break; // hide on escape
+ case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+ -$.datepicker._get(inst, "stepBigMonths") :
+ -$.datepicker._get(inst, "stepMonths")), "M");
+ break; // previous month/year on page up/+ ctrl
+ case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+ +$.datepicker._get(inst, "stepBigMonths") :
+ +$.datepicker._get(inst, "stepMonths")), "M");
+ break; // next month/year on page down/+ ctrl
+ case 35: if (event.ctrlKey || event.metaKey) {
+ $.datepicker._clearDate(event.target);
+ }
+ handled = event.ctrlKey || event.metaKey;
+ break; // clear on ctrl or command +end
+ case 36: if (event.ctrlKey || event.metaKey) {
+ $.datepicker._gotoToday(event.target);
+ }
+ handled = event.ctrlKey || event.metaKey;
+ break; // current on ctrl or command +home
+ case 37: if (event.ctrlKey || event.metaKey) {
+ $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
+ }
+ handled = event.ctrlKey || event.metaKey;
+ // -1 day on ctrl or command +left
+ if (event.originalEvent.altKey) {
+ $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+ -$.datepicker._get(inst, "stepBigMonths") :
+ -$.datepicker._get(inst, "stepMonths")), "M");
+ }
+ // next month/year on alt +left on Mac
+ break;
+ case 38: if (event.ctrlKey || event.metaKey) {
+ $.datepicker._adjustDate(event.target, -7, "D");
+ }
+ handled = event.ctrlKey || event.metaKey;
+ break; // -1 week on ctrl or command +up
+ case 39: if (event.ctrlKey || event.metaKey) {
+ $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
+ }
+ handled = event.ctrlKey || event.metaKey;
+ // +1 day on ctrl or command +right
+ if (event.originalEvent.altKey) {
+ $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+ +$.datepicker._get(inst, "stepBigMonths") :
+ +$.datepicker._get(inst, "stepMonths")), "M");
+ }
+ // next month/year on alt +right
+ break;
+ case 40: if (event.ctrlKey || event.metaKey) {
+ $.datepicker._adjustDate(event.target, +7, "D");
+ }
+ handled = event.ctrlKey || event.metaKey;
+ break; // +1 week on ctrl or command +down
+ default: handled = false;
+ }
+ } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
+ $.datepicker._showDatepicker(this);
+ } else {
+ handled = false;
+ }
+
+ if (handled) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ },
+
+ /* Filter entered characters - based on date format. */
+ _doKeyPress: function(event) {
+ var chars, chr,
+ inst = $.datepicker._getInst(event.target);
+
+ if ($.datepicker._get(inst, "constrainInput")) {
+ chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
+ chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
+ return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
+ }
+ },
+
+ /* Synchronise manual entry and field/alternate field. */
+ _doKeyUp: function(event) {
+ var date,
+ inst = $.datepicker._getInst(event.target);
+
+ if (inst.input.val() !== inst.lastVal) {
+ try {
+ date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
+ (inst.input ? inst.input.val() : null),
+ $.datepicker._getFormatConfig(inst));
+
+ if (date) { // only if valid
+ $.datepicker._setDateFromField(inst);
+ $.datepicker._updateAlternate(inst);
+ $.datepicker._updateDatepicker(inst);
+ }
+ }
+ catch (err) {
+ }
+ }
+ return true;
+ },
+
+ /* Pop-up the date picker for a given input field.
+ * If false returned from beforeShow event handler do not show.
+ * @param input element - the input field attached to the date picker or
+ * event - if triggered by focus
+ */
+ _showDatepicker: function(input) {
+ input = input.target || input;
+ if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
+ input = $("input", input.parentNode)[0];
+ }
+
+ if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
+ return;
+ }
+
+ var inst, beforeShow, beforeShowSettings, isFixed,
+ offset, showAnim, duration;
+
+ inst = $.datepicker._getInst(input);
+ if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
+ $.datepicker._curInst.dpDiv.stop(true, true);
+ if ( inst && $.datepicker._datepickerShowing ) {
+ $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
+ }
+ }
+
+ beforeShow = $.datepicker._get(inst, "beforeShow");
+ beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
+ if(beforeShowSettings === false){
+ return;
+ }
+ datepicker_extendRemove(inst.settings, beforeShowSettings);
+
+ inst.lastVal = null;
+ $.datepicker._lastInput = input;
+ $.datepicker._setDateFromField(inst);
+
+ if ($.datepicker._inDialog) { // hide cursor
+ input.value = "";
+ }
+ if (!$.datepicker._pos) { // position below input
+ $.datepicker._pos = $.datepicker._findPos(input);
+ $.datepicker._pos[1] += input.offsetHeight; // add the height
+ }
+
+ isFixed = false;
+ $(input).parents().each(function() {
+ isFixed |= $(this).css("position") === "fixed";
+ return !isFixed;
+ });
+
+ offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
+ $.datepicker._pos = null;
+ //to avoid flashes on Firefox
+ inst.dpDiv.empty();
+ // determine sizing offscreen
+ inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
+ $.datepicker._updateDatepicker(inst);
+ // fix width for dynamic number of date pickers
+ // and adjust position before showing
+ offset = $.datepicker._checkOffset(inst, offset, isFixed);
+ inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
+ "static" : (isFixed ? "fixed" : "absolute")), display: "none",
+ left: offset.left + "px", top: offset.top + "px"});
+
+ if (!inst.inline) {
+ showAnim = $.datepicker._get(inst, "showAnim");
+ duration = $.datepicker._get(inst, "duration");
+ inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
+ $.datepicker._datepickerShowing = true;
+
+ if ( $.effects && $.effects.effect[ showAnim ] ) {
+ inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
+ } else {
+ inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
+ }
+
+ if ( $.datepicker._shouldFocusInput( inst ) ) {
+ inst.input.focus();
+ }
+
+ $.datepicker._curInst = inst;
+ }
+ },
+
+ /* Generate the date picker content. */
+ _updateDatepicker: function(inst) {
+ this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
+ datepicker_instActive = inst; // for delegate hover events
+ inst.dpDiv.empty().append(this._generateHTML(inst));
+ this._attachHandlers(inst);
+
+ var origyearshtml,
+ numMonths = this._getNumberOfMonths(inst),
+ cols = numMonths[1],
+ width = 17,
+ activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );
+
+ if ( activeCell.length > 0 ) {
+ datepicker_handleMouseover.apply( activeCell.get( 0 ) );
+ }
+
+ inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
+ if (cols > 1) {
+ inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
+ }
+ inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
+ "Class"]("ui-datepicker-multi");
+ inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
+ "Class"]("ui-datepicker-rtl");
+
+ if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
+ inst.input.focus();
+ }
+
+ // deffered render of the years select (to avoid flashes on Firefox)
+ if( inst.yearshtml ){
+ origyearshtml = inst.yearshtml;
+ setTimeout(function(){
+ //assure that inst.yearshtml didn't change.
+ if( origyearshtml === inst.yearshtml && inst.yearshtml ){
+ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
+ }
+ origyearshtml = inst.yearshtml = null;
+ }, 0);
+ }
+ },
+
+ // #6694 - don't focus the input if it's already focused
+ // this breaks the change event in IE
+ // Support: IE and jQuery <1.9
+ _shouldFocusInput: function( inst ) {
+ return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
+ },
+
+ /* Check positioning to remain on screen. */
+ _checkOffset: function(inst, offset, isFixed) {
+ var dpWidth = inst.dpDiv.outerWidth(),
+ dpHeight = inst.dpDiv.outerHeight(),
+ inputWidth = inst.input ? inst.input.outerWidth() : 0,
+ inputHeight = inst.input ? inst.input.outerHeight() : 0,
+ viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
+ viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
+
+ offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
+ offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
+ offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
+
+ // now check if datepicker is showing outside window viewport - move to a better place if so.
+ offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
+ Math.abs(offset.left + dpWidth - viewWidth) : 0);
+ offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
+ Math.abs(dpHeight + inputHeight) : 0);
+
+ return offset;
+ },
+
+ /* Find an object's position on the screen. */
+ _findPos: function(obj) {
+ var position,
+ inst = this._getInst(obj),
+ isRTL = this._get(inst, "isRTL");
+
+ while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
+ obj = obj[isRTL ? "previousSibling" : "nextSibling"];
+ }
+
+ position = $(obj).offset();
+ return [position.left, position.top];
+ },
+
+ /* Hide the date picker from view.
+ * @param input element - the input field attached to the date picker
+ */
+ _hideDatepicker: function(input) {
+ var showAnim, duration, postProcess, onClose,
+ inst = this._curInst;
+
+ if (!inst || (input && inst !== $.data(input, "datepicker"))) {
+ return;
+ }
+
+ if (this._datepickerShowing) {
+ showAnim = this._get(inst, "showAnim");
+ duration = this._get(inst, "duration");
+ postProcess = function() {
+ $.datepicker._tidyDialog(inst);
+ };
+
+ // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
+ if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
+ inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
+ } else {
+ inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
+ (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
+ }
+
+ if (!showAnim) {
+ postProcess();
+ }
+ this._datepickerShowing = false;
+
+ onClose = this._get(inst, "onClose");
+ if (onClose) {
+ onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
+ }
+
+ this._lastInput = null;
+ if (this._inDialog) {
+ this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
+ if ($.blockUI) {
+ $.unblockUI();
+ $("body").append(this.dpDiv);
+ }
+ }
+ this._inDialog = false;
+ }
+ },
+
+ /* Tidy up after a dialog display. */
+ _tidyDialog: function(inst) {
+ inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
+ },
+
+ /* Close date picker if clicked elsewhere. */
+ _checkExternalClick: function(event) {
+ if (!$.datepicker._curInst) {
+ return;
+ }
+
+ var $target = $(event.target),
+ inst = $.datepicker._getInst($target[0]);
+
+ if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
+ $target.parents("#" + $.datepicker._mainDivId).length === 0 &&
+ !$target.hasClass($.datepicker.markerClassName) &&
+ !$target.closest("." + $.datepicker._triggerClass).length &&
+ $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
+ ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
+ $.datepicker._hideDatepicker();
+ }
+ },
+
+ /* Adjust one of the date sub-fields. */
+ _adjustDate: function(id, offset, period) {
+ var target = $(id),
+ inst = this._getInst(target[0]);
+
+ if (this._isDisabledDatepicker(target[0])) {
+ return;
+ }
+ this._adjustInstDate(inst, offset +
+ (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
+ period);
+ this._updateDatepicker(inst);
+ },
+
+ /* Action for current link. */
+ _gotoToday: function(id) {
+ var date,
+ target = $(id),
+ inst = this._getInst(target[0]);
+
+ if (this._get(inst, "gotoCurrent") && inst.currentDay) {
+ inst.selectedDay = inst.currentDay;
+ inst.drawMonth = inst.selectedMonth = inst.currentMonth;
+ inst.drawYear = inst.selectedYear = inst.currentYear;
+ } else {
+ date = new Date();
+ inst.selectedDay = date.getDate();
+ inst.drawMonth = inst.selectedMonth = date.getMonth();
+ inst.drawYear = inst.selectedYear = date.getFullYear();
+ }
+ this._notifyChange(inst);
+ this._adjustDate(target);
+ },
+
+ /* Action for selecting a new month/year. */
+ _selectMonthYear: function(id, select, period) {
+ var target = $(id),
+ inst = this._getInst(target[0]);
+
+ inst["selected" + (period === "M" ? "Month" : "Year")] =
+ inst["draw" + (period === "M" ? "Month" : "Year")] =
+ parseInt(select.options[select.selectedIndex].value,10);
+
+ this._notifyChange(inst);
+ this._adjustDate(target);
+ },
+
+ /* Action for selecting a day. */
+ _selectDay: function(id, month, year, td) {
+ var inst,
+ target = $(id);
+
+ if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
+ return;
+ }
+
+ inst = this._getInst(target[0]);
+ inst.selectedDay = inst.currentDay = $("a", td).html();
+ inst.selectedMonth = inst.currentMonth = month;
+ inst.selectedYear = inst.currentYear = year;
+ this._selectDate(id, this._formatDate(inst,
+ inst.currentDay, inst.currentMonth, inst.currentYear));
+ },
+
+ /* Erase the input field and hide the date picker. */
+ _clearDate: function(id) {
+ var target = $(id);
+ this._selectDate(target, "");
+ },
+
+ /* Update the input field with the selected date. */
+ _selectDate: function(id, dateStr) {
+ var onSelect,
+ target = $(id),
+ inst = this._getInst(target[0]);
+
+ dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
+ if (inst.input) {
+ inst.input.val(dateStr);
+ }
+ this._updateAlternate(inst);
+
+ onSelect = this._get(inst, "onSelect");
+ if (onSelect) {
+ onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
+ } else if (inst.input) {
+ inst.input.trigger("change"); // fire the change event
+ }
+
+ if (inst.inline){
+ this._updateDatepicker(inst);
+ } else {
+ this._hideDatepicker();
+ this._lastInput = inst.input[0];
+ if (typeof(inst.input[0]) !== "object") {
+ inst.input.focus(); // restore focus
+ }
+ this._lastInput = null;
+ }
+ },
+
+ /* Update any alternate field to synchronise with the main field. */
+ _updateAlternate: function(inst) {
+ var altFormat, date, dateStr,
+ altField = this._get(inst, "altField");
+
+ if (altField) { // update alternate field too
+ altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
+ date = this._getDate(inst);
+ dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
+ $(altField).each(function() { $(this).val(dateStr); });
+ }
+ },
+
+ /* Set as beforeShowDay function to prevent selection of weekends.
+ * @param date Date - the date to customise
+ * @return [boolean, string] - is this date selectable?, what is its CSS class?
+ */
+ noWeekends: function(date) {
+ var day = date.getDay();
+ return [(day > 0 && day < 6), ""];
+ },
+
+ /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
+ * @param date Date - the date to get the week for
+ * @return number - the number of the week within the year that contains this date
+ */
+ iso8601Week: function(date) {
+ var time,
+ checkDate = new Date(date.getTime());
+
+ // Find Thursday of this week starting on Monday
+ checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
+
+ time = checkDate.getTime();
+ checkDate.setMonth(0); // Compare with Jan 1
+ checkDate.setDate(1);
+ return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
+ },
+
+ /* Parse a string value into a date object.
+ * See formatDate below for the possible formats.
+ *
+ * @param format string - the expected format of the date
+ * @param value string - the date in the above format
+ * @param settings Object - attributes include:
+ * shortYearCutoff number - the cutoff year for determining the century (optional)
+ * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
+ * dayNames string[7] - names of the days from Sunday (optional)
+ * monthNamesShort string[12] - abbreviated names of the months (optional)
+ * monthNames string[12] - names of the months (optional)
+ * @return Date - the extracted date value or null if value is blank
+ */
+ parseDate: function (format, value, settings) {
+ if (format == null || value == null) {
+ throw "Invalid arguments";
+ }
+
+ value = (typeof value === "object" ? value.toString() : value + "");
+ if (value === "") {
+ return null;
+ }
+
+ var iFormat, dim, extra,
+ iValue = 0,
+ shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
+ shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
+ new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
+ dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
+ dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
+ monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
+ monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
+ year = -1,
+ month = -1,
+ day = -1,
+ doy = -1,
+ literal = false,
+ date,
+ // Check whether a format character is doubled
+ lookAhead = function(match) {
+ var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
+ if (matches) {
+ iFormat++;
+ }
+ return matches;
+ },
+ // Extract a number from the string value
+ getNumber = function(match) {
+ var isDoubled = lookAhead(match),
+ size = (match === "@" ? 14 : (match === "!" ? 20 :
+ (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
+ minSize = (match === "y" ? size : 1),
+ digits = new RegExp("^\\d{" + minSize + "," + size + "}"),
+ num = value.substring(iValue).match(digits);
+ if (!num) {
+ throw "Missing number at position " + iValue;
+ }
+ iValue += num[0].length;
+ return parseInt(num[0], 10);
+ },
+ // Extract a name from the string value and convert to an index
+ getName = function(match, shortNames, longNames) {
+ var index = -1,
+ names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
+ return [ [k, v] ];
+ }).sort(function (a, b) {
+ return -(a[1].length - b[1].length);
+ });
+
+ $.each(names, function (i, pair) {
+ var name = pair[1];
+ if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
+ index = pair[0];
+ iValue += name.length;
+ return false;
+ }
+ });
+ if (index !== -1) {
+ return index + 1;
+ } else {
+ throw "Unknown name at position " + iValue;
+ }
+ },
+ // Confirm that a literal character matches the string value
+ checkLiteral = function() {
+ if (value.charAt(iValue) !== format.charAt(iFormat)) {
+ throw "Unexpected literal at position " + iValue;
+ }
+ iValue++;
+ };
+
+ for (iFormat = 0; iFormat < format.length; iFormat++) {
+ if (literal) {
+ if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
+ literal = false;
+ } else {
+ checkLiteral();
+ }
+ } else {
+ switch (format.charAt(iFormat)) {
+ case "d":
+ day = getNumber("d");
+ break;
+ case "D":
+ getName("D", dayNamesShort, dayNames);
+ break;
+ case "o":
+ doy = getNumber("o");
+ break;
+ case "m":
+ month = getNumber("m");
+ break;
+ case "M":
+ month = getName("M", monthNamesShort, monthNames);
+ break;
+ case "y":
+ year = getNumber("y");
+ break;
+ case "@":
+ date = new Date(getNumber("@"));
+ year = date.getFullYear();
+ month = date.getMonth() + 1;
+ day = date.getDate();
+ break;
+ case "!":
+ date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
+ year = date.getFullYear();
+ month = date.getMonth() + 1;
+ day = date.getDate();
+ break;
+ case "'":
+ if (lookAhead("'")){
+ checkLiteral();
+ } else {
+ literal = true;
+ }
+ break;
+ default:
+ checkLiteral();
+ }
+ }
+ }
+
+ if (iValue < value.length){
+ extra = value.substr(iValue);
+ if (!/^\s+/.test(extra)) {
+ throw "Extra/unparsed characters found in date: " + extra;
+ }
+ }
+
+ if (year === -1) {
+ year = new Date().getFullYear();
+ } else if (year < 100) {
+ year += new Date().getFullYear() - new Date().getFullYear() % 100 +
+ (year <= shortYearCutoff ? 0 : -100);
+ }
+
+ if (doy > -1) {
+ month = 1;
+ day = doy;
+ do {
+ dim = this._getDaysInMonth(year, month - 1);
+ if (day <= dim) {
+ break;
+ }
+ month++;
+ day -= dim;
+ } while (true);
+ }
+
+ date = this._daylightSavingAdjust(new Date(year, month - 1, day));
+ if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
+ throw "Invalid date"; // E.g. 31/02/00
+ }
+ return date;
+ },
+
+ /* Standard date formats. */
+ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
+ COOKIE: "D, dd M yy",
+ ISO_8601: "yy-mm-dd",
+ RFC_822: "D, d M y",
+ RFC_850: "DD, dd-M-y",
+ RFC_1036: "D, d M y",
+ RFC_1123: "D, d M yy",
+ RFC_2822: "D, d M yy",
+ RSS: "D, d M y", // RFC 822
+ TICKS: "!",
+ TIMESTAMP: "@",
+ W3C: "yy-mm-dd", // ISO 8601
+
+ _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
+ Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
+
+ /* Format a date object into a string value.
+ * The format can be combinations of the following:
+ * d - day of month (no leading zero)
+ * dd - day of month (two digit)
+ * o - day of year (no leading zeros)
+ * oo - day of year (three digit)
+ * D - day name short
+ * DD - day name long
+ * m - month of year (no leading zero)
+ * mm - month of year (two digit)
+ * M - month name short
+ * MM - month name long
+ * y - year (two digit)
+ * yy - year (four digit)
+ * @ - Unix timestamp (ms since 01/01/1970)
+ * ! - Windows ticks (100ns since 01/01/0001)
+ * "..." - literal text
+ * '' - single quote
+ *
+ * @param format string - the desired format of the date
+ * @param date Date - the date value to format
+ * @param settings Object - attributes include:
+ * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
+ * dayNames string[7] - names of the days from Sunday (optional)
+ * monthNamesShort string[12] - abbreviated names of the months (optional)
+ * monthNames string[12] - names of the months (optional)
+ * @return string - the date in the above format
+ */
+ formatDate: function (format, date, settings) {
+ if (!date) {
+ return "";
+ }
+
+ var iFormat,
+ dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
+ dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
+ monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
+ monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
+ // Check whether a format character is doubled
+ lookAhead = function(match) {
+ var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
+ if (matches) {
+ iFormat++;
+ }
+ return matches;
+ },
+ // Format a number, with leading zero if necessary
+ formatNumber = function(match, value, len) {
+ var num = "" + value;
+ if (lookAhead(match)) {
+ while (num.length < len) {
+ num = "0" + num;
+ }
+ }
+ return num;
+ },
+ // Format a name, short or long as requested
+ formatName = function(match, value, shortNames, longNames) {
+ return (lookAhead(match) ? longNames[value] : shortNames[value]);
+ },
+ output = "",
+ literal = false;
+
+ if (date) {
+ for (iFormat = 0; iFormat < format.length; iFormat++) {
+ if (literal) {
+ if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
+ literal = false;
+ } else {
+ output += format.charAt(iFormat);
+ }
+ } else {
+ switch (format.charAt(iFormat)) {
+ case "d":
+ output += formatNumber("d", date.getDate(), 2);
+ break;
+ case "D":
+ output += formatName("D", date.getDay(), dayNamesShort, dayNames);
+ break;
+ case "o":
+ output += formatNumber("o",
+ Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
+ break;
+ case "m":
+ output += formatNumber("m", date.getMonth() + 1, 2);
+ break;
+ case "M":
+ output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
+ break;
+ case "y":
+ output += (lookAhead("y") ? date.getFullYear() :
+ (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
+ break;
+ case "@":
+ output += date.getTime();
+ break;
+ case "!":
+ output += date.getTime() * 10000 + this._ticksTo1970;
+ break;
+ case "'":
+ if (lookAhead("'")) {
+ output += "'";
+ } else {
+ literal = true;
+ }
+ break;
+ default:
+ output += format.charAt(iFormat);
+ }
+ }
+ }
+ }
+ return output;
+ },
+
+ /* Extract all possible characters from the date format. */
+ _possibleChars: function (format) {
+ var iFormat,
+ chars = "",
+ literal = false,
+ // Check whether a format character is doubled
+ lookAhead = function(match) {
+ var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
+ if (matches) {
+ iFormat++;
+ }
+ return matches;
+ };
+
+ for (iFormat = 0; iFormat < format.length; iFormat++) {
+ if (literal) {
+ if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
+ literal = false;
+ } else {
+ chars += format.charAt(iFormat);
+ }
+ } else {
+ switch (format.charAt(iFormat)) {
+ case "d": case "m": case "y": case "@":
+ chars += "0123456789";
+ break;
+ case "D": case "M":
+ return null; // Accept anything
+ case "'":
+ if (lookAhead("'")) {
+ chars += "'";
+ } else {
+ literal = true;
+ }
+ break;
+ default:
+ chars += format.charAt(iFormat);
+ }
+ }
+ }
+ return chars;
+ },
+
+ /* Get a setting value, defaulting if necessary. */
+ _get: function(inst, name) {
+ return inst.settings[name] !== undefined ?
+ inst.settings[name] : this._defaults[name];
+ },
+
+ /* Parse existing date and initialise date picker. */
+ _setDateFromField: function(inst, noDefault) {
+ if (inst.input.val() === inst.lastVal) {
+ return;
+ }
+
+ var dateFormat = this._get(inst, "dateFormat"),
+ dates = inst.lastVal = inst.input ? inst.input.val() : null,
+ defaultDate = this._getDefaultDate(inst),
+ date = defaultDate,
+ settings = this._getFormatConfig(inst);
+
+ try {
+ date = this.parseDate(dateFormat, dates, settings) || defaultDate;
+ } catch (event) {
+ dates = (noDefault ? "" : dates);
+ }
+ inst.selectedDay = date.getDate();
+ inst.drawMonth = inst.selectedMonth = date.getMonth();
+ inst.drawYear = inst.selectedYear = date.getFullYear();
+ inst.currentDay = (dates ? date.getDate() : 0);
+ inst.currentMonth = (dates ? date.getMonth() : 0);
+ inst.currentYear = (dates ? date.getFullYear() : 0);
+ this._adjustInstDate(inst);
+ },
+
+ /* Retrieve the default date shown on opening. */
+ _getDefaultDate: function(inst) {
+ return this._restrictMinMax(inst,
+ this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
+ },
+
+ /* A date may be specified as an exact value or a relative one. */
+ _determineDate: function(inst, date, defaultDate) {
+ var offsetNumeric = function(offset) {
+ var date = new Date();
+ date.setDate(date.getDate() + offset);
+ return date;
+ },
+ offsetString = function(offset) {
+ try {
+ return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
+ offset, $.datepicker._getFormatConfig(inst));
+ }
+ catch (e) {
+ // Ignore
+ }
+
+ var date = (offset.toLowerCase().match(/^c/) ?
+ $.datepicker._getDate(inst) : null) || new Date(),
+ year = date.getFullYear(),
+ month = date.getMonth(),
+ day = date.getDate(),
+ pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
+ matches = pattern.exec(offset);
+
+ while (matches) {
+ switch (matches[2] || "d") {
+ case "d" : case "D" :
+ day += parseInt(matches[1],10); break;
+ case "w" : case "W" :
+ day += parseInt(matches[1],10) * 7; break;
+ case "m" : case "M" :
+ month += parseInt(matches[1],10);
+ day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
+ break;
+ case "y": case "Y" :
+ year += parseInt(matches[1],10);
+ day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
+ break;
+ }
+ matches = pattern.exec(offset);
+ }
+ return new Date(year, month, day);
+ },
+ newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
+ (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
+
+ newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
+ if (newDate) {
+ newDate.setHours(0);
+ newDate.setMinutes(0);
+ newDate.setSeconds(0);
+ newDate.setMilliseconds(0);
+ }
+ return this._daylightSavingAdjust(newDate);
+ },
+
+ /* Handle switch to/from daylight saving.
+ * Hours may be non-zero on daylight saving cut-over:
+ * > 12 when midnight changeover, but then cannot generate
+ * midnight datetime, so jump to 1AM, otherwise reset.
+ * @param date (Date) the date to check
+ * @return (Date) the corrected date
+ */
+ _daylightSavingAdjust: function(date) {
+ if (!date) {
+ return null;
+ }
+ date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
+ return date;
+ },
+
+ /* Set the date(s) directly. */
+ _setDate: function(inst, date, noChange) {
+ var clear = !date,
+ origMonth = inst.selectedMonth,
+ origYear = inst.selectedYear,
+ newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
+
+ inst.selectedDay = inst.currentDay = newDate.getDate();
+ inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
+ inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
+ if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
+ this._notifyChange(inst);
+ }
+ this._adjustInstDate(inst);
+ if (inst.input) {
+ inst.input.val(clear ? "" : this._formatDate(inst));
+ }
+ },
+
+ /* Retrieve the date(s) directly. */
+ _getDate: function(inst) {
+ var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
+ this._daylightSavingAdjust(new Date(
+ inst.currentYear, inst.currentMonth, inst.currentDay)));
+ return startDate;
+ },
+
+ /* Attach the onxxx handlers. These are declared statically so
+ * they work with static code transformers like Caja.
+ */
+ _attachHandlers: function(inst) {
+ var stepMonths = this._get(inst, "stepMonths"),
+ id = "#" + inst.id.replace( /\\\\/g, "\\" );
+ inst.dpDiv.find("[data-handler]").map(function () {
+ var handler = {
+ prev: function () {
+ $.datepicker._adjustDate(id, -stepMonths, "M");
+ },
+ next: function () {
+ $.datepicker._adjustDate(id, +stepMonths, "M");
+ },
+ hide: function () {
+ $.datepicker._hideDatepicker();
+ },
+ today: function () {
+ $.datepicker._gotoToday(id);
+ },
+ selectDay: function () {
+ $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
+ return false;
+ },
+ selectMonth: function () {
+ $.datepicker._selectMonthYear(id, this, "M");
+ return false;
+ },
+ selectYear: function () {
+ $.datepicker._selectMonthYear(id, this, "Y");
+ return false;
+ }
+ };
+ $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
+ });
+ },
+
+ /* Generate the HTML for the current state of the date picker. */
+ _generateHTML: function(inst) {
+ var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
+ controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
+ monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
+ selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
+ cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
+ printDate, dRow, tbody, daySettings, otherMonth, unselectable,
+ tempDate = new Date(),
+ today = this._daylightSavingAdjust(
+ new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
+ isRTL = this._get(inst, "isRTL"),
+ showButtonPanel = this._get(inst, "showButtonPanel"),
+ hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
+ navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
+ numMonths = this._getNumberOfMonths(inst),
+ showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
+ stepMonths = this._get(inst, "stepMonths"),
+ isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
+ currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
+ new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
+ minDate = this._getMinMaxDate(inst, "min"),
+ maxDate = this._getMinMaxDate(inst, "max"),
+ drawMonth = inst.drawMonth - showCurrentAtPos,
+ drawYear = inst.drawYear;
+
+ if (drawMonth < 0) {
+ drawMonth += 12;
+ drawYear--;
+ }
+ if (maxDate) {
+ maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
+ maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
+ maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
+ while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
+ drawMonth--;
+ if (drawMonth < 0) {
+ drawMonth = 11;
+ drawYear--;
+ }
+ }
+ }
+ inst.drawMonth = drawMonth;
+ inst.drawYear = drawYear;
+
+ prevText = this._get(inst, "prevText");
+ prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
+ this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
+ this._getFormatConfig(inst)));
+
+ prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
+ "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
+ " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
+ (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
+
+ nextText = this._get(inst, "nextText");
+ nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
+ this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
+ this._getFormatConfig(inst)));
+
+ next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
+ "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
+ " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
+ (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
+
+ currentText = this._get(inst, "currentText");
+ gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
+ currentText = (!navigationAsDateFormat ? currentText :
+ this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
+
+ controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
+ this._get(inst, "closeText") + "</button>" : "");
+
+ buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
+ (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
+ ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
+
+ firstDay = parseInt(this._get(inst, "firstDay"),10);
+ firstDay = (isNaN(firstDay) ? 0 : firstDay);
+
+ showWeek = this._get(inst, "showWeek");
+ dayNames = this._get(inst, "dayNames");
+ dayNamesMin = this._get(inst, "dayNamesMin");
+ monthNames = this._get(inst, "monthNames");
+ monthNamesShort = this._get(inst, "monthNamesShort");
+ beforeShowDay = this._get(inst, "beforeShowDay");
+ showOtherMonths = this._get(inst, "showOtherMonths");
+ selectOtherMonths = this._get(inst, "selectOtherMonths");
+ defaultDate = this._getDefaultDate(inst);
+ html = "";
+ dow;
+ for (row = 0; row < numMonths[0]; row++) {
+ group = "";
+ this.maxRows = 4;
+ for (col = 0; col < numMonths[1]; col++) {
+ selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
+ cornerClass = " ui-corner-all";
+ calender = "";
+ if (isMultiMonth) {
+ calender += "<div class='ui-datepicker-group";
+ if (numMonths[1] > 1) {
+ switch (col) {
+ case 0: calender += " ui-datepicker-group-first";
+ cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
+ case numMonths[1]-1: calender += " ui-datepicker-group-last";
+ cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
+ default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
+ }
+ }
+ calender += "'>";
+ }
+ calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
+ (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
+ (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
+ this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
+ row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
+ "</div><table class='ui-datepicker-calendar'><thead>" +
+ "<tr>";
+ thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
+ for (dow = 0; dow < 7; dow++) { // days of the week
+ day = (dow + firstDay) % 7;
+ thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
+ "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
+ }
+ calender += thead + "</tr></thead><tbody>";
+ daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
+ if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
+ inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
+ }
+ leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
+ curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
+ numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
+ this.maxRows = numRows;
+ printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
+ for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
+ calender += "<tr>";
+ tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
+ this._get(inst, "calculateWeek")(printDate) + "</td>");
+ for (dow = 0; dow < 7; dow++) { // create date picker days
+ daySettings = (beforeShowDay ?
+ beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
+ otherMonth = (printDate.getMonth() !== drawMonth);
+ unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
+ (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
+ tbody += "<td class='" +
+ ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
+ (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
+ ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
+ (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
+ // or defaultDate is current printedDate and defaultDate is selectedDate
+ " " + this._dayOverClass : "") + // highlight selected day
+ (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
+ (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
+ (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
+ (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
+ ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
+ (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
+ (otherMonth && !showOtherMonths ? " " : // display for other months
+ (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
+ (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
+ (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
+ (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
+ "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
+ printDate.setDate(printDate.getDate() + 1);
+ printDate = this._daylightSavingAdjust(printDate);
+ }
+ calender += tbody + "</tr>";
+ }
+ drawMonth++;
+ if (drawMonth > 11) {
+ drawMonth = 0;
+ drawYear++;
+ }
+ calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
+ ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
+ group += calender;
+ }
+ html += group;
+ }
+ html += buttonPanel;
+ inst._keyEvent = false;
+ return html;
+ },
+
+ /* Generate the month and year header. */
+ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
+ secondary, monthNames, monthNamesShort) {
+
+ var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
+ changeMonth = this._get(inst, "changeMonth"),
+ changeYear = this._get(inst, "changeYear"),
+ showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
+ html = "<div class='ui-datepicker-title'>",
+ monthHtml = "";
+
+ // month selection
+ if (secondary || !changeMonth) {
+ monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
+ } else {
+ inMinYear = (minDate && minDate.getFullYear() === drawYear);
+ inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
+ monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
+ for ( month = 0; month < 12; month++) {
+ if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
+ monthHtml += "<option value='" + month + "'" +
+ (month === drawMonth ? " selected='selected'" : "") +
+ ">" + monthNamesShort[month] + "</option>";
+ }
+ }
+ monthHtml += "</select>";
+ }
+
+ if (!showMonthAfterYear) {
+ html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
+ }
+
+ // year selection
+ if ( !inst.yearshtml ) {
+ inst.yearshtml = "";
+ if (secondary || !changeYear) {
+ html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
+ } else {
+ // determine range of years to display
+ years = this._get(inst, "yearRange").split(":");
+ thisYear = new Date().getFullYear();
+ determineYear = function(value) {
+ var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
+ (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
+ parseInt(value, 10)));
+ return (isNaN(year) ? thisYear : year);
+ };
+ year = determineYear(years[0]);
+ endYear = Math.max(year, determineYear(years[1] || ""));
+ year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
+ endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
+ inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
+ for (; year <= endYear; year++) {
+ inst.yearshtml += "<option value='" + year + "'" +
+ (year === drawYear ? " selected='selected'" : "") +
+ ">" + year + "</option>";
+ }
+ inst.yearshtml += "</select>";
+
+ html += inst.yearshtml;
+ inst.yearshtml = null;
+ }
+ }
+
+ html += this._get(inst, "yearSuffix");
+ if (showMonthAfterYear) {
+ html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
+ }
+ html += "</div>"; // Close datepicker_header
+ return html;
+ },
+
+ /* Adjust one of the date sub-fields. */
+ _adjustInstDate: function(inst, offset, period) {
+ var year = inst.drawYear + (period === "Y" ? offset : 0),
+ month = inst.drawMonth + (period === "M" ? offset : 0),
+ day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
+ date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
+
+ inst.selectedDay = date.getDate();
+ inst.drawMonth = inst.selectedMonth = date.getMonth();
+ inst.drawYear = inst.selectedYear = date.getFullYear();
+ if (period === "M" || period === "Y") {
+ this._notifyChange(inst);
+ }
+ },
+
+ /* Ensure a date is within any min/max bounds. */
+ _restrictMinMax: function(inst, date) {
+ var minDate = this._getMinMaxDate(inst, "min"),
+ maxDate = this._getMinMaxDate(inst, "max"),
+ newDate = (minDate && date < minDate ? minDate : date);
+ return (maxDate && newDate > maxDate ? maxDate : newDate);
+ },
+
+ /* Notify change of month/year. */
+ _notifyChange: function(inst) {
+ var onChange = this._get(inst, "onChangeMonthYear");
+ if (onChange) {
+ onChange.apply((inst.input ? inst.input[0] : null),
+ [inst.selectedYear, inst.selectedMonth + 1, inst]);
+ }
+ },
+
+ /* Determine the number of months to show. */
+ _getNumberOfMonths: function(inst) {
+ var numMonths = this._get(inst, "numberOfMonths");
+ return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
+ },
+
+ /* Determine the current maximum date - ensure no time components are set. */
+ _getMinMaxDate: function(inst, minMax) {
+ return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
+ },
+
+ /* Find the number of days in a given month. */
+ _getDaysInMonth: function(year, month) {
+ return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
+ },
+
+ /* Find the day of the week of the first of a month. */
+ _getFirstDayOfMonth: function(year, month) {
+ return new Date(year, month, 1).getDay();
+ },
+
+ /* Determines if we should allow a "next/prev" month display change. */
+ _canAdjustMonth: function(inst, offset, curYear, curMonth) {
+ var numMonths = this._getNumberOfMonths(inst),
+ date = this._daylightSavingAdjust(new Date(curYear,
+ curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
+
+ if (offset < 0) {
+ date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
+ }
+ return this._isInRange(inst, date);
+ },
+
+ /* Is the given date in the accepted range? */
+ _isInRange: function(inst, date) {
+ var yearSplit, currentYear,
+ minDate = this._getMinMaxDate(inst, "min"),
+ maxDate = this._getMinMaxDate(inst, "max"),
+ minYear = null,
+ maxYear = null,
+ years = this._get(inst, "yearRange");
+ if (years){
+ yearSplit = years.split(":");
+ currentYear = new Date().getFullYear();
+ minYear = parseInt(yearSplit[0], 10);
+ maxYear = parseInt(yearSplit[1], 10);
+ if ( yearSplit[0].match(/[+\-].*/) ) {
+ minYear += currentYear;
+ }
+ if ( yearSplit[1].match(/[+\-].*/) ) {
+ maxYear += currentYear;
+ }
+ }
+
+ return ((!minDate || date.getTime() >= minDate.getTime()) &&
+ (!maxDate || date.getTime() <= maxDate.getTime()) &&
+ (!minYear || date.getFullYear() >= minYear) &&
+ (!maxYear || date.getFullYear() <= maxYear));
+ },
+
+ /* Provide the configuration settings for formatting/parsing. */
+ _getFormatConfig: function(inst) {
+ var shortYearCutoff = this._get(inst, "shortYearCutoff");
+ shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
+ new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
+ return {shortYearCutoff: shortYearCutoff,
+ dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
+ monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
+ },
+
+ /* Format the given date for display. */
+ _formatDate: function(inst, day, month, year) {
+ if (!day) {
+ inst.currentDay = inst.selectedDay;
+ inst.currentMonth = inst.selectedMonth;
+ inst.currentYear = inst.selectedYear;
+ }
+ var date = (day ? (typeof day === "object" ? day :
+ this._daylightSavingAdjust(new Date(year, month, day))) :
+ this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
+ return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
+ }
+});
+
+/*
+ * Bind hover events for datepicker elements.
+ * Done via delegate so the binding only occurs once in the lifetime of the parent div.
+ * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
+ */
+function datepicker_bindHover(dpDiv) {
+ var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
+ return dpDiv.delegate(selector, "mouseout", function() {
+ $(this).removeClass("ui-state-hover");
+ if (this.className.indexOf("ui-datepicker-prev") !== -1) {
+ $(this).removeClass("ui-datepicker-prev-hover");
+ }
+ if (this.className.indexOf("ui-datepicker-next") !== -1) {
+ $(this).removeClass("ui-datepicker-next-hover");
+ }
+ })
+ .delegate( selector, "mouseover", datepicker_handleMouseover );
+}
+
+function datepicker_handleMouseover() {
+ if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) {
+ $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
+ $(this).addClass("ui-state-hover");
+ if (this.className.indexOf("ui-datepicker-prev") !== -1) {
+ $(this).addClass("ui-datepicker-prev-hover");
+ }
+ if (this.className.indexOf("ui-datepicker-next") !== -1) {
+ $(this).addClass("ui-datepicker-next-hover");
+ }
+ }
+}
+
+/* jQuery extend now ignores nulls! */
+function datepicker_extendRemove(target, props) {
+ $.extend(target, props);
+ for (var name in props) {
+ if (props[name] == null) {
+ target[name] = props[name];
+ }
+ }
+ return target;
+}
+
+/* Invoke the datepicker functionality.
+ @param options string - a command, optionally followed by additional parameters or
+ Object - settings for attaching new datepicker functionality
+ @return jQuery object */
+$.fn.datepicker = function(options){
+
+ /* Verify an empty collection wasn't passed - Fixes #6976 */
+ if ( !this.length ) {
+ return this;
+ }
+
+ /* Initialise the date picker. */
+ if (!$.datepicker.initialized) {
+ $(document).mousedown($.datepicker._checkExternalClick);
+ $.datepicker.initialized = true;
+ }
+
+ /* Append datepicker main container to body if not exist. */
+ if ($("#"+$.datepicker._mainDivId).length === 0) {
+ $("body").append($.datepicker.dpDiv);
+ }
+
+ var otherArgs = Array.prototype.slice.call(arguments, 1);
+ if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
+ return $.datepicker["_" + options + "Datepicker"].
+ apply($.datepicker, [this[0]].concat(otherArgs));
+ }
+ if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
+ return $.datepicker["_" + options + "Datepicker"].
+ apply($.datepicker, [this[0]].concat(otherArgs));
+ }
+ return this.each(function() {
+ typeof options === "string" ?
+ $.datepicker["_" + options + "Datepicker"].
+ apply($.datepicker, [this].concat(otherArgs)) :
+ $.datepicker._attachDatepicker(this, options);
+ });
+};
+
+$.datepicker = new Datepicker(); // singleton instance
+$.datepicker.initialized = false;
+$.datepicker.uuid = new Date().getTime();
+$.datepicker.version = "1.11.2";
+
+var datepicker = $.datepicker;
+
+
+/*!
+ * jQuery UI Draggable 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/draggable/
+ */
+
+
+$.widget("ui.draggable", $.ui.mouse, {
+ version: "1.11.2",
+ widgetEventPrefix: "drag",
+ options: {
+ addClasses: true,
+ appendTo: "parent",
+ axis: false,
+ connectToSortable: false,
+ containment: false,
+ cursor: "auto",
+ cursorAt: false,
+ grid: false,
+ handle: false,
+ helper: "original",
+ iframeFix: false,
+ opacity: false,
+ refreshPositions: false,
+ revert: false,
+ revertDuration: 500,
+ scope: "default",
+ scroll: true,
+ scrollSensitivity: 20,
+ scrollSpeed: 20,
+ snap: false,
+ snapMode: "both",
+ snapTolerance: 20,
+ stack: false,
+ zIndex: false,
+
+ // callbacks
+ drag: null,
+ start: null,
+ stop: null
+ },
+ _create: function() {
+
+ if ( this.options.helper === "original" ) {
+ this._setPositionRelative();
+ }
+ if (this.options.addClasses){
+ this.element.addClass("ui-draggable");
+ }
+ if (this.options.disabled){
+ this.element.addClass("ui-draggable-disabled");
+ }
+ this._setHandleClassName();
+
+ this._mouseInit();
+ },
+
+ _setOption: function( key, value ) {
+ this._super( key, value );
+ if ( key === "handle" ) {
+ this._removeHandleClassName();
+ this._setHandleClassName();
+ }
+ },
+
+ _destroy: function() {
+ if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
+ this.destroyOnClear = true;
+ return;
+ }
+ this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
+ this._removeHandleClassName();
+ this._mouseDestroy();
+ },
+
+ _mouseCapture: function(event) {
+ var o = this.options;
+
+ this._blurActiveElement( event );
+
+ // among others, prevent a drag on a resizable-handle
+ if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
+ return false;
+ }
+
+ //Quit if we're not on a valid handle
+ this.handle = this._getHandle(event);
+ if (!this.handle) {
+ return false;
+ }
+
+ this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );
+
+ return true;
+
+ },
+
+ _blockFrames: function( selector ) {
+ this.iframeBlocks = this.document.find( selector ).map(function() {
+ var iframe = $( this );
+
+ return $( "<div>" )
+ .css( "position", "absolute" )
+ .appendTo( iframe.parent() )
+ .outerWidth( iframe.outerWidth() )
+ .outerHeight( iframe.outerHeight() )
+ .offset( iframe.offset() )[ 0 ];
+ });
+ },
+
+ _unblockFrames: function() {
+ if ( this.iframeBlocks ) {
+ this.iframeBlocks.remove();
+ delete this.iframeBlocks;
+ }
+ },
+
+ _blurActiveElement: function( event ) {
+ var document = this.document[ 0 ];
+
+ // Only need to blur if the event occurred on the draggable itself, see #10527
+ if ( !this.handleElement.is( event.target ) ) {
+ return;
+ }
+
+ // support: IE9
+ // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
+ try {
+
+ // Support: IE9, IE10
+ // If the <body> is blurred, IE will switch windows, see #9520
+ if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) {
+
+ // Blur any element that currently has focus, see #4261
+ $( document.activeElement ).blur();
+ }
+ } catch ( error ) {}
+ },
+
+ _mouseStart: function(event) {
+
+ var o = this.options;
+
+ //Create and append the visible helper
+ this.helper = this._createHelper(event);
+
+ this.helper.addClass("ui-draggable-dragging");
+
+ //Cache the helper size
+ this._cacheHelperProportions();
+
+ //If ddmanager is used for droppables, set the global draggable
+ if ($.ui.ddmanager) {
+ $.ui.ddmanager.current = this;
+ }
+
+ /*
+ * - Position generation -
+ * This block generates everything position related - it's the core of draggables.
+ */
+
+ //Cache the margins of the original element
+ this._cacheMargins();
+
+ //Store the helper's css position
+ this.cssPosition = this.helper.css( "position" );
+ this.scrollParent = this.helper.scrollParent( true );
+ this.offsetParent = this.helper.offsetParent();
+ this.hasFixedAncestor = this.helper.parents().filter(function() {
+ return $( this ).css( "position" ) === "fixed";
+ }).length > 0;
+
+ //The element's absolute position on the page minus margins
+ this.positionAbs = this.element.offset();
+ this._refreshOffsets( event );
+
+ //Generate the original position
+ this.originalPosition = this.position = this._generatePosition( event, false );
+ this.originalPageX = event.pageX;
+ this.originalPageY = event.pageY;
+
+ //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
+ (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
+
+ //Set a containment if given in the options
+ this._setContainment();
+
+ //Trigger event + callbacks
+ if (this._trigger("start", event) === false) {
+ this._clear();
+ return false;
+ }
+
+ //Recache the helper size
+ this._cacheHelperProportions();
+
+ //Prepare the droppable offsets
+ if ($.ui.ddmanager && !o.dropBehaviour) {
+ $.ui.ddmanager.prepareOffsets(this, event);
+ }
+
+ // Reset helper's right/bottom css if they're set and set explicit width/height instead
+ // as this prevents resizing of elements with right/bottom set (see #7772)
+ this._normalizeRightBottom();
+
+ this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
+
+ //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
+ if ( $.ui.ddmanager ) {
+ $.ui.ddmanager.dragStart(this, event);
+ }
+
+ return true;
+ },
+
+ _refreshOffsets: function( event ) {
+ this.offset = {
+ top: this.positionAbs.top - this.margins.top,
+ left: this.positionAbs.left - this.margins.left,
+ scroll: false,
+ parent: this._getParentOffset(),
+ relative: this._getRelativeOffset()
+ };
+
+ this.offset.click = {
+ left: event.pageX - this.offset.left,
+ top: event.pageY - this.offset.top
+ };
+ },
+
+ _mouseDrag: function(event, noPropagation) {
+ // reset any necessary cached properties (see #5009)
+ if ( this.hasFixedAncestor ) {
+ this.offset.parent = this._getParentOffset();
+ }
+
+ //Compute the helpers position
+ this.position = this._generatePosition( event, true );
+ this.positionAbs = this._convertPositionTo("absolute");
+
+ //Call plugins and callbacks and use the resulting position if something is returned
+ if (!noPropagation) {
+ var ui = this._uiHash();
+ if (this._trigger("drag", event, ui) === false) {
+ this._mouseUp({});
+ return false;
+ }
+ this.position = ui.position;
+ }
+
+ this.helper[ 0 ].style.left = this.position.left + "px";
+ this.helper[ 0 ].style.top = this.position.top + "px";
+
+ if ($.ui.ddmanager) {
+ $.ui.ddmanager.drag(this, event);
+ }
+
+ return false;
+ },
+
+ _mouseStop: function(event) {
+
+ //If we are using droppables, inform the manager about the drop
+ var that = this,
+ dropped = false;
+ if ($.ui.ddmanager && !this.options.dropBehaviour) {
+ dropped = $.ui.ddmanager.drop(this, event);
+ }
+
+ //if a drop comes from outside (a sortable)
+ if (this.dropped) {
+ dropped = this.dropped;
+ this.dropped = false;
+ }
+
+ if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
+ $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
+ if (that._trigger("stop", event) !== false) {
+ that._clear();
+ }
+ });
+ } else {
+ if (this._trigger("stop", event) !== false) {
+ this._clear();
+ }
+ }
+
+ return false;
+ },
+
+ _mouseUp: function( event ) {
+ this._unblockFrames();
+
+ //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
+ if ( $.ui.ddmanager ) {
+ $.ui.ddmanager.dragStop(this, event);
+ }
+
+ // Only need to focus if the event occurred on the draggable itself, see #10527
+ if ( this.handleElement.is( event.target ) ) {
+ // The interaction is over; whether or not the click resulted in a drag, focus the element
+ this.element.focus();
+ }
+
+ return $.ui.mouse.prototype._mouseUp.call(this, event);
+ },
+
+ cancel: function() {
+
+ if (this.helper.is(".ui-draggable-dragging")) {
+ this._mouseUp({});
+ } else {
+ this._clear();
+ }
+
+ return this;
+
+ },
+
+ _getHandle: function(event) {
+ return this.options.handle ?
+ !!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
+ true;
+ },
+
+ _setHandleClassName: function() {
+ this.handleElement = this.options.handle ?
+ this.element.find( this.options.handle ) : this.element;
+ this.handleElement.addClass( "ui-draggable-handle" );
+ },
+
+ _removeHandleClassName: function() {
+ this.handleElement.removeClass( "ui-draggable-handle" );
+ },
+
+ _createHelper: function(event) {
+
+ var o = this.options,
+ helperIsFunction = $.isFunction( o.helper ),
+ helper = helperIsFunction ?
+ $( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
+ ( o.helper === "clone" ?
+ this.element.clone().removeAttr( "id" ) :
+ this.element );
+
+ if (!helper.parents("body").length) {
+ helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
+ }
+
+ // http://bugs.jqueryui.com/ticket/9446
+ // a helper function can return the original element
+ // which wouldn't have been set to relative in _create
+ if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
+ this._setPositionRelative();
+ }
+
+ if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
+ helper.css("position", "absolute");
+ }
+
+ return helper;
+
+ },
+
+ _setPositionRelative: function() {
+ if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
+ this.element[ 0 ].style.position = "relative";
+ }
+ },
+
+ _adjustOffsetFromHelper: function(obj) {
+ if (typeof obj === "string") {
+ obj = obj.split(" ");
+ }
+ if ($.isArray(obj)) {
+ obj = { left: +obj[0], top: +obj[1] || 0 };
+ }
+ if ("left" in obj) {
+ this.offset.click.left = obj.left + this.margins.left;
+ }
+ if ("right" in obj) {
+ this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
+ }
+ if ("top" in obj) {
+ this.offset.click.top = obj.top + this.margins.top;
+ }
+ if ("bottom" in obj) {
+ this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
+ }
+ },
+
+ _isRootNode: function( element ) {
+ return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
+ },
+
+ _getParentOffset: function() {
+
+ //Get the offsetParent and cache its position
+ var po = this.offsetParent.offset(),
+ document = this.document[ 0 ];
+
+ // This is a special case where we need to modify a offset calculated on start, since the following happened:
+ // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
+ // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
+ // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
+ if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
+ po.left += this.scrollParent.scrollLeft();
+ po.top += this.scrollParent.scrollTop();
+ }
+
+ if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
+ po = { top: 0, left: 0 };
+ }
+
+ return {
+ top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
+ left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
+ };
+
+ },
+
+ _getRelativeOffset: function() {
+ if ( this.cssPosition !== "relative" ) {
+ return { top: 0, left: 0 };
+ }
+
+ var p = this.element.position(),
+ scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );
+
+ return {
+ top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
+ left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
+ };
+
+ },
+
+ _cacheMargins: function() {
+ this.margins = {
+ left: (parseInt(this.element.css("marginLeft"), 10) || 0),
+ top: (parseInt(this.element.css("marginTop"), 10) || 0),
+ right: (parseInt(this.element.css("marginRight"), 10) || 0),
+ bottom: (parseInt(this.element.css("marginBottom"), 10) || 0)
+ };
+ },
+
+ _cacheHelperProportions: function() {
+ this.helperProportions = {
+ width: this.helper.outerWidth(),
+ height: this.helper.outerHeight()
+ };
+ },
+
+ _setContainment: function() {
+
+ var isUserScrollable, c, ce,
+ o = this.options,
+ document = this.document[ 0 ];
+
+ this.relativeContainer = null;
+
+ if ( !o.containment ) {
+ this.containment = null;
+ return;
+ }
+
+ if ( o.containment === "window" ) {
+ this.containment = [
+ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
+ $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
+ $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left,
+ $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
+ ];
+ return;
+ }
+
+ if ( o.containment === "document") {
+ this.containment = [
+ 0,
+ 0,
+ $( document ).width() - this.helperProportions.width - this.margins.left,
+ ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
+ ];
+ return;
+ }
+
+ if ( o.containment.constructor === Array ) {
+ this.containment = o.containment;
+ return;
+ }
+
+ if ( o.containment === "parent" ) {
+ o.containment = this.helper[ 0 ].parentNode;
+ }
+
+ c = $( o.containment );
+ ce = c[ 0 ];
+
+ if ( !ce ) {
+ return;
+ }
+
+ isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );
+
+ this.containment = [
+ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
+ ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
+ ( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
+ ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
+ ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
+ this.helperProportions.width -
+ this.margins.left -
+ this.margins.right,
+ ( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
+ ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
+ ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
+ this.helperProportions.height -
+ this.margins.top -
+ this.margins.bottom
+ ];
+ this.relativeContainer = c;
+ },
+
+ _convertPositionTo: function(d, pos) {
+
+ if (!pos) {
+ pos = this.position;
+ }
+
+ var mod = d === "absolute" ? 1 : -1,
+ scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );
+
+ return {
+ top: (
+ pos.top + // The absolute mouse position
+ this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod)
+ ),
+ left: (
+ pos.left + // The absolute mouse position
+ this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod)
+ )
+ };
+
+ },
+
+ _generatePosition: function( event, constrainPosition ) {
+
+ var containment, co, top, left,
+ o = this.options,
+ scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
+ pageX = event.pageX,
+ pageY = event.pageY;
+
+ // Cache the scroll
+ if ( !scrollIsRootNode || !this.offset.scroll ) {
+ this.offset.scroll = {
+ top: this.scrollParent.scrollTop(),
+ left: this.scrollParent.scrollLeft()
+ };
+ }
+
+ /*
+ * - Position constraining -
+ * Constrain the position to a mix of grid, containment.
+ */
+
+ // If we are not dragging yet, we won't check for options
+ if ( constrainPosition ) {
+ if ( this.containment ) {
+ if ( this.relativeContainer ){
+ co = this.relativeContainer.offset();
+ containment = [
+ this.containment[ 0 ] + co.left,
+ this.containment[ 1 ] + co.top,
+ this.containment[ 2 ] + co.left,
+ this.containment[ 3 ] + co.top
+ ];
+ } else {
+ containment = this.containment;
+ }
+
+ if (event.pageX - this.offset.click.left < containment[0]) {
+ pageX = containment[0] + this.offset.click.left;
+ }
+ if (event.pageY - this.offset.click.top < containment[1]) {
+ pageY = containment[1] + this.offset.click.top;
+ }
+ if (event.pageX - this.offset.click.left > containment[2]) {
+ pageX = containment[2] + this.offset.click.left;
+ }
+ if (event.pageY - this.offset.click.top > containment[3]) {
+ pageY = containment[3] + this.offset.click.top;
+ }
+ }
+
+ if (o.grid) {
+ //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
+ top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
+ pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
+
+ left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
+ pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
+ }
+
+ if ( o.axis === "y" ) {
+ pageX = this.originalPageX;
+ }
+
+ if ( o.axis === "x" ) {
+ pageY = this.originalPageY;
+ }
+ }
+
+ return {
+ top: (
+ pageY - // The absolute mouse position
+ this.offset.click.top - // Click offset (relative to the element)
+ this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
+ ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
+ ),
+ left: (
+ pageX - // The absolute mouse position
+ this.offset.click.left - // Click offset (relative to the element)
+ this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
+ ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
+ )
+ };
+
+ },
+
+ _clear: function() {
+ this.helper.removeClass("ui-draggable-dragging");
+ if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
+ this.helper.remove();
+ }
+ this.helper = null;
+ this.cancelHelperRemoval = false;
+ if ( this.destroyOnClear ) {
+ this.destroy();
+ }
+ },
+
+ _normalizeRightBottom: function() {
+ if ( this.options.axis !== "y" && this.helper.css( "right" ) !== "auto" ) {
+ this.helper.width( this.helper.width() );
+ this.helper.css( "right", "auto" );
+ }
+ if ( this.options.axis !== "x" && this.helper.css( "bottom" ) !== "auto" ) {
+ this.helper.height( this.helper.height() );
+ this.helper.css( "bottom", "auto" );
+ }
+ },
+
+ // From now on bulk stuff - mainly helpers
+
+ _trigger: function( type, event, ui ) {
+ ui = ui || this._uiHash();
+ $.ui.plugin.call( this, type, [ event, ui, this ], true );
+
+ // Absolute position and offset (see #6884 ) have to be recalculated after plugins
+ if ( /^(drag|start|stop)/.test( type ) ) {
+ this.positionAbs = this._convertPositionTo( "absolute" );
+ ui.offset = this.positionAbs;
+ }
+ return $.Widget.prototype._trigger.call( this, type, event, ui );
+ },
+
+ plugins: {},
+
+ _uiHash: function() {
+ return {
+ helper: this.helper,
+ position: this.position,
+ originalPosition: this.originalPosition,
+ offset: this.positionAbs
+ };
+ }
+
+});
+
+$.ui.plugin.add( "draggable", "connectToSortable", {
+ start: function( event, ui, draggable ) {
+ var uiSortable = $.extend( {}, ui, {
+ item: draggable.element
+ });
+
+ draggable.sortables = [];
+ $( draggable.options.connectToSortable ).each(function() {
+ var sortable = $( this ).sortable( "instance" );
+
+ if ( sortable && !sortable.options.disabled ) {
+ draggable.sortables.push( sortable );
+
+ // refreshPositions is called at drag start to refresh the containerCache
+ // which is used in drag. This ensures it's initialized and synchronized
+ // with any changes that might have happened on the page since initialization.
+ sortable.refreshPositions();
+ sortable._trigger("activate", event, uiSortable);
+ }
+ });
+ },
+ stop: function( event, ui, draggable ) {
+ var uiSortable = $.extend( {}, ui, {
+ item: draggable.element
+ });
+
+ draggable.cancelHelperRemoval = false;
+
+ $.each( draggable.sortables, function() {
+ var sortable = this;
+
+ if ( sortable.isOver ) {
+ sortable.isOver = 0;
+
+ // Allow this sortable to handle removing the helper
+ draggable.cancelHelperRemoval = true;
+ sortable.cancelHelperRemoval = false;
+
+ // Use _storedCSS To restore properties in the sortable,
+ // as this also handles revert (#9675) since the draggable
+ // may have modified them in unexpected ways (#8809)
+ sortable._storedCSS = {
+ position: sortable.placeholder.css( "position" ),
+ top: sortable.placeholder.css( "top" ),
+ left: sortable.placeholder.css( "left" )
+ };
+
+ sortable._mouseStop(event);
+
+ // Once drag has ended, the sortable should return to using
+ // its original helper, not the shared helper from draggable
+ sortable.options.helper = sortable.options._helper;
+ } else {
+ // Prevent this Sortable from removing the helper.
+ // However, don't set the draggable to remove the helper
+ // either as another connected Sortable may yet handle the removal.
+ sortable.cancelHelperRemoval = true;
+
+ sortable._trigger( "deactivate", event, uiSortable );
+ }
+ });
+ },
+ drag: function( event, ui, draggable ) {
+ $.each( draggable.sortables, function() {
+ var innermostIntersecting = false,
+ sortable = this;
+
+ // Copy over variables that sortable's _intersectsWith uses
+ sortable.positionAbs = draggable.positionAbs;
+ sortable.helperProportions = draggable.helperProportions;
+ sortable.offset.click = draggable.offset.click;
+
+ if ( sortable._intersectsWith( sortable.containerCache ) ) {
+ innermostIntersecting = true;
+
+ $.each( draggable.sortables, function() {
+ // Copy over variables that sortable's _intersectsWith uses
+ this.positionAbs = draggable.positionAbs;
+ this.helperProportions = draggable.helperProportions;
+ this.offset.click = draggable.offset.click;
+
+ if ( this !== sortable &&
+ this._intersectsWith( this.containerCache ) &&
+ $.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
+ innermostIntersecting = false;
+ }
+
+ return innermostIntersecting;
+ });
+ }
+
+ if ( innermostIntersecting ) {
+ // If it intersects, we use a little isOver variable and set it once,
+ // so that the move-in stuff gets fired only once.
+ if ( !sortable.isOver ) {
+ sortable.isOver = 1;
+
+ sortable.currentItem = ui.helper
+ .appendTo( sortable.element )
+ .data( "ui-sortable-item", true );
+
+ // Store helper option to later restore it
+ sortable.options._helper = sortable.options.helper;
+
+ sortable.options.helper = function() {
+ return ui.helper[ 0 ];
+ };
+
+ // Fire the start events of the sortable with our passed browser event,
+ // and our own helper (so it doesn't create a new one)
+ event.target = sortable.currentItem[ 0 ];
+ sortable._mouseCapture( event, true );
+ sortable._mouseStart( event, true, true );
+
+ // Because the browser event is way off the new appended portlet,
+ // modify necessary variables to reflect the changes
+ sortable.offset.click.top = draggable.offset.click.top;
+ sortable.offset.click.left = draggable.offset.click.left;
+ sortable.offset.parent.left -= draggable.offset.parent.left -
+ sortable.offset.parent.left;
+ sortable.offset.parent.top -= draggable.offset.parent.top -
+ sortable.offset.parent.top;
+
+ draggable._trigger( "toSortable", event );
+
+ // Inform draggable that the helper is in a valid drop zone,
+ // used solely in the revert option to handle "valid/invalid".
+ draggable.dropped = sortable.element;
+
+ // Need to refreshPositions of all sortables in the case that
+ // adding to one sortable changes the location of the other sortables (#9675)
+ $.each( draggable.sortables, function() {
+ this.refreshPositions();
+ });
+
+ // hack so receive/update callbacks work (mostly)
+ draggable.currentItem = draggable.element;
+ sortable.fromOutside = draggable;
+ }
+
+ if ( sortable.currentItem ) {
+ sortable._mouseDrag( event );
+ // Copy the sortable's position because the draggable's can potentially reflect
+ // a relative position, while sortable is always absolute, which the dragged
+ // element has now become. (#8809)
+ ui.position = sortable.position;
+ }
+ } else {
+ // If it doesn't intersect with the sortable, and it intersected before,
+ // we fake the drag stop of the sortable, but make sure it doesn't remove
+ // the helper by using cancelHelperRemoval.
+ if ( sortable.isOver ) {
+
+ sortable.isOver = 0;
+ sortable.cancelHelperRemoval = true;
+
+ // Calling sortable's mouseStop would trigger a revert,
+ // so revert must be temporarily false until after mouseStop is called.
+ sortable.options._revert = sortable.options.revert;
+ sortable.options.revert = false;
+
+ sortable._trigger( "out", event, sortable._uiHash( sortable ) );
+ sortable._mouseStop( event, true );
+
+ // restore sortable behaviors that were modfied
+ // when the draggable entered the sortable area (#9481)
+ sortable.options.revert = sortable.options._revert;
+ sortable.options.helper = sortable.options._helper;
+
+ if ( sortable.placeholder ) {
+ sortable.placeholder.remove();
+ }
+
+ // Recalculate the draggable's offset considering the sortable
+ // may have modified them in unexpected ways (#8809)
+ draggable._refreshOffsets( event );
+ ui.position = draggable._generatePosition( event, true );
+
+ draggable._trigger( "fromSortable", event );
+
+ // Inform draggable that the helper is no longer in a valid drop zone
+ draggable.dropped = false;
+
+ // Need to refreshPositions of all sortables just in case removing
+ // from one sortable changes the location of other sortables (#9675)
+ $.each( draggable.sortables, function() {
+ this.refreshPositions();
+ });
+ }
+ }
+ });
+ }
+});
+
+$.ui.plugin.add("draggable", "cursor", {
+ start: function( event, ui, instance ) {
+ var t = $( "body" ),
+ o = instance.options;
+
+ if (t.css("cursor")) {
+ o._cursor = t.css("cursor");
+ }
+ t.css("cursor", o.cursor);
+ },
+ stop: function( event, ui, instance ) {
+ var o = instance.options;
+ if (o._cursor) {
+ $("body").css("cursor", o._cursor);
+ }
+ }
+});
+
+$.ui.plugin.add("draggable", "opacity", {
+ start: function( event, ui, instance ) {
+ var t = $( ui.helper ),
+ o = instance.options;
+ if (t.css("opacity")) {
+ o._opacity = t.css("opacity");
+ }
+ t.css("opacity", o.opacity);
+ },
+ stop: function( event, ui, instance ) {
+ var o = instance.options;
+ if (o._opacity) {
+ $(ui.helper).css("opacity", o._opacity);
+ }
+ }
+});
+
+$.ui.plugin.add("draggable", "scroll", {
+ start: function( event, ui, i ) {
+ if ( !i.scrollParentNotHidden ) {
+ i.scrollParentNotHidden = i.helper.scrollParent( false );
+ }
+
+ if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] && i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
+ i.overflowOffset = i.scrollParentNotHidden.offset();
+ }
+ },
+ drag: function( event, ui, i ) {
+
+ var o = i.options,
+ scrolled = false,
+ scrollParent = i.scrollParentNotHidden[ 0 ],
+ document = i.document[ 0 ];
+
+ if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
+ if ( !o.axis || o.axis !== "x" ) {
+ if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY < o.scrollSensitivity ) {
+ scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
+ } else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
+ scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
+ }
+ }
+
+ if ( !o.axis || o.axis !== "y" ) {
+ if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX < o.scrollSensitivity ) {
+ scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
+ } else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
+ scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
+ }
+ }
+
+ } else {
+
+ if (!o.axis || o.axis !== "x") {
+ if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
+ scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
+ } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
+ scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
+ }
+ }
+
+ if (!o.axis || o.axis !== "y") {
+ if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
+ scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
+ } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
+ scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
+ }
+ }
+
+ }
+
+ if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
+ $.ui.ddmanager.prepareOffsets(i, event);
+ }
+
+ }
+});
+
+$.ui.plugin.add("draggable", "snap", {
+ start: function( event, ui, i ) {
+
+ var o = i.options;
+
+ i.snapElements = [];
+
+ $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
+ var $t = $(this),
+ $o = $t.offset();
+ if (this !== i.element[0]) {
+ i.snapElements.push({
+ item: this,
+ width: $t.outerWidth(), height: $t.outerHeight(),
+ top: $o.top, left: $o.left
+ });
+ }
+ });
+
+ },
+ drag: function( event, ui, inst ) {
+
+ var ts, bs, ls, rs, l, r, t, b, i, first,
+ o = inst.options,
+ d = o.snapTolerance,
+ x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
+ y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
+
+ for (i = inst.snapElements.length - 1; i >= 0; i--){
+
+ l = inst.snapElements[i].left - inst.margins.left;
+ r = l + inst.snapElements[i].width;
+ t = inst.snapElements[i].top - inst.margins.top;
+ b = t + inst.snapElements[i].height;
+
+ if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) {
+ if (inst.snapElements[i].snapping) {
+ (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
+ }
+ inst.snapElements[i].snapping = false;
+ continue;
+ }
+
+ if (o.snapMode !== "inner") {
+ ts = Math.abs(t - y2) <= d;
+ bs = Math.abs(b - y1) <= d;
+ ls = Math.abs(l - x2) <= d;
+ rs = Math.abs(r - x1) <= d;
+ if (ts) {
+ ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
+ }
+ if (bs) {
+ ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top;
+ }
+ if (ls) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
+ }
+ if (rs) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left;
+ }
+ }
+
+ first = (ts || bs || ls || rs);
+
+ if (o.snapMode !== "outer") {
+ ts = Math.abs(t - y1) <= d;
+ bs = Math.abs(b - y2) <= d;
+ ls = Math.abs(l - x1) <= d;
+ rs = Math.abs(r - x2) <= d;
+ if (ts) {
+ ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top;
+ }
+ if (bs) {
+ ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
+ }
+ if (ls) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left;
+ }
+ if (rs) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
+ }
+ }
+
+ if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
+ (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
+ }
+ inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
+
+ }
+
+ }
+});
+
+$.ui.plugin.add("draggable", "stack", {
+ start: function( event, ui, instance ) {
+ var min,
+ o = instance.options,
+ group = $.makeArray($(o.stack)).sort(function(a, b) {
+ return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0);
+ });
+
+ if (!group.length) { return; }
+
+ min = parseInt($(group[0]).css("zIndex"), 10) || 0;
+ $(group).each(function(i) {
+ $(this).css("zIndex", min + i);
+ });
+ this.css("zIndex", (min + group.length));
+ }
+});
+
+$.ui.plugin.add("draggable", "zIndex", {
+ start: function( event, ui, instance ) {
+ var t = $( ui.helper ),
+ o = instance.options;
+
+ if (t.css("zIndex")) {
+ o._zIndex = t.css("zIndex");
+ }
+ t.css("zIndex", o.zIndex);
+ },
+ stop: function( event, ui, instance ) {
+ var o = instance.options;
+
+ if (o._zIndex) {
+ $(ui.helper).css("zIndex", o._zIndex);
+ }
+ }
+});
+
+var draggable = $.ui.draggable;
+
+
+/*!
+ * jQuery UI Resizable 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/resizable/
+ */
+
+
+$.widget("ui.resizable", $.ui.mouse, {
+ version: "1.11.2",
+ widgetEventPrefix: "resize",
+ options: {
+ alsoResize: false,
+ animate: false,
+ animateDuration: "slow",
+ animateEasing: "swing",
+ aspectRatio: false,
+ autoHide: false,
+ containment: false,
+ ghost: false,
+ grid: false,
+ handles: "e,s,se",
+ helper: false,
+ maxHeight: null,
+ maxWidth: null,
+ minHeight: 10,
+ minWidth: 10,
+ // See #7960
+ zIndex: 90,
+
+ // callbacks
+ resize: null,
+ start: null,
+ stop: null
+ },
+
+ _num: function( value ) {
+ return parseInt( value, 10 ) || 0;
+ },
+
+ _isNumber: function( value ) {
+ return !isNaN( parseInt( value, 10 ) );
+ },
+
+ _hasScroll: function( el, a ) {
+
+ if ( $( el ).css( "overflow" ) === "hidden") {
+ return false;
+ }
+
+ var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
+ has = false;
+
+ if ( el[ scroll ] > 0 ) {
+ return true;
+ }
+
+ // TODO: determine which cases actually cause this to happen
+ // if the element doesn't have the scroll set, see if it's possible to
+ // set the scroll
+ el[ scroll ] = 1;
+ has = ( el[ scroll ] > 0 );
+ el[ scroll ] = 0;
+ return has;
+ },
+
+ _create: function() {
+
+ var n, i, handle, axis, hname,
+ that = this,
+ o = this.options;
+ this.element.addClass("ui-resizable");
+
+ $.extend(this, {
+ _aspectRatio: !!(o.aspectRatio),
+ aspectRatio: o.aspectRatio,
+ originalElement: this.element,
+ _proportionallyResizeElements: [],
+ _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
+ });
+
+ // Wrap the element if it cannot hold child nodes
+ if (this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
+
+ this.element.wrap(
+ $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
+ position: this.element.css("position"),
+ width: this.element.outerWidth(),
+ height: this.element.outerHeight(),
+ top: this.element.css("top"),
+ left: this.element.css("left")
+ })
+ );
+
+ this.element = this.element.parent().data(
+ "ui-resizable", this.element.resizable( "instance" )
+ );
+
+ this.elementIsWrapper = true;
+
+ this.element.css({
+ marginLeft: this.originalElement.css("marginLeft"),
+ marginTop: this.originalElement.css("marginTop"),
+ marginRight: this.originalElement.css("marginRight"),
+ marginBottom: this.originalElement.css("marginBottom")
+ });
+ this.originalElement.css({
+ marginLeft: 0,
+ marginTop: 0,
+ marginRight: 0,
+ marginBottom: 0
+ });
+ // support: Safari
+ // Prevent Safari textarea resize
+ this.originalResizeStyle = this.originalElement.css("resize");
+ this.originalElement.css("resize", "none");
+
+ this._proportionallyResizeElements.push( this.originalElement.css({
+ position: "static",
+ zoom: 1,
+ display: "block"
+ }) );
+
+ // support: IE9
+ // avoid IE jump (hard set the margin)
+ this.originalElement.css({ margin: this.originalElement.css("margin") });
+
+ this._proportionallyResize();
+ }
+
+ this.handles = o.handles ||
+ ( !$(".ui-resizable-handle", this.element).length ?
+ "e,s,se" : {
+ n: ".ui-resizable-n",
+ e: ".ui-resizable-e",
+ s: ".ui-resizable-s",
+ w: ".ui-resizable-w",
+ se: ".ui-resizable-se",
+ sw: ".ui-resizable-sw",
+ ne: ".ui-resizable-ne",
+ nw: ".ui-resizable-nw"
+ } );
+
+ if (this.handles.constructor === String) {
+
+ if ( this.handles === "all") {
+ this.handles = "n,e,s,w,se,sw,ne,nw";
+ }
+
+ n = this.handles.split(",");
+ this.handles = {};
+
+ for (i = 0; i < n.length; i++) {
+
+ handle = $.trim(n[i]);
+ hname = "ui-resizable-" + handle;
+ axis = $("<div class='ui-resizable-handle " + hname + "'></div>");
+
+ axis.css({ zIndex: o.zIndex });
+
+ // TODO : What's going on here?
+ if ("se" === handle) {
+ axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
+ }
+
+ this.handles[handle] = ".ui-resizable-" + handle;
+ this.element.append(axis);
+ }
+
+ }
+
+ this._renderAxis = function(target) {
+
+ var i, axis, padPos, padWrapper;
+
+ target = target || this.element;
+
+ for (i in this.handles) {
+
+ if (this.handles[i].constructor === String) {
+ this.handles[i] = this.element.children( this.handles[ i ] ).first().show();
+ }
+
+ if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
+
+ axis = $(this.handles[i], this.element);
+
+ padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
+
+ padPos = [ "padding",
+ /ne|nw|n/.test(i) ? "Top" :
+ /se|sw|s/.test(i) ? "Bottom" :
+ /^e$/.test(i) ? "Right" : "Left" ].join("");
+
+ target.css(padPos, padWrapper);
+
+ this._proportionallyResize();
+
+ }
+
+ // TODO: What's that good for? There's not anything to be executed left
+ if (!$(this.handles[i]).length) {
+ continue;
+ }
+ }
+ };
+
+ // TODO: make renderAxis a prototype function
+ this._renderAxis(this.element);
+
+ this._handles = $(".ui-resizable-handle", this.element)
+ .disableSelection();
+
+ this._handles.mouseover(function() {
+ if (!that.resizing) {
+ if (this.className) {
+ axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
+ }
+ that.axis = axis && axis[1] ? axis[1] : "se";
+ }
+ });
+
+ if (o.autoHide) {
+ this._handles.hide();
+ $(this.element)
+ .addClass("ui-resizable-autohide")
+ .mouseenter(function() {
+ if (o.disabled) {
+ return;
+ }
+ $(this).removeClass("ui-resizable-autohide");
+ that._handles.show();
+ })
+ .mouseleave(function() {
+ if (o.disabled) {
+ return;
+ }
+ if (!that.resizing) {
+ $(this).addClass("ui-resizable-autohide");
+ that._handles.hide();
+ }
+ });
+ }
+
+ this._mouseInit();
+
+ },
+
+ _destroy: function() {
+
+ this._mouseDestroy();
+
+ var wrapper,
+ _destroy = function(exp) {
+ $(exp)
+ .removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
+ .removeData("resizable")
+ .removeData("ui-resizable")
+ .unbind(".resizable")
+ .find(".ui-resizable-handle")
+ .remove();
+ };
+
+ // TODO: Unwrap at same DOM position
+ if (this.elementIsWrapper) {
+ _destroy(this.element);
+ wrapper = this.element;
+ this.originalElement.css({
+ position: wrapper.css("position"),
+ width: wrapper.outerWidth(),
+ height: wrapper.outerHeight(),
+ top: wrapper.css("top"),
+ left: wrapper.css("left")
+ }).insertAfter( wrapper );
+ wrapper.remove();
+ }
+
+ this.originalElement.css("resize", this.originalResizeStyle);
+ _destroy(this.originalElement);
+
+ return this;
+ },
+
+ _mouseCapture: function(event) {
+ var i, handle,
+ capture = false;
+
+ for (i in this.handles) {
+ handle = $(this.handles[i])[0];
+ if (handle === event.target || $.contains(handle, event.target)) {
+ capture = true;
+ }
+ }
+
+ return !this.options.disabled && capture;
+ },
+
+ _mouseStart: function(event) {
+
+ var curleft, curtop, cursor,
+ o = this.options,
+ el = this.element;
+
+ this.resizing = true;
+
+ this._renderProxy();
+
+ curleft = this._num(this.helper.css("left"));
+ curtop = this._num(this.helper.css("top"));
+
+ if (o.containment) {
+ curleft += $(o.containment).scrollLeft() || 0;
+ curtop += $(o.containment).scrollTop() || 0;
+ }
+
+ this.offset = this.helper.offset();
+ this.position = { left: curleft, top: curtop };
+
+ this.size = this._helper ? {
+ width: this.helper.width(),
+ height: this.helper.height()
+ } : {
+ width: el.width(),
+ height: el.height()
+ };
+
+ this.originalSize = this._helper ? {
+ width: el.outerWidth(),
+ height: el.outerHeight()
+ } : {
+ width: el.width(),
+ height: el.height()
+ };
+
+ this.sizeDiff = {
+ width: el.outerWidth() - el.width(),
+ height: el.outerHeight() - el.height()
+ };
+
+ this.originalPosition = { left: curleft, top: curtop };
+ this.originalMousePosition = { left: event.pageX, top: event.pageY };
+
+ this.aspectRatio = (typeof o.aspectRatio === "number") ?
+ o.aspectRatio :
+ ((this.originalSize.width / this.originalSize.height) || 1);
+
+ cursor = $(".ui-resizable-" + this.axis).css("cursor");
+ $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);
+
+ el.addClass("ui-resizable-resizing");
+ this._propagate("start", event);
+ return true;
+ },
+
+ _mouseDrag: function(event) {
+
+ var data, props,
+ smp = this.originalMousePosition,
+ a = this.axis,
+ dx = (event.pageX - smp.left) || 0,
+ dy = (event.pageY - smp.top) || 0,
+ trigger = this._change[a];
+
+ this._updatePrevProperties();
+
+ if (!trigger) {
+ return false;
+ }
+
+ data = trigger.apply(this, [ event, dx, dy ]);
+
+ this._updateVirtualBoundaries(event.shiftKey);
+ if (this._aspectRatio || event.shiftKey) {
+ data = this._updateRatio(data, event);
+ }
+
+ data = this._respectSize(data, event);
+
+ this._updateCache(data);
+
+ this._propagate("resize", event);
+
+ props = this._applyChanges();
+
+ if ( !this._helper && this._proportionallyResizeElements.length ) {
+ this._proportionallyResize();
+ }
+
+ if ( !$.isEmptyObject( props ) ) {
+ this._updatePrevProperties();
+ this._trigger( "resize", event, this.ui() );
+ this._applyChanges();
+ }
+
+ return false;
+ },
+
+ _mouseStop: function(event) {
+
+ this.resizing = false;
+ var pr, ista, soffseth, soffsetw, s, left, top,
+ o = this.options, that = this;
+
+ if (this._helper) {
+
+ pr = this._proportionallyResizeElements;
+ ista = pr.length && (/textarea/i).test(pr[0].nodeName);
+ soffseth = ista && this._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height;
+ soffsetw = ista ? 0 : that.sizeDiff.width;
+
+ s = {
+ width: (that.helper.width() - soffsetw),
+ height: (that.helper.height() - soffseth)
+ };
+ left = (parseInt(that.element.css("left"), 10) +
+ (that.position.left - that.originalPosition.left)) || null;
+ top = (parseInt(that.element.css("top"), 10) +
+ (that.position.top - that.originalPosition.top)) || null;
+
+ if (!o.animate) {
+ this.element.css($.extend(s, { top: top, left: left }));
+ }
+
+ that.helper.height(that.size.height);
+ that.helper.width(that.size.width);
+
+ if (this._helper && !o.animate) {
+ this._proportionallyResize();
+ }
+ }
+
+ $("body").css("cursor", "auto");
+
+ this.element.removeClass("ui-resizable-resizing");
+
+ this._propagate("stop", event);
+
+ if (this._helper) {
+ this.helper.remove();
+ }
+
+ return false;
+
+ },
+
+ _updatePrevProperties: function() {
+ this.prevPosition = {
+ top: this.position.top,
+ left: this.position.left
+ };
+ this.prevSize = {
+ width: this.size.width,
+ height: this.size.height
+ };
+ },
+
+ _applyChanges: function() {
+ var props = {};
+
+ if ( this.position.top !== this.prevPosition.top ) {
+ props.top = this.position.top + "px";
+ }
+ if ( this.position.left !== this.prevPosition.left ) {
+ props.left = this.position.left + "px";
+ }
+ if ( this.size.width !== this.prevSize.width ) {
+ props.width = this.size.width + "px";
+ }
+ if ( this.size.height !== this.prevSize.height ) {
+ props.height = this.size.height + "px";
+ }
+
+ this.helper.css( props );
+
+ return props;
+ },
+
+ _updateVirtualBoundaries: function(forceAspectRatio) {
+ var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
+ o = this.options;
+
+ b = {
+ minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0,
+ maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity,
+ minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0,
+ maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity
+ };
+
+ if (this._aspectRatio || forceAspectRatio) {
+ pMinWidth = b.minHeight * this.aspectRatio;
+ pMinHeight = b.minWidth / this.aspectRatio;
+ pMaxWidth = b.maxHeight * this.aspectRatio;
+ pMaxHeight = b.maxWidth / this.aspectRatio;
+
+ if (pMinWidth > b.minWidth) {
+ b.minWidth = pMinWidth;
+ }
+ if (pMinHeight > b.minHeight) {
+ b.minHeight = pMinHeight;
+ }
+ if (pMaxWidth < b.maxWidth) {
+ b.maxWidth = pMaxWidth;
+ }
+ if (pMaxHeight < b.maxHeight) {
+ b.maxHeight = pMaxHeight;
+ }
+ }
+ this._vBoundaries = b;
+ },
+
+ _updateCache: function(data) {
+ this.offset = this.helper.offset();
+ if (this._isNumber(data.left)) {
+ this.position.left = data.left;
+ }
+ if (this._isNumber(data.top)) {
+ this.position.top = data.top;
+ }
+ if (this._isNumber(data.height)) {
+ this.size.height = data.height;
+ }
+ if (this._isNumber(data.width)) {
+ this.size.width = data.width;
+ }
+ },
+
+ _updateRatio: function( data ) {
+
+ var cpos = this.position,
+ csize = this.size,
+ a = this.axis;
+
+ if (this._isNumber(data.height)) {
+ data.width = (data.height * this.aspectRatio);
+ } else if (this._isNumber(data.width)) {
+ data.height = (data.width / this.aspectRatio);
+ }
+
+ if (a === "sw") {
+ data.left = cpos.left + (csize.width - data.width);
+ data.top = null;
+ }
+ if (a === "nw") {
+ data.top = cpos.top + (csize.height - data.height);
+ data.left = cpos.left + (csize.width - data.width);
+ }
+
+ return data;
+ },
+
+ _respectSize: function( data ) {
+
+ var o = this._vBoundaries,
+ a = this.axis,
+ ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width),
+ ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
+ isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width),
+ isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
+ dw = this.originalPosition.left + this.originalSize.width,
+ dh = this.position.top + this.size.height,
+ cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
+ if (isminw) {
+ data.width = o.minWidth;
+ }
+ if (isminh) {
+ data.height = o.minHeight;
+ }
+ if (ismaxw) {
+ data.width = o.maxWidth;
+ }
+ if (ismaxh) {
+ data.height = o.maxHeight;
+ }
+
+ if (isminw && cw) {
+ data.left = dw - o.minWidth;
+ }
+ if (ismaxw && cw) {
+ data.left = dw - o.maxWidth;
+ }
+ if (isminh && ch) {
+ data.top = dh - o.minHeight;
+ }
+ if (ismaxh && ch) {
+ data.top = dh - o.maxHeight;
+ }
+
+ // Fixing jump error on top/left - bug #2330
+ if (!data.width && !data.height && !data.left && data.top) {
+ data.top = null;
+ } else if (!data.width && !data.height && !data.top && data.left) {
+ data.left = null;
+ }
+
+ return data;
+ },
+
+ _getPaddingPlusBorderDimensions: function( element ) {
+ var i = 0,
+ widths = [],
+ borders = [
+ element.css( "borderTopWidth" ),
+ element.css( "borderRightWidth" ),
+ element.css( "borderBottomWidth" ),
+ element.css( "borderLeftWidth" )
+ ],
+ paddings = [
+ element.css( "paddingTop" ),
+ element.css( "paddingRight" ),
+ element.css( "paddingBottom" ),
+ element.css( "paddingLeft" )
+ ];
+
+ for ( ; i < 4; i++ ) {
+ widths[ i ] = ( parseInt( borders[ i ], 10 ) || 0 );
+ widths[ i ] += ( parseInt( paddings[ i ], 10 ) || 0 );
+ }
+
+ return {
+ height: widths[ 0 ] + widths[ 2 ],
+ width: widths[ 1 ] + widths[ 3 ]
+ };
+ },
+
+ _proportionallyResize: function() {
+
+ if (!this._proportionallyResizeElements.length) {
+ return;
+ }
+
+ var prel,
+ i = 0,
+ element = this.helper || this.element;
+
+ for ( ; i < this._proportionallyResizeElements.length; i++) {
+
+ prel = this._proportionallyResizeElements[i];
+
+ // TODO: Seems like a bug to cache this.outerDimensions
+ // considering that we are in a loop.
+ if (!this.outerDimensions) {
+ this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
+ }
+
+ prel.css({
+ height: (element.height() - this.outerDimensions.height) || 0,
+ width: (element.width() - this.outerDimensions.width) || 0
+ });
+
+ }
+
+ },
+
+ _renderProxy: function() {
+
+ var el = this.element, o = this.options;
+ this.elementOffset = el.offset();
+
+ if (this._helper) {
+
+ this.helper = this.helper || $("<div style='overflow:hidden;'></div>");
+
+ this.helper.addClass(this._helper).css({
+ width: this.element.outerWidth() - 1,
+ height: this.element.outerHeight() - 1,
+ position: "absolute",
+ left: this.elementOffset.left + "px",
+ top: this.elementOffset.top + "px",
+ zIndex: ++o.zIndex //TODO: Don't modify option
+ });
+
+ this.helper
+ .appendTo("body")
+ .disableSelection();
+
+ } else {
+ this.helper = this.element;
+ }
+
+ },
+
+ _change: {
+ e: function(event, dx) {
+ return { width: this.originalSize.width + dx };
+ },
+ w: function(event, dx) {
+ var cs = this.originalSize, sp = this.originalPosition;
+ return { left: sp.left + dx, width: cs.width - dx };
+ },
+ n: function(event, dx, dy) {
+ var cs = this.originalSize, sp = this.originalPosition;
+ return { top: sp.top + dy, height: cs.height - dy };
+ },
+ s: function(event, dx, dy) {
+ return { height: this.originalSize.height + dy };
+ },
+ se: function(event, dx, dy) {
+ return $.extend(this._change.s.apply(this, arguments),
+ this._change.e.apply(this, [ event, dx, dy ]));
+ },
+ sw: function(event, dx, dy) {
+ return $.extend(this._change.s.apply(this, arguments),
+ this._change.w.apply(this, [ event, dx, dy ]));
+ },
+ ne: function(event, dx, dy) {
+ return $.extend(this._change.n.apply(this, arguments),
+ this._change.e.apply(this, [ event, dx, dy ]));
+ },
+ nw: function(event, dx, dy) {
+ return $.extend(this._change.n.apply(this, arguments),
+ this._change.w.apply(this, [ event, dx, dy ]));
+ }
+ },
+
+ _propagate: function(n, event) {
+ $.ui.plugin.call(this, n, [ event, this.ui() ]);
+ (n !== "resize" && this._trigger(n, event, this.ui()));
+ },
+
+ plugins: {},
+
+ ui: function() {
+ return {
+ originalElement: this.originalElement,
+ element: this.element,
+ helper: this.helper,
+ position: this.position,
+ size: this.size,
+ originalSize: this.originalSize,
+ originalPosition: this.originalPosition
+ };
+ }
+
+});
+
+/*
+ * Resizable Extensions
+ */
+
+$.ui.plugin.add("resizable", "animate", {
+
+ stop: function( event ) {
+ var that = $(this).resizable( "instance" ),
+ o = that.options,
+ pr = that._proportionallyResizeElements,
+ ista = pr.length && (/textarea/i).test(pr[0].nodeName),
+ soffseth = ista && that._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height,
+ soffsetw = ista ? 0 : that.sizeDiff.width,
+ style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
+ left = (parseInt(that.element.css("left"), 10) +
+ (that.position.left - that.originalPosition.left)) || null,
+ top = (parseInt(that.element.css("top"), 10) +
+ (that.position.top - that.originalPosition.top)) || null;
+
+ that.element.animate(
+ $.extend(style, top && left ? { top: top, left: left } : {}), {
+ duration: o.animateDuration,
+ easing: o.animateEasing,
+ step: function() {
+
+ var data = {
+ width: parseInt(that.element.css("width"), 10),
+ height: parseInt(that.element.css("height"), 10),
+ top: parseInt(that.element.css("top"), 10),
+ left: parseInt(that.element.css("left"), 10)
+ };
+
+ if (pr && pr.length) {
+ $(pr[0]).css({ width: data.width, height: data.height });
+ }
+
+ // propagating resize, and updating values for each animation step
+ that._updateCache(data);
+ that._propagate("resize", event);
+
+ }
+ }
+ );
+ }
+
+});
+
+$.ui.plugin.add( "resizable", "containment", {
+
+ start: function() {
+ var element, p, co, ch, cw, width, height,
+ that = $( this ).resizable( "instance" ),
+ o = that.options,
+ el = that.element,
+ oc = o.containment,
+ ce = ( oc instanceof $ ) ? oc.get( 0 ) : ( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;
+
+ if ( !ce ) {
+ return;
+ }
+
+ that.containerElement = $( ce );
+
+ if ( /document/.test( oc ) || oc === document ) {
+ that.containerOffset = {
+ left: 0,
+ top: 0
+ };
+ that.containerPosition = {
+ left: 0,
+ top: 0
+ };
+
+ that.parentData = {
+ element: $( document ),
+ left: 0,
+ top: 0,
+ width: $( document ).width(),
+ height: $( document ).height() || document.body.parentNode.scrollHeight
+ };
+ } else {
+ element = $( ce );
+ p = [];
+ $([ "Top", "Right", "Left", "Bottom" ]).each(function( i, name ) {
+ p[ i ] = that._num( element.css( "padding" + name ) );
+ });
+
+ that.containerOffset = element.offset();
+ that.containerPosition = element.position();
+ that.containerSize = {
+ height: ( element.innerHeight() - p[ 3 ] ),
+ width: ( element.innerWidth() - p[ 1 ] )
+ };
+
+ co = that.containerOffset;
+ ch = that.containerSize.height;
+ cw = that.containerSize.width;
+ width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw );
+ height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ;
+
+ that.parentData = {
+ element: ce,
+ left: co.left,
+ top: co.top,
+ width: width,
+ height: height
+ };
+ }
+ },
+
+ resize: function( event ) {
+ var woset, hoset, isParent, isOffsetRelative,
+ that = $( this ).resizable( "instance" ),
+ o = that.options,
+ co = that.containerOffset,
+ cp = that.position,
+ pRatio = that._aspectRatio || event.shiftKey,
+ cop = {
+ top: 0,
+ left: 0
+ },
+ ce = that.containerElement,
+ continueResize = true;
+
+ if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
+ cop = co;
+ }
+
+ if ( cp.left < ( that._helper ? co.left : 0 ) ) {
+ that.size.width = that.size.width +
+ ( that._helper ?
+ ( that.position.left - co.left ) :
+ ( that.position.left - cop.left ) );
+
+ if ( pRatio ) {
+ that.size.height = that.size.width / that.aspectRatio;
+ continueResize = false;
+ }
+ that.position.left = o.helper ? co.left : 0;
+ }
+
+ if ( cp.top < ( that._helper ? co.top : 0 ) ) {
+ that.size.height = that.size.height +
+ ( that._helper ?
+ ( that.position.top - co.top ) :
+ that.position.top );
+
+ if ( pRatio ) {
+ that.size.width = that.size.height * that.aspectRatio;
+ continueResize = false;
+ }
+ that.position.top = that._helper ? co.top : 0;
+ }
+
+ isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
+ isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );
+
+ if ( isParent && isOffsetRelative ) {
+ that.offset.left = that.parentData.left + that.position.left;
+ that.offset.top = that.parentData.top + that.position.top;
+ } else {
+ that.offset.left = that.element.offset().left;
+ that.offset.top = that.element.offset().top;
+ }
+
+ woset = Math.abs( that.sizeDiff.width +
+ (that._helper ?
+ that.offset.left - cop.left :
+ (that.offset.left - co.left)) );
+
+ hoset = Math.abs( that.sizeDiff.height +
+ (that._helper ?
+ that.offset.top - cop.top :
+ (that.offset.top - co.top)) );
+
+ if ( woset + that.size.width >= that.parentData.width ) {
+ that.size.width = that.parentData.width - woset;
+ if ( pRatio ) {
+ that.size.height = that.size.width / that.aspectRatio;
+ continueResize = false;
+ }
+ }
+
+ if ( hoset + that.size.height >= that.parentData.height ) {
+ that.size.height = that.parentData.height - hoset;
+ if ( pRatio ) {
+ that.size.width = that.size.height * that.aspectRatio;
+ continueResize = false;
+ }
+ }
+
+ if ( !continueResize ){
+ that.position.left = that.prevPosition.left;
+ that.position.top = that.prevPosition.top;
+ that.size.width = that.prevSize.width;
+ that.size.height = that.prevSize.height;
+ }
+ },
+
+ stop: function() {
+ var that = $( this ).resizable( "instance" ),
+ o = that.options,
+ co = that.containerOffset,
+ cop = that.containerPosition,
+ ce = that.containerElement,
+ helper = $( that.helper ),
+ ho = helper.offset(),
+ w = helper.outerWidth() - that.sizeDiff.width,
+ h = helper.outerHeight() - that.sizeDiff.height;
+
+ if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
+ $( this ).css({
+ left: ho.left - cop.left - co.left,
+ width: w,
+ height: h
+ });
+ }
+
+ if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
+ $( this ).css({
+ left: ho.left - cop.left - co.left,
+ width: w,
+ height: h
+ });
+ }
+ }
+});
+
+$.ui.plugin.add("resizable", "alsoResize", {
+
+ start: function() {
+ var that = $(this).resizable( "instance" ),
+ o = that.options,
+ _store = function(exp) {
+ $(exp).each(function() {
+ var el = $(this);
+ el.data("ui-resizable-alsoresize", {
+ width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
+ left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
+ });
+ });
+ };
+
+ if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) {
+ if (o.alsoResize.length) {
+ o.alsoResize = o.alsoResize[0];
+ _store(o.alsoResize);
+ } else {
+ $.each(o.alsoResize, function(exp) {
+ _store(exp);
+ });
+ }
+ } else {
+ _store(o.alsoResize);
+ }
+ },
+
+ resize: function(event, ui) {
+ var that = $(this).resizable( "instance" ),
+ o = that.options,
+ os = that.originalSize,
+ op = that.originalPosition,
+ delta = {
+ height: (that.size.height - os.height) || 0,
+ width: (that.size.width - os.width) || 0,
+ top: (that.position.top - op.top) || 0,
+ left: (that.position.left - op.left) || 0
+ },
+
+ _alsoResize = function(exp, c) {
+ $(exp).each(function() {
+ var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
+ css = c && c.length ?
+ c :
+ el.parents(ui.originalElement[0]).length ?
+ [ "width", "height" ] :
+ [ "width", "height", "top", "left" ];
+
+ $.each(css, function(i, prop) {
+ var sum = (start[prop] || 0) + (delta[prop] || 0);
+ if (sum && sum >= 0) {
+ style[prop] = sum || null;
+ }
+ });
+
+ el.css(style);
+ });
+ };
+
+ if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) {
+ $.each(o.alsoResize, function(exp, c) {
+ _alsoResize(exp, c);
+ });
+ } else {
+ _alsoResize(o.alsoResize);
+ }
+ },
+
+ stop: function() {
+ $(this).removeData("resizable-alsoresize");
+ }
+});
+
+$.ui.plugin.add("resizable", "ghost", {
+
+ start: function() {
+
+ var that = $(this).resizable( "instance" ), o = that.options, cs = that.size;
+
+ that.ghost = that.originalElement.clone();
+ that.ghost
+ .css({
+ opacity: 0.25,
+ display: "block",
+ position: "relative",
+ height: cs.height,
+ width: cs.width,
+ margin: 0,
+ left: 0,
+ top: 0
+ })
+ .addClass("ui-resizable-ghost")
+ .addClass(typeof o.ghost === "string" ? o.ghost : "");
+
+ that.ghost.appendTo(that.helper);
+
+ },
+
+ resize: function() {
+ var that = $(this).resizable( "instance" );
+ if (that.ghost) {
+ that.ghost.css({
+ position: "relative",
+ height: that.size.height,
+ width: that.size.width
+ });
+ }
+ },
+
+ stop: function() {
+ var that = $(this).resizable( "instance" );
+ if (that.ghost && that.helper) {
+ that.helper.get(0).removeChild(that.ghost.get(0));
+ }
+ }
+
+});
+
+$.ui.plugin.add("resizable", "grid", {
+
+ resize: function() {
+ var outerDimensions,
+ that = $(this).resizable( "instance" ),
+ o = that.options,
+ cs = that.size,
+ os = that.originalSize,
+ op = that.originalPosition,
+ a = that.axis,
+ grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
+ gridX = (grid[0] || 1),
+ gridY = (grid[1] || 1),
+ ox = Math.round((cs.width - os.width) / gridX) * gridX,
+ oy = Math.round((cs.height - os.height) / gridY) * gridY,
+ newWidth = os.width + ox,
+ newHeight = os.height + oy,
+ isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
+ isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
+ isMinWidth = o.minWidth && (o.minWidth > newWidth),
+ isMinHeight = o.minHeight && (o.minHeight > newHeight);
+
+ o.grid = grid;
+
+ if (isMinWidth) {
+ newWidth += gridX;
+ }
+ if (isMinHeight) {
+ newHeight += gridY;
+ }
+ if (isMaxWidth) {
+ newWidth -= gridX;
+ }
+ if (isMaxHeight) {
+ newHeight -= gridY;
+ }
+
+ if (/^(se|s|e)$/.test(a)) {
+ that.size.width = newWidth;
+ that.size.height = newHeight;
+ } else if (/^(ne)$/.test(a)) {
+ that.size.width = newWidth;
+ that.size.height = newHeight;
+ that.position.top = op.top - oy;
+ } else if (/^(sw)$/.test(a)) {
+ that.size.width = newWidth;
+ that.size.height = newHeight;
+ that.position.left = op.left - ox;
+ } else {
+ if ( newHeight - gridY <= 0 || newWidth - gridX <= 0) {
+ outerDimensions = that._getPaddingPlusBorderDimensions( this );
+ }
+
+ if ( newHeight - gridY > 0 ) {
+ that.size.height = newHeight;
+ that.position.top = op.top - oy;
+ } else {
+ newHeight = gridY - outerDimensions.height;
+ that.size.height = newHeight;
+ that.position.top = op.top + os.height - newHeight;
+ }
+ if ( newWidth - gridX > 0 ) {
+ that.size.width = newWidth;
+ that.position.left = op.left - ox;
+ } else {
+ newWidth = gridY - outerDimensions.height;
+ that.size.width = newWidth;
+ that.position.left = op.left + os.width - newWidth;
+ }
+ }
+ }
+
+});
+
+var resizable = $.ui.resizable;
+
+
+/*!
+ * jQuery UI Dialog 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/dialog/
+ */
+
+
+var dialog = $.widget( "ui.dialog", {
+ version: "1.11.2",
+ options: {
+ appendTo: "body",
+ autoOpen: true,
+ buttons: [],
+ closeOnEscape: true,
+ closeText: "Close",
+ dialogClass: "",
+ draggable: true,
+ hide: null,
+ height: "auto",
+ maxHeight: null,
+ maxWidth: null,
+ minHeight: 150,
+ minWidth: 150,
+ modal: false,
+ position: {
+ my: "center",
+ at: "center",
+ of: window,
+ collision: "fit",
+ // Ensure the titlebar is always visible
+ using: function( pos ) {
+ var topOffset = $( this ).css( pos ).offset().top;
+ if ( topOffset < 0 ) {
+ $( this ).css( "top", pos.top - topOffset );
+ }
+ }
+ },
+ resizable: true,
+ show: null,
+ title: null,
+ width: 300,
+
+ // callbacks
+ beforeClose: null,
+ close: null,
+ drag: null,
+ dragStart: null,
+ dragStop: null,
+ focus: null,
+ open: null,
+ resize: null,
+ resizeStart: null,
+ resizeStop: null
+ },
+
+ sizeRelatedOptions: {
+ buttons: true,
+ height: true,
+ maxHeight: true,
+ maxWidth: true,
+ minHeight: true,
+ minWidth: true,
+ width: true
+ },
+
+ resizableRelatedOptions: {
+ maxHeight: true,
+ maxWidth: true,
+ minHeight: true,
+ minWidth: true
+ },
+
+ _create: function() {
+ this.originalCss = {
+ display: this.element[ 0 ].style.display,
+ width: this.element[ 0 ].style.width,
+ minHeight: this.element[ 0 ].style.minHeight,
+ maxHeight: this.element[ 0 ].style.maxHeight,
+ height: this.element[ 0 ].style.height
+ };
+ this.originalPosition = {
+ parent: this.element.parent(),
+ index: this.element.parent().children().index( this.element )
+ };
+ this.originalTitle = this.element.attr( "title" );
+ this.options.title = this.options.title || this.originalTitle;
+
+ this._createWrapper();
+
+ this.element
+ .show()
+ .removeAttr( "title" )
+ .addClass( "ui-dialog-content ui-widget-content" )
+ .appendTo( this.uiDialog );
+
+ this._createTitlebar();
+ this._createButtonPane();
+
+ if ( this.options.draggable && $.fn.draggable ) {
+ this._makeDraggable();
+ }
+ if ( this.options.resizable && $.fn.resizable ) {
+ this._makeResizable();
+ }
+
+ this._isOpen = false;
+
+ this._trackFocus();
+ },
+
+ _init: function() {
+ if ( this.options.autoOpen ) {
+ this.open();
+ }
+ },
+
+ _appendTo: function() {
+ var element = this.options.appendTo;
+ if ( element && (element.jquery || element.nodeType) ) {
+ return $( element );
+ }
+ return this.document.find( element || "body" ).eq( 0 );
+ },
+
+ _destroy: function() {
+ var next,
+ originalPosition = this.originalPosition;
+
+ this._destroyOverlay();
+
+ this.element
+ .removeUniqueId()
+ .removeClass( "ui-dialog-content ui-widget-content" )
+ .css( this.originalCss )
+ // Without detaching first, the following becomes really slow
+ .detach();
+
+ this.uiDialog.stop( true, true ).remove();
+
+ if ( this.originalTitle ) {
+ this.element.attr( "title", this.originalTitle );
+ }
+
+ next = originalPosition.parent.children().eq( originalPosition.index );
+ // Don't try to place the dialog next to itself (#8613)
+ if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
+ next.before( this.element );
+ } else {
+ originalPosition.parent.append( this.element );
+ }
+ },
+
+ widget: function() {
+ return this.uiDialog;
+ },
+
+ disable: $.noop,
+ enable: $.noop,
+
+ close: function( event ) {
+ var activeElement,
+ that = this;
+
+ if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
+ return;
+ }
+
+ this._isOpen = false;
+ this._focusedElement = null;
+ this._destroyOverlay();
+ this._untrackInstance();
+
+ if ( !this.opener.filter( ":focusable" ).focus().length ) {
+
+ // support: IE9
+ // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
+ try {
+ activeElement = this.document[ 0 ].activeElement;
+
+ // Support: IE9, IE10
+ // If the <body> is blurred, IE will switch windows, see #4520
+ if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) {
+
+ // Hiding a focused element doesn't trigger blur in WebKit
+ // so in case we have nothing to focus on, explicitly blur the active element
+ // https://bugs.webkit.org/show_bug.cgi?id=47182
+ $( activeElement ).blur();
+ }
+ } catch ( error ) {}
+ }
+
+ this._hide( this.uiDialog, this.options.hide, function() {
+ that._trigger( "close", event );
+ });
+ },
+
+ isOpen: function() {
+ return this._isOpen;
+ },
+
+ moveToTop: function() {
+ this._moveToTop();
+ },
+
+ _moveToTop: function( event, silent ) {
+ var moved = false,
+ zIndicies = this.uiDialog.siblings( ".ui-front:visible" ).map(function() {
+ return +$( this ).css( "z-index" );
+ }).get(),
+ zIndexMax = Math.max.apply( null, zIndicies );
+
+ if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) {
+ this.uiDialog.css( "z-index", zIndexMax + 1 );
+ moved = true;
+ }
+
+ if ( moved && !silent ) {
+ this._trigger( "focus", event );
+ }
+ return moved;
+ },
+
+ open: function() {
+ var that = this;
+ if ( this._isOpen ) {
+ if ( this._moveToTop() ) {
+ this._focusTabbable();
+ }
+ return;
+ }
+
+ this._isOpen = true;
+ this.opener = $( this.document[ 0 ].activeElement );
+
+ this._size();
+ this._position();
+ this._createOverlay();
+ this._moveToTop( null, true );
+
+ // Ensure the overlay is moved to the top with the dialog, but only when
+ // opening. The overlay shouldn't move after the dialog is open so that
+ // modeless dialogs opened after the modal dialog stack properly.
+ if ( this.overlay ) {
+ this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 );
+ }
+
+ this._show( this.uiDialog, this.options.show, function() {
+ that._focusTabbable();
+ that._trigger( "focus" );
+ });
+
+ // Track the dialog immediately upon openening in case a focus event
+ // somehow occurs outside of the dialog before an element inside the
+ // dialog is focused (#10152)
+ this._makeFocusTarget();
+
+ this._trigger( "open" );
+ },
+
+ _focusTabbable: function() {
+ // Set focus to the first match:
+ // 1. An element that was focused previously
+ // 2. First element inside the dialog matching [autofocus]
+ // 3. Tabbable element inside the content element
+ // 4. Tabbable element inside the buttonpane
+ // 5. The close button
+ // 6. The dialog itself
+ var hasFocus = this._focusedElement;
+ if ( !hasFocus ) {
+ hasFocus = this.element.find( "[autofocus]" );
+ }
+ if ( !hasFocus.length ) {
+ hasFocus = this.element.find( ":tabbable" );
+ }
+ if ( !hasFocus.length ) {
+ hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
+ }
+ if ( !hasFocus.length ) {
+ hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" );
+ }
+ if ( !hasFocus.length ) {
+ hasFocus = this.uiDialog;
+ }
+ hasFocus.eq( 0 ).focus();
+ },
+
+ _keepFocus: function( event ) {
+ function checkFocus() {
+ var activeElement = this.document[0].activeElement,
+ isActive = this.uiDialog[0] === activeElement ||
+ $.contains( this.uiDialog[0], activeElement );
+ if ( !isActive ) {
+ this._focusTabbable();
+ }
+ }
+ event.preventDefault();
+ checkFocus.call( this );
+ // support: IE
+ // IE <= 8 doesn't prevent moving focus even with event.preventDefault()
+ // so we check again later
+ this._delay( checkFocus );
+ },
+
+ _createWrapper: function() {
+ this.uiDialog = $("<div>")
+ .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
+ this.options.dialogClass )
+ .hide()
+ .attr({
+ // Setting tabIndex makes the div focusable
+ tabIndex: -1,
+ role: "dialog"
+ })
+ .appendTo( this._appendTo() );
+
+ this._on( this.uiDialog, {
+ keydown: function( event ) {
+ if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
+ event.keyCode === $.ui.keyCode.ESCAPE ) {
+ event.preventDefault();
+ this.close( event );
+ return;
+ }
+
+ // prevent tabbing out of dialogs
+ if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) {
+ return;
+ }
+ var tabbables = this.uiDialog.find( ":tabbable" ),
+ first = tabbables.filter( ":first" ),
+ last = tabbables.filter( ":last" );
+
+ if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
+ this._delay(function() {
+ first.focus();
+ });
+ event.preventDefault();
+ } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
+ this._delay(function() {
+ last.focus();
+ });
+ event.preventDefault();
+ }
+ },
+ mousedown: function( event ) {
+ if ( this._moveToTop( event ) ) {
+ this._focusTabbable();
+ }
+ }
+ });
+
+ // We assume that any existing aria-describedby attribute means
+ // that the dialog content is marked up properly
+ // otherwise we brute force the content as the description
+ if ( !this.element.find( "[aria-describedby]" ).length ) {
+ this.uiDialog.attr({
+ "aria-describedby": this.element.uniqueId().attr( "id" )
+ });
+ }
+ },
+
+ _createTitlebar: function() {
+ var uiDialogTitle;
+
+ this.uiDialogTitlebar = $( "<div>" )
+ .addClass( "ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" )
+ .prependTo( this.uiDialog );
+ this._on( this.uiDialogTitlebar, {
+ mousedown: function( event ) {
+ // Don't prevent click on close button (#8838)
+ // Focusing a dialog that is partially scrolled out of view
+ // causes the browser to scroll it into view, preventing the click event
+ if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) {
+ // Dialog isn't getting focus when dragging (#8063)
+ this.uiDialog.focus();
+ }
+ }
+ });
+
+ // support: IE
+ // Use type="button" to prevent enter keypresses in textboxes from closing the
+ // dialog in IE (#9312)
+ this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
+ .button({
+ label: this.options.closeText,
+ icons: {
+ primary: "ui-icon-closethick"
+ },
+ text: false
+ })
+ .addClass( "ui-dialog-titlebar-close" )
+ .appendTo( this.uiDialogTitlebar );
+ this._on( this.uiDialogTitlebarClose, {
+ click: function( event ) {
+ event.preventDefault();
+ this.close( event );
+ }
+ });
+
+ uiDialogTitle = $( "<span>" )
+ .uniqueId()
+ .addClass( "ui-dialog-title" )
+ .prependTo( this.uiDialogTitlebar );
+ this._title( uiDialogTitle );
+
+ this.uiDialog.attr({
+ "aria-labelledby": uiDialogTitle.attr( "id" )
+ });
+ },
+
+ _title: function( title ) {
+ if ( !this.options.title ) {
+ title.html( " " );
+ }
+ title.text( this.options.title );
+ },
+
+ _createButtonPane: function() {
+ this.uiDialogButtonPane = $( "<div>" )
+ .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" );
+
+ this.uiButtonSet = $( "<div>" )
+ .addClass( "ui-dialog-buttonset" )
+ .appendTo( this.uiDialogButtonPane );
+
+ this._createButtons();
+ },
+
+ _createButtons: function() {
+ var that = this,
+ buttons = this.options.buttons;
+
+ // if we already have a button pane, remove it
+ this.uiDialogButtonPane.remove();
+ this.uiButtonSet.empty();
+
+ if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) {
+ this.uiDialog.removeClass( "ui-dialog-buttons" );
+ return;
+ }
+
+ $.each( buttons, function( name, props ) {
+ var click, buttonOptions;
+ props = $.isFunction( props ) ?
+ { click: props, text: name } :
+ props;
+ // Default to a non-submitting button
+ props = $.extend( { type: "button" }, props );
+ // Change the context for the click callback to be the main element
+ click = props.click;
+ props.click = function() {
+ click.apply( that.element[ 0 ], arguments );
+ };
+ buttonOptions = {
+ icons: props.icons,
+ text: props.showText
+ };
+ delete props.icons;
+ delete props.showText;
+ $( "<button></button>", props )
+ .button( buttonOptions )
+ .appendTo( that.uiButtonSet );
+ });
+ this.uiDialog.addClass( "ui-dialog-buttons" );
+ this.uiDialogButtonPane.appendTo( this.uiDialog );
+ },
+
+ _makeDraggable: function() {
+ var that = this,
+ options = this.options;
+
+ function filteredUi( ui ) {
+ return {
+ position: ui.position,
+ offset: ui.offset
+ };
+ }
+
+ this.uiDialog.draggable({
+ cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
+ handle: ".ui-dialog-titlebar",
+ containment: "document",
+ start: function( event, ui ) {
+ $( this ).addClass( "ui-dialog-dragging" );
+ that._blockFrames();
+ that._trigger( "dragStart", event, filteredUi( ui ) );
+ },
+ drag: function( event, ui ) {
+ that._trigger( "drag", event, filteredUi( ui ) );
+ },
+ stop: function( event, ui ) {
+ var left = ui.offset.left - that.document.scrollLeft(),
+ top = ui.offset.top - that.document.scrollTop();
+
+ options.position = {
+ my: "left top",
+ at: "left" + (left >= 0 ? "+" : "") + left + " " +
+ "top" + (top >= 0 ? "+" : "") + top,
+ of: that.window
+ };
+ $( this ).removeClass( "ui-dialog-dragging" );
+ that._unblockFrames();
+ that._trigger( "dragStop", event, filteredUi( ui ) );
+ }
+ });
+ },
+
+ _makeResizable: function() {
+ var that = this,
+ options = this.options,
+ handles = options.resizable,
+ // .ui-resizable has position: relative defined in the stylesheet
+ // but dialogs have to use absolute or fixed positioning
+ position = this.uiDialog.css("position"),
+ resizeHandles = typeof handles === "string" ?
+ handles :
+ "n,e,s,w,se,sw,ne,nw";
+
+ function filteredUi( ui ) {
+ return {
+ originalPosition: ui.originalPosition,
+ originalSize: ui.originalSize,
+ position: ui.position,
+ size: ui.size
+ };
+ }
+
+ this.uiDialog.resizable({
+ cancel: ".ui-dialog-content",
+ containment: "document",
+ alsoResize: this.element,
+ maxWidth: options.maxWidth,
+ maxHeight: options.maxHeight,
+ minWidth: options.minWidth,
+ minHeight: this._minHeight(),
+ handles: resizeHandles,
+ start: function( event, ui ) {
+ $( this ).addClass( "ui-dialog-resizing" );
+ that._blockFrames();
+ that._trigger( "resizeStart", event, filteredUi( ui ) );
+ },
+ resize: function( event, ui ) {
+ that._trigger( "resize", event, filteredUi( ui ) );
+ },
+ stop: function( event, ui ) {
+ var offset = that.uiDialog.offset(),
+ left = offset.left - that.document.scrollLeft(),
+ top = offset.top - that.document.scrollTop();
+
+ options.height = that.uiDialog.height();
+ options.width = that.uiDialog.width();
+ options.position = {
+ my: "left top",
+ at: "left" + (left >= 0 ? "+" : "") + left + " " +
+ "top" + (top >= 0 ? "+" : "") + top,
+ of: that.window
+ };
+ $( this ).removeClass( "ui-dialog-resizing" );
+ that._unblockFrames();
+ that._trigger( "resizeStop", event, filteredUi( ui ) );
+ }
+ })
+ .css( "position", position );
+ },
+
+ _trackFocus: function() {
+ this._on( this.widget(), {
+ focusin: function( event ) {
+ this._makeFocusTarget();
+ this._focusedElement = $( event.target );
+ }
+ });
+ },
+
+ _makeFocusTarget: function() {
+ this._untrackInstance();
+ this._trackingInstances().unshift( this );
+ },
+
+ _untrackInstance: function() {
+ var instances = this._trackingInstances(),
+ exists = $.inArray( this, instances );
+ if ( exists !== -1 ) {
+ instances.splice( exists, 1 );
+ }
+ },
+
+ _trackingInstances: function() {
+ var instances = this.document.data( "ui-dialog-instances" );
+ if ( !instances ) {
+ instances = [];
+ this.document.data( "ui-dialog-instances", instances );
+ }
+ return instances;
+ },
+
+ _minHeight: function() {
+ var options = this.options;
+
+ return options.height === "auto" ?
+ options.minHeight :
+ Math.min( options.minHeight, options.height );
+ },
+
+ _position: function() {
+ // Need to show the dialog to get the actual offset in the position plugin
+ var isVisible = this.uiDialog.is( ":visible" );
+ if ( !isVisible ) {
+ this.uiDialog.show();
+ }
+ this.uiDialog.position( this.options.position );
+ if ( !isVisible ) {
+ this.uiDialog.hide();
+ }
+ },
+
+ _setOptions: function( options ) {
+ var that = this,
+ resize = false,
+ resizableOptions = {};
+
+ $.each( options, function( key, value ) {
+ that._setOption( key, value );
+
+ if ( key in that.sizeRelatedOptions ) {
+ resize = true;
+ }
+ if ( key in that.resizableRelatedOptions ) {
+ resizableOptions[ key ] = value;
+ }
+ });
+
+ if ( resize ) {
+ this._size();
+ this._position();
+ }
+ if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
+ this.uiDialog.resizable( "option", resizableOptions );
+ }
+ },
+
+ _setOption: function( key, value ) {
+ var isDraggable, isResizable,
+ uiDialog = this.uiDialog;
+
+ if ( key === "dialogClass" ) {
+ uiDialog
+ .removeClass( this.options.dialogClass )
+ .addClass( value );
+ }
+
+ if ( key === "disabled" ) {
+ return;
+ }
+
+ this._super( key, value );
+
+ if ( key === "appendTo" ) {
+ this.uiDialog.appendTo( this._appendTo() );
+ }
+
+ if ( key === "buttons" ) {
+ this._createButtons();
+ }
+
+ if ( key === "closeText" ) {
+ this.uiDialogTitlebarClose.button({
+ // Ensure that we always pass a string
+ label: "" + value
+ });
+ }
+
+ if ( key === "draggable" ) {
+ isDraggable = uiDialog.is( ":data(ui-draggable)" );
+ if ( isDraggable && !value ) {
+ uiDialog.draggable( "destroy" );
+ }
+
+ if ( !isDraggable && value ) {
+ this._makeDraggable();
+ }
+ }
+
+ if ( key === "position" ) {
+ this._position();
+ }
+
+ if ( key === "resizable" ) {
+ // currently resizable, becoming non-resizable
+ isResizable = uiDialog.is( ":data(ui-resizable)" );
+ if ( isResizable && !value ) {
+ uiDialog.resizable( "destroy" );
+ }
+
+ // currently resizable, changing handles
+ if ( isResizable && typeof value === "string" ) {
+ uiDialog.resizable( "option", "handles", value );
+ }
+
+ // currently non-resizable, becoming resizable
+ if ( !isResizable && value !== false ) {
+ this._makeResizable();
+ }
+ }
+
+ if ( key === "title" ) {
+ this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
+ }
+ },
+
+ _size: function() {
+ // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
+ // divs will both have width and height set, so we need to reset them
+ var nonContentHeight, minContentHeight, maxContentHeight,
+ options = this.options;
+
+ // Reset content sizing
+ this.element.show().css({
+ width: "auto",
+ minHeight: 0,
+ maxHeight: "none",
+ height: 0
+ });
+
+ if ( options.minWidth > options.width ) {
+ options.width = options.minWidth;
+ }
+
+ // reset wrapper sizing
+ // determine the height of all the non-content elements
+ nonContentHeight = this.uiDialog.css({
+ height: "auto",
+ width: options.width
+ })
+ .outerHeight();
+ minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
+ maxContentHeight = typeof options.maxHeight === "number" ?
+ Math.max( 0, options.maxHeight - nonContentHeight ) :
+ "none";
+
+ if ( options.height === "auto" ) {
+ this.element.css({
+ minHeight: minContentHeight,
+ maxHeight: maxContentHeight,
+ height: "auto"
+ });
+ } else {
+ this.element.height( Math.max( 0, options.height - nonContentHeight ) );
+ }
+
+ if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
+ this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
+ }
+ },
+
+ _blockFrames: function() {
+ this.iframeBlocks = this.document.find( "iframe" ).map(function() {
+ var iframe = $( this );
+
+ return $( "<div>" )
+ .css({
+ position: "absolute",
+ width: iframe.outerWidth(),
+ height: iframe.outerHeight()
+ })
+ .appendTo( iframe.parent() )
+ .offset( iframe.offset() )[0];
+ });
+ },
+
+ _unblockFrames: function() {
+ if ( this.iframeBlocks ) {
+ this.iframeBlocks.remove();
+ delete this.iframeBlocks;
+ }
+ },
+
+ _allowInteraction: function( event ) {
+ if ( $( event.target ).closest( ".ui-dialog" ).length ) {
+ return true;
+ }
+
+ // TODO: Remove hack when datepicker implements
+ // the .ui-front logic (#8989)
+ return !!$( event.target ).closest( ".ui-datepicker" ).length;
+ },
+
+ _createOverlay: function() {
+ if ( !this.options.modal ) {
+ return;
+ }
+
+ // We use a delay in case the overlay is created from an
+ // event that we're going to be cancelling (#2804)
+ var isOpening = true;
+ this._delay(function() {
+ isOpening = false;
+ });
+
+ if ( !this.document.data( "ui-dialog-overlays" ) ) {
+
+ // Prevent use of anchors and inputs
+ // Using _on() for an event handler shared across many instances is
+ // safe because the dialogs stack and must be closed in reverse order
+ this._on( this.document, {
+ focusin: function( event ) {
+ if ( isOpening ) {
+ return;
+ }
+
+ if ( !this._allowInteraction( event ) ) {
+ event.preventDefault();
+ this._trackingInstances()[ 0 ]._focusTabbable();
+ }
+ }
+ });
+ }
+
+ this.overlay = $( "<div>" )
+ .addClass( "ui-widget-overlay ui-front" )
+ .appendTo( this._appendTo() );
+ this._on( this.overlay, {
+ mousedown: "_keepFocus"
+ });
+ this.document.data( "ui-dialog-overlays",
+ (this.document.data( "ui-dialog-overlays" ) || 0) + 1 );
+ },
+
+ _destroyOverlay: function() {
+ if ( !this.options.modal ) {
+ return;
+ }
+
+ if ( this.overlay ) {
+ var overlays = this.document.data( "ui-dialog-overlays" ) - 1;
+
+ if ( !overlays ) {
+ this.document
+ .unbind( "focusin" )
+ .removeData( "ui-dialog-overlays" );
+ } else {
+ this.document.data( "ui-dialog-overlays", overlays );
+ }
+
+ this.overlay.remove();
+ this.overlay = null;
+ }
+ }
+});
+
+
+/*!
+ * jQuery UI Droppable 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/droppable/
+ */
+
+
+$.widget( "ui.droppable", {
+ version: "1.11.2",
+ widgetEventPrefix: "drop",
+ options: {
+ accept: "*",
+ activeClass: false,
+ addClasses: true,
+ greedy: false,
+ hoverClass: false,
+ scope: "default",
+ tolerance: "intersect",
+
+ // callbacks
+ activate: null,
+ deactivate: null,
+ drop: null,
+ out: null,
+ over: null
+ },
+ _create: function() {
+
+ var proportions,
+ o = this.options,
+ accept = o.accept;
+
+ this.isover = false;
+ this.isout = true;
+
+ this.accept = $.isFunction( accept ) ? accept : function( d ) {
+ return d.is( accept );
+ };
+
+ this.proportions = function( /* valueToWrite */ ) {
+ if ( arguments.length ) {
+ // Store the droppable's proportions
+ proportions = arguments[ 0 ];
+ } else {
+ // Retrieve or derive the droppable's proportions
+ return proportions ?
+ proportions :
+ proportions = {
+ width: this.element[ 0 ].offsetWidth,
+ height: this.element[ 0 ].offsetHeight
+ };
+ }
+ };
+
+ this._addToManager( o.scope );
+
+ o.addClasses && this.element.addClass( "ui-droppable" );
+
+ },
+
+ _addToManager: function( scope ) {
+ // Add the reference and positions to the manager
+ $.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || [];
+ $.ui.ddmanager.droppables[ scope ].push( this );
+ },
+
+ _splice: function( drop ) {
+ var i = 0;
+ for ( ; i < drop.length; i++ ) {
+ if ( drop[ i ] === this ) {
+ drop.splice( i, 1 );
+ }
+ }
+ },
+
+ _destroy: function() {
+ var drop = $.ui.ddmanager.droppables[ this.options.scope ];
+
+ this._splice( drop );
+
+ this.element.removeClass( "ui-droppable ui-droppable-disabled" );
+ },
+
+ _setOption: function( key, value ) {
+
+ if ( key === "accept" ) {
+ this.accept = $.isFunction( value ) ? value : function( d ) {
+ return d.is( value );
+ };
+ } else if ( key === "scope" ) {
+ var drop = $.ui.ddmanager.droppables[ this.options.scope ];
+
+ this._splice( drop );
+ this._addToManager( value );
+ }
+
+ this._super( key, value );
+ },
+
+ _activate: function( event ) {
+ var draggable = $.ui.ddmanager.current;
+ if ( this.options.activeClass ) {
+ this.element.addClass( this.options.activeClass );
+ }
+ if ( draggable ){
+ this._trigger( "activate", event, this.ui( draggable ) );
+ }
+ },
+
+ _deactivate: function( event ) {
+ var draggable = $.ui.ddmanager.current;
+ if ( this.options.activeClass ) {
+ this.element.removeClass( this.options.activeClass );
+ }
+ if ( draggable ){
+ this._trigger( "deactivate", event, this.ui( draggable ) );
+ }
+ },
+
+ _over: function( event ) {
+
+ var draggable = $.ui.ddmanager.current;
+
+ // Bail if draggable and droppable are same element
+ if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
+ return;
+ }
+
+ if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
+ if ( this.options.hoverClass ) {
+ this.element.addClass( this.options.hoverClass );
+ }
+ this._trigger( "over", event, this.ui( draggable ) );
+ }
+
+ },
+
+ _out: function( event ) {
+
+ var draggable = $.ui.ddmanager.current;
+
+ // Bail if draggable and droppable are same element
+ if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
+ return;
+ }
+
+ if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
+ if ( this.options.hoverClass ) {
+ this.element.removeClass( this.options.hoverClass );
+ }
+ this._trigger( "out", event, this.ui( draggable ) );
+ }
+
+ },
+
+ _drop: function( event, custom ) {
+
+ var draggable = custom || $.ui.ddmanager.current,
+ childrenIntersection = false;
+
+ // Bail if draggable and droppable are same element
+ if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
+ return false;
+ }
+
+ this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() {
+ var inst = $( this ).droppable( "instance" );
+ if (
+ inst.options.greedy &&
+ !inst.options.disabled &&
+ inst.options.scope === draggable.options.scope &&
+ inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) &&
+ $.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance, event )
+ ) { childrenIntersection = true; return false; }
+ });
+ if ( childrenIntersection ) {
+ return false;
+ }
+
+ if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
+ if ( this.options.activeClass ) {
+ this.element.removeClass( this.options.activeClass );
+ }
+ if ( this.options.hoverClass ) {
+ this.element.removeClass( this.options.hoverClass );
+ }
+ this._trigger( "drop", event, this.ui( draggable ) );
+ return this.element;
+ }
+
+ return false;
+
+ },
+
+ ui: function( c ) {
+ return {
+ draggable: ( c.currentItem || c.element ),
+ helper: c.helper,
+ position: c.position,
+ offset: c.positionAbs
+ };
+ }
+
+});
+
+$.ui.intersect = (function() {
+ function isOverAxis( x, reference, size ) {
+ return ( x >= reference ) && ( x < ( reference + size ) );
+ }
+
+ return function( draggable, droppable, toleranceMode, event ) {
+
+ if ( !droppable.offset ) {
+ return false;
+ }
+
+ var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left,
+ y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top,
+ x2 = x1 + draggable.helperProportions.width,
+ y2 = y1 + draggable.helperProportions.height,
+ l = droppable.offset.left,
+ t = droppable.offset.top,
+ r = l + droppable.proportions().width,
+ b = t + droppable.proportions().height;
+
+ switch ( toleranceMode ) {
+ case "fit":
+ return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b );
+ case "intersect":
+ return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half
+ x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half
+ t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half
+ y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half
+ case "pointer":
+ return isOverAxis( event.pageY, t, droppable.proportions().height ) && isOverAxis( event.pageX, l, droppable.proportions().width );
+ case "touch":
+ return (
+ ( y1 >= t && y1 <= b ) || // Top edge touching
+ ( y2 >= t && y2 <= b ) || // Bottom edge touching
+ ( y1 < t && y2 > b ) // Surrounded vertically
+ ) && (
+ ( x1 >= l && x1 <= r ) || // Left edge touching
+ ( x2 >= l && x2 <= r ) || // Right edge touching
+ ( x1 < l && x2 > r ) // Surrounded horizontally
+ );
+ default:
+ return false;
+ }
+ };
+})();
+
+/*
+ This manager tracks offsets of draggables and droppables
+*/
+$.ui.ddmanager = {
+ current: null,
+ droppables: { "default": [] },
+ prepareOffsets: function( t, event ) {
+
+ var i, j,
+ m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
+ type = event ? event.type : null, // workaround for #2317
+ list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack();
+
+ droppablesLoop: for ( i = 0; i < m.length; i++ ) {
+
+ // No disabled and non-accepted
+ if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) {
+ continue;
+ }
+
+ // Filter out elements in the current dragged item
+ for ( j = 0; j < list.length; j++ ) {
+ if ( list[ j ] === m[ i ].element[ 0 ] ) {
+ m[ i ].proportions().height = 0;
+ continue droppablesLoop;
+ }
+ }
+
+ m[ i ].visible = m[ i ].element.css( "display" ) !== "none";
+ if ( !m[ i ].visible ) {
+ continue;
+ }
+
+ // Activate the droppable if used directly from draggables
+ if ( type === "mousedown" ) {
+ m[ i ]._activate.call( m[ i ], event );
+ }
+
+ m[ i ].offset = m[ i ].element.offset();
+ m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight });
+
+ }
+
+ },
+ drop: function( draggable, event ) {
+
+ var dropped = false;
+ // Create a copy of the droppables in case the list changes during the drop (#9116)
+ $.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() {
+
+ if ( !this.options ) {
+ return;
+ }
+ if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance, event ) ) {
+ dropped = this._drop.call( this, event ) || dropped;
+ }
+
+ if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
+ this.isout = true;
+ this.isover = false;
+ this._deactivate.call( this, event );
+ }
+
+ });
+ return dropped;
+
+ },
+ dragStart: function( draggable, event ) {
+ // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
+ draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
+ if ( !draggable.options.refreshPositions ) {
+ $.ui.ddmanager.prepareOffsets( draggable, event );
+ }
+ });
+ },
+ drag: function( draggable, event ) {
+
+ // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
+ if ( draggable.options.refreshPositions ) {
+ $.ui.ddmanager.prepareOffsets( draggable, event );
+ }
+
+ // Run through all droppables and check their positions based on specific tolerance options
+ $.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() {
+
+ if ( this.options.disabled || this.greedyChild || !this.visible ) {
+ return;
+ }
+
+ var parentInstance, scope, parent,
+ intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ),
+ c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null );
+ if ( !c ) {
+ return;
+ }
+
+ if ( this.options.greedy ) {
+ // find droppable parents with same scope
+ scope = this.options.scope;
+ parent = this.element.parents( ":data(ui-droppable)" ).filter(function() {
+ return $( this ).droppable( "instance" ).options.scope === scope;
+ });
+
+ if ( parent.length ) {
+ parentInstance = $( parent[ 0 ] ).droppable( "instance" );
+ parentInstance.greedyChild = ( c === "isover" );
+ }
+ }
+
+ // we just moved into a greedy child
+ if ( parentInstance && c === "isover" ) {
+ parentInstance.isover = false;
+ parentInstance.isout = true;
+ parentInstance._out.call( parentInstance, event );
+ }
+
+ this[ c ] = true;
+ this[c === "isout" ? "isover" : "isout"] = false;
+ this[c === "isover" ? "_over" : "_out"].call( this, event );
+
+ // we just moved out of a greedy child
+ if ( parentInstance && c === "isout" ) {
+ parentInstance.isout = false;
+ parentInstance.isover = true;
+ parentInstance._over.call( parentInstance, event );
+ }
+ });
+
+ },
+ dragStop: function( draggable, event ) {
+ draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
+ // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
+ if ( !draggable.options.refreshPositions ) {
+ $.ui.ddmanager.prepareOffsets( draggable, event );
+ }
+ }
+};
+
+var droppable = $.ui.droppable;
+
+
+/*!
+ * jQuery UI Effects 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/category/effects-core/
+ */
+
+
+var dataSpace = "ui-effects-",
+
+ // Create a local jQuery because jQuery Color relies on it and the
+ // global may not exist with AMD and a custom build (#10199)
+ jQuery = $;
+
+$.effects = {
+ effect: {}
+};
+
+/*!
+ * jQuery Color Animations v2.1.2
+ * https://github.com/jquery/jquery-color
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * Date: Wed Jan 16 08:47:09 2013 -0600
+ */
+(function( jQuery, undefined ) {
+
+ var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
+
+ // plusequals test for += 100 -= 100
+ rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
+ // a set of RE's that can match strings and generate color tuples.
+ stringParsers = [ {
+ re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
+ parse: function( execResult ) {
+ return [
+ execResult[ 1 ],
+ execResult[ 2 ],
+ execResult[ 3 ],
+ execResult[ 4 ]
+ ];
+ }
+ }, {
+ re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
+ parse: function( execResult ) {
+ return [
+ execResult[ 1 ] * 2.55,
+ execResult[ 2 ] * 2.55,
+ execResult[ 3 ] * 2.55,
+ execResult[ 4 ]
+ ];
+ }
+ }, {
+ // this regex ignores A-F because it's compared against an already lowercased string
+ re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
+ parse: function( execResult ) {
+ return [
+ parseInt( execResult[ 1 ], 16 ),
+ parseInt( execResult[ 2 ], 16 ),
+ parseInt( execResult[ 3 ], 16 )
+ ];
+ }
+ }, {
+ // this regex ignores A-F because it's compared against an already lowercased string
+ re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
+ parse: function( execResult ) {
+ return [
+ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
+ parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
+ parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
+ ];
+ }
+ }, {
+ re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
+ space: "hsla",
+ parse: function( execResult ) {
+ return [
+ execResult[ 1 ],
+ execResult[ 2 ] / 100,
+ execResult[ 3 ] / 100,
+ execResult[ 4 ]
+ ];
+ }
+ } ],
+
+ // jQuery.Color( )
+ color = jQuery.Color = function( color, green, blue, alpha ) {
+ return new jQuery.Color.fn.parse( color, green, blue, alpha );
+ },
+ spaces = {
+ rgba: {
+ props: {
+ red: {
+ idx: 0,
+ type: "byte"
+ },
+ green: {
+ idx: 1,
+ type: "byte"
+ },
+ blue: {
+ idx: 2,
+ type: "byte"
+ }
+ }
+ },
+
+ hsla: {
+ props: {
+ hue: {
+ idx: 0,
+ type: "degrees"
+ },
+ saturation: {
+ idx: 1,
+ type: "percent"
+ },
+ lightness: {
+ idx: 2,
+ type: "percent"
+ }
+ }
+ }
+ },
+ propTypes = {
+ "byte": {
+ floor: true,
+ max: 255
+ },
+ "percent": {
+ max: 1
+ },
+ "degrees": {
+ mod: 360,
+ floor: true
+ }
+ },
+ support = color.support = {},
+
+ // element for support tests
+ supportElem = jQuery( "<p>" )[ 0 ],
+
+ // colors = jQuery.Color.names
+ colors,
+
+ // local aliases of functions called often
+ each = jQuery.each;
+
+// determine rgba support immediately
+supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
+support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
+
+// define cache name and alpha properties
+// for rgba and hsla spaces
+each( spaces, function( spaceName, space ) {
+ space.cache = "_" + spaceName;
+ space.props.alpha = {
+ idx: 3,
+ type: "percent",
+ def: 1
+ };
+});
+
+function clamp( value, prop, allowEmpty ) {
+ var type = propTypes[ prop.type ] || {};
+
+ if ( value == null ) {
+ return (allowEmpty || !prop.def) ? null : prop.def;
+ }
+
+ // ~~ is an short way of doing floor for positive numbers
+ value = type.floor ? ~~value : parseFloat( value );
+
+ // IE will pass in empty strings as value for alpha,
+ // which will hit this case
+ if ( isNaN( value ) ) {
+ return prop.def;
+ }
+
+ if ( type.mod ) {
+ // we add mod before modding to make sure that negatives values
+ // get converted properly: -10 -> 350
+ return (value + type.mod) % type.mod;
+ }
+
+ // for now all property types without mod have min and max
+ return 0 > value ? 0 : type.max < value ? type.max : value;
+}
+
+function stringParse( string ) {
+ var inst = color(),
+ rgba = inst._rgba = [];
+
+ string = string.toLowerCase();
+
+ each( stringParsers, function( i, parser ) {
+ var parsed,
+ match = parser.re.exec( string ),
+ values = match && parser.parse( match ),
+ spaceName = parser.space || "rgba";
+
+ if ( values ) {
+ parsed = inst[ spaceName ]( values );
+
+ // if this was an rgba parse the assignment might happen twice
+ // oh well....
+ inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
+ rgba = inst._rgba = parsed._rgba;
+
+ // exit each( stringParsers ) here because we matched
+ return false;
+ }
+ });
+
+ // Found a stringParser that handled it
+ if ( rgba.length ) {
+
+ // if this came from a parsed string, force "transparent" when alpha is 0
+ // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
+ if ( rgba.join() === "0,0,0,0" ) {
+ jQuery.extend( rgba, colors.transparent );
+ }
+ return inst;
+ }
+
+ // named colors
+ return colors[ string ];
+}
+
+color.fn = jQuery.extend( color.prototype, {
+ parse: function( red, green, blue, alpha ) {
+ if ( red === undefined ) {
+ this._rgba = [ null, null, null, null ];
+ return this;
+ }
+ if ( red.jquery || red.nodeType ) {
+ red = jQuery( red ).css( green );
+ green = undefined;
+ }
+
+ var inst = this,
+ type = jQuery.type( red ),
+ rgba = this._rgba = [];
+
+ // more than 1 argument specified - assume ( red, green, blue, alpha )
+ if ( green !== undefined ) {
+ red = [ red, green, blue, alpha ];
+ type = "array";
+ }
+
+ if ( type === "string" ) {
+ return this.parse( stringParse( red ) || colors._default );
+ }
+
+ if ( type === "array" ) {
+ each( spaces.rgba.props, function( key, prop ) {
+ rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
+ });
+ return this;
+ }
+
+ if ( type === "object" ) {
+ if ( red instanceof color ) {
+ each( spaces, function( spaceName, space ) {
+ if ( red[ space.cache ] ) {
+ inst[ space.cache ] = red[ space.cache ].slice();
+ }
+ });
+ } else {
+ each( spaces, function( spaceName, space ) {
+ var cache = space.cache;
+ each( space.props, function( key, prop ) {
+
+ // if the cache doesn't exist, and we know how to convert
+ if ( !inst[ cache ] && space.to ) {
+
+ // if the value was null, we don't need to copy it
+ // if the key was alpha, we don't need to copy it either
+ if ( key === "alpha" || red[ key ] == null ) {
+ return;
+ }
+ inst[ cache ] = space.to( inst._rgba );
+ }
+
+ // this is the only case where we allow nulls for ALL properties.
+ // call clamp with alwaysAllowEmpty
+ inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
+ });
+
+ // everything defined but alpha?
+ if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
+ // use the default of 1
+ inst[ cache ][ 3 ] = 1;
+ if ( space.from ) {
+ inst._rgba = space.from( inst[ cache ] );
+ }
+ }
+ });
+ }
+ return this;
+ }
+ },
+ is: function( compare ) {
+ var is = color( compare ),
+ same = true,
+ inst = this;
+
+ each( spaces, function( _, space ) {
+ var localCache,
+ isCache = is[ space.cache ];
+ if (isCache) {
+ localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
+ each( space.props, function( _, prop ) {
+ if ( isCache[ prop.idx ] != null ) {
+ same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
+ return same;
+ }
+ });
+ }
+ return same;
+ });
+ return same;
+ },
+ _space: function() {
+ var used = [],
+ inst = this;
+ each( spaces, function( spaceName, space ) {
+ if ( inst[ space.cache ] ) {
+ used.push( spaceName );
+ }
+ });
+ return used.pop();
+ },
+ transition: function( other, distance ) {
+ var end = color( other ),
+ spaceName = end._space(),
+ space = spaces[ spaceName ],
+ startColor = this.alpha() === 0 ? color( "transparent" ) : this,
+ start = startColor[ space.cache ] || space.to( startColor._rgba ),
+ result = start.slice();
+
+ end = end[ space.cache ];
+ each( space.props, function( key, prop ) {
+ var index = prop.idx,
+ startValue = start[ index ],
+ endValue = end[ index ],
+ type = propTypes[ prop.type ] || {};
+
+ // if null, don't override start value
+ if ( endValue === null ) {
+ return;
+ }
+ // if null - use end
+ if ( startValue === null ) {
+ result[ index ] = endValue;
+ } else {
+ if ( type.mod ) {
+ if ( endValue - startValue > type.mod / 2 ) {
+ startValue += type.mod;
+ } else if ( startValue - endValue > type.mod / 2 ) {
+ startValue -= type.mod;
+ }
+ }
+ result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
+ }
+ });
+ return this[ spaceName ]( result );
+ },
+ blend: function( opaque ) {
+ // if we are already opaque - return ourself
+ if ( this._rgba[ 3 ] === 1 ) {
+ return this;
+ }
+
+ var rgb = this._rgba.slice(),
+ a = rgb.pop(),
+ blend = color( opaque )._rgba;
+
+ return color( jQuery.map( rgb, function( v, i ) {
+ return ( 1 - a ) * blend[ i ] + a * v;
+ }));
+ },
+ toRgbaString: function() {
+ var prefix = "rgba(",
+ rgba = jQuery.map( this._rgba, function( v, i ) {
+ return v == null ? ( i > 2 ? 1 : 0 ) : v;
+ });
+
+ if ( rgba[ 3 ] === 1 ) {
+ rgba.pop();
+ prefix = "rgb(";
+ }
+
+ return prefix + rgba.join() + ")";
+ },
+ toHslaString: function() {
+ var prefix = "hsla(",
+ hsla = jQuery.map( this.hsla(), function( v, i ) {
+ if ( v == null ) {
+ v = i > 2 ? 1 : 0;
+ }
+
+ // catch 1 and 2
+ if ( i && i < 3 ) {
+ v = Math.round( v * 100 ) + "%";
+ }
+ return v;
+ });
+
+ if ( hsla[ 3 ] === 1 ) {
+ hsla.pop();
+ prefix = "hsl(";
+ }
+ return prefix + hsla.join() + ")";
+ },
+ toHexString: function( includeAlpha ) {
+ var rgba = this._rgba.slice(),
+ alpha = rgba.pop();
+
+ if ( includeAlpha ) {
+ rgba.push( ~~( alpha * 255 ) );
+ }
+
+ return "#" + jQuery.map( rgba, function( v ) {
+
+ // default to 0 when nulls exist
+ v = ( v || 0 ).toString( 16 );
+ return v.length === 1 ? "0" + v : v;
+ }).join("");
+ },
+ toString: function() {
+ return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
+ }
+});
+color.fn.parse.prototype = color.fn;
+
+// hsla conversions adapted from:
+// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
+
+function hue2rgb( p, q, h ) {
+ h = ( h + 1 ) % 1;
+ if ( h * 6 < 1 ) {
+ return p + ( q - p ) * h * 6;
+ }
+ if ( h * 2 < 1) {
+ return q;
+ }
+ if ( h * 3 < 2 ) {
+ return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
+ }
+ return p;
+}
+
+spaces.hsla.to = function( rgba ) {
+ if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
+ return [ null, null, null, rgba[ 3 ] ];
+ }
+ var r = rgba[ 0 ] / 255,
+ g = rgba[ 1 ] / 255,
+ b = rgba[ 2 ] / 255,
+ a = rgba[ 3 ],
+ max = Math.max( r, g, b ),
+ min = Math.min( r, g, b ),
+ diff = max - min,
+ add = max + min,
+ l = add * 0.5,
+ h, s;
+
+ if ( min === max ) {
+ h = 0;
+ } else if ( r === max ) {
+ h = ( 60 * ( g - b ) / diff ) + 360;
+ } else if ( g === max ) {
+ h = ( 60 * ( b - r ) / diff ) + 120;
+ } else {
+ h = ( 60 * ( r - g ) / diff ) + 240;
+ }
+
+ // chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
+ // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
+ if ( diff === 0 ) {
+ s = 0;
+ } else if ( l <= 0.5 ) {
+ s = diff / add;
+ } else {
+ s = diff / ( 2 - add );
+ }
+ return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
+};
+
+spaces.hsla.from = function( hsla ) {
+ if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
+ return [ null, null, null, hsla[ 3 ] ];
+ }
+ var h = hsla[ 0 ] / 360,
+ s = hsla[ 1 ],
+ l = hsla[ 2 ],
+ a = hsla[ 3 ],
+ q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
+ p = 2 * l - q;
+
+ return [
+ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
+ Math.round( hue2rgb( p, q, h ) * 255 ),
+ Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
+ a
+ ];
+};
+
+each( spaces, function( spaceName, space ) {
+ var props = space.props,
+ cache = space.cache,
+ to = space.to,
+ from = space.from;
+
+ // makes rgba() and hsla()
+ color.fn[ spaceName ] = function( value ) {
+
+ // generate a cache for this space if it doesn't exist
+ if ( to && !this[ cache ] ) {
+ this[ cache ] = to( this._rgba );
+ }
+ if ( value === undefined ) {
+ return this[ cache ].slice();
+ }
+
+ var ret,
+ type = jQuery.type( value ),
+ arr = ( type === "array" || type === "object" ) ? value : arguments,
+ local = this[ cache ].slice();
+
+ each( props, function( key, prop ) {
+ var val = arr[ type === "object" ? key : prop.idx ];
+ if ( val == null ) {
+ val = local[ prop.idx ];
+ }
+ local[ prop.idx ] = clamp( val, prop );
+ });
+
+ if ( from ) {
+ ret = color( from( local ) );
+ ret[ cache ] = local;
+ return ret;
+ } else {
+ return color( local );
+ }
+ };
+
+ // makes red() green() blue() alpha() hue() saturation() lightness()
+ each( props, function( key, prop ) {
+ // alpha is included in more than one space
+ if ( color.fn[ key ] ) {
+ return;
+ }
+ color.fn[ key ] = function( value ) {
+ var vtype = jQuery.type( value ),
+ fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
+ local = this[ fn ](),
+ cur = local[ prop.idx ],
+ match;
+
+ if ( vtype === "undefined" ) {
+ return cur;
+ }
+
+ if ( vtype === "function" ) {
+ value = value.call( this, cur );
+ vtype = jQuery.type( value );
+ }
+ if ( value == null && prop.empty ) {
+ return this;
+ }
+ if ( vtype === "string" ) {
+ match = rplusequals.exec( value );
+ if ( match ) {
+ value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
+ }
+ }
+ local[ prop.idx ] = value;
+ return this[ fn ]( local );
+ };
+ });
+});
+
+// add cssHook and .fx.step function for each named hook.
+// accept a space separated string of properties
+color.hook = function( hook ) {
+ var hooks = hook.split( " " );
+ each( hooks, function( i, hook ) {
+ jQuery.cssHooks[ hook ] = {
+ set: function( elem, value ) {
+ var parsed, curElem,
+ backgroundColor = "";
+
+ if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
+ value = color( parsed || value );
+ if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
+ curElem = hook === "backgroundColor" ? elem.parentNode : elem;
+ while (
+ (backgroundColor === "" || backgroundColor === "transparent") &&
+ curElem && curElem.style
+ ) {
+ try {
+ backgroundColor = jQuery.css( curElem, "backgroundColor" );
+ curElem = curElem.parentNode;
+ } catch ( e ) {
+ }
+ }
+
+ value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
+ backgroundColor :
+ "_default" );
+ }
+
+ value = value.toRgbaString();
+ }
+ try {
+ elem.style[ hook ] = value;
+ } catch ( e ) {
+ // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
+ }
+ }
+ };
+ jQuery.fx.step[ hook ] = function( fx ) {
+ if ( !fx.colorInit ) {
+ fx.start = color( fx.elem, hook );
+ fx.end = color( fx.end );
+ fx.colorInit = true;
+ }
+ jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
+ };
+ });
+
+};
+
+color.hook( stepHooks );
+
+jQuery.cssHooks.borderColor = {
+ expand: function( value ) {
+ var expanded = {};
+
+ each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
+ expanded[ "border" + part + "Color" ] = value;
+ });
+ return expanded;
+ }
+};
+
+// Basic color names only.
+// Usage of any of the other color names requires adding yourself or including
+// jquery.color.svg-names.js.
+colors = jQuery.Color.names = {
+ // 4.1. Basic color keywords
+ aqua: "#00ffff",
+ black: "#000000",
+ blue: "#0000ff",
+ fuchsia: "#ff00ff",
+ gray: "#808080",
+ green: "#008000",
+ lime: "#00ff00",
+ maroon: "#800000",
+ navy: "#000080",
+ olive: "#808000",
+ purple: "#800080",
+ red: "#ff0000",
+ silver: "#c0c0c0",
+ teal: "#008080",
+ white: "#ffffff",
+ yellow: "#ffff00",
+
+ // 4.2.3. "transparent" color keyword
+ transparent: [ null, null, null, 0 ],
+
+ _default: "#ffffff"
+};
+
+})( jQuery );
+
+/******************************************************************************/
+/****************************** CLASS ANIMATIONS ******************************/
+/******************************************************************************/
+(function() {
+
+var classAnimationActions = [ "add", "remove", "toggle" ],
+ shorthandStyles = {
+ border: 1,
+ borderBottom: 1,
+ borderColor: 1,
+ borderLeft: 1,
+ borderRight: 1,
+ borderTop: 1,
+ borderWidth: 1,
+ margin: 1,
+ padding: 1
+ };
+
+$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
+ $.fx.step[ prop ] = function( fx ) {
+ if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
+ jQuery.style( fx.elem, prop, fx.end );
+ fx.setAttr = true;
+ }
+ };
+});
+
+function getElementStyles( elem ) {
+ var key, len,
+ style = elem.ownerDocument.defaultView ?
+ elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
+ elem.currentStyle,
+ styles = {};
+
+ if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
+ len = style.length;
+ while ( len-- ) {
+ key = style[ len ];
+ if ( typeof style[ key ] === "string" ) {
+ styles[ $.camelCase( key ) ] = style[ key ];
+ }
+ }
+ // support: Opera, IE <9
+ } else {
+ for ( key in style ) {
+ if ( typeof style[ key ] === "string" ) {
+ styles[ key ] = style[ key ];
+ }
+ }
+ }
+
+ return styles;
+}
+
+function styleDifference( oldStyle, newStyle ) {
+ var diff = {},
+ name, value;
+
+ for ( name in newStyle ) {
+ value = newStyle[ name ];
+ if ( oldStyle[ name ] !== value ) {
+ if ( !shorthandStyles[ name ] ) {
+ if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
+ diff[ name ] = value;
+ }
+ }
+ }
+ }
+
+ return diff;
+}
+
+// support: jQuery <1.8
+if ( !$.fn.addBack ) {
+ $.fn.addBack = function( selector ) {
+ return this.add( selector == null ?
+ this.prevObject : this.prevObject.filter( selector )
+ );
+ };
+}
+
+$.effects.animateClass = function( value, duration, easing, callback ) {
+ var o = $.speed( duration, easing, callback );
+
+ return this.queue( function() {
+ var animated = $( this ),
+ baseClass = animated.attr( "class" ) || "",
+ applyClassChange,
+ allAnimations = o.children ? animated.find( "*" ).addBack() : animated;
+
+ // map the animated objects to store the original styles.
+ allAnimations = allAnimations.map(function() {
+ var el = $( this );
+ return {
+ el: el,
+ start: getElementStyles( this )
+ };
+ });
+
+ // apply class change
+ applyClassChange = function() {
+ $.each( classAnimationActions, function(i, action) {
+ if ( value[ action ] ) {
+ animated[ action + "Class" ]( value[ action ] );
+ }
+ });
+ };
+ applyClassChange();
+
+ // map all animated objects again - calculate new styles and diff
+ allAnimations = allAnimations.map(function() {
+ this.end = getElementStyles( this.el[ 0 ] );
+ this.diff = styleDifference( this.start, this.end );
+ return this;
+ });
+
+ // apply original class
+ animated.attr( "class", baseClass );
+
+ // map all animated objects again - this time collecting a promise
+ allAnimations = allAnimations.map(function() {
+ var styleInfo = this,
+ dfd = $.Deferred(),
+ opts = $.extend({}, o, {
+ queue: false,
+ complete: function() {
+ dfd.resolve( styleInfo );
+ }
+ });
+
+ this.el.animate( this.diff, opts );
+ return dfd.promise();
+ });
+
+ // once all animations have completed:
+ $.when.apply( $, allAnimations.get() ).done(function() {
+
+ // set the final class
+ applyClassChange();
+
+ // for each animated element,
+ // clear all css properties that were animated
+ $.each( arguments, function() {
+ var el = this.el;
+ $.each( this.diff, function(key) {
+ el.css( key, "" );
+ });
+ });
+
+ // this is guarnteed to be there if you use jQuery.speed()
+ // it also handles dequeuing the next anim...
+ o.complete.call( animated[ 0 ] );
+ });
+ });
+};
+
+$.fn.extend({
+ addClass: (function( orig ) {
+ return function( classNames, speed, easing, callback ) {
+ return speed ?
+ $.effects.animateClass.call( this,
+ { add: classNames }, speed, easing, callback ) :
+ orig.apply( this, arguments );
+ };
+ })( $.fn.addClass ),
+
+ removeClass: (function( orig ) {
+ return function( classNames, speed, easing, callback ) {
+ return arguments.length > 1 ?
+ $.effects.animateClass.call( this,
+ { remove: classNames }, speed, easing, callback ) :
+ orig.apply( this, arguments );
+ };
+ })( $.fn.removeClass ),
+
+ toggleClass: (function( orig ) {
+ return function( classNames, force, speed, easing, callback ) {
+ if ( typeof force === "boolean" || force === undefined ) {
+ if ( !speed ) {
+ // without speed parameter
+ return orig.apply( this, arguments );
+ } else {
+ return $.effects.animateClass.call( this,
+ (force ? { add: classNames } : { remove: classNames }),
+ speed, easing, callback );
+ }
+ } else {
+ // without force parameter
+ return $.effects.animateClass.call( this,
+ { toggle: classNames }, force, speed, easing );
+ }
+ };
+ })( $.fn.toggleClass ),
+
+ switchClass: function( remove, add, speed, easing, callback) {
+ return $.effects.animateClass.call( this, {
+ add: add,
+ remove: remove
+ }, speed, easing, callback );
+ }
+});
+
+})();
+
+/******************************************************************************/
+/*********************************** EFFECTS **********************************/
+/******************************************************************************/
+
+(function() {
+
+$.extend( $.effects, {
+ version: "1.11.2",
+
+ // Saves a set of properties in a data storage
+ save: function( element, set ) {
+ for ( var i = 0; i < set.length; i++ ) {
+ if ( set[ i ] !== null ) {
+ element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
+ }
+ }
+ },
+
+ // Restores a set of previously saved properties from a data storage
+ restore: function( element, set ) {
+ var val, i;
+ for ( i = 0; i < set.length; i++ ) {
+ if ( set[ i ] !== null ) {
+ val = element.data( dataSpace + set[ i ] );
+ // support: jQuery 1.6.2
+ // http://bugs.jquery.com/ticket/9917
+ // jQuery 1.6.2 incorrectly returns undefined for any falsy value.
+ // We can't differentiate between "" and 0 here, so we just assume
+ // empty string since it's likely to be a more common value...
+ if ( val === undefined ) {
+ val = "";
+ }
+ element.css( set[ i ], val );
+ }
+ }
+ },
+
+ setMode: function( el, mode ) {
+ if (mode === "toggle") {
+ mode = el.is( ":hidden" ) ? "show" : "hide";
+ }
+ return mode;
+ },
+
+ // Translates a [top,left] array into a baseline value
+ // this should be a little more flexible in the future to handle a string & hash
+ getBaseline: function( origin, original ) {
+ var y, x;
+ switch ( origin[ 0 ] ) {
+ case "top": y = 0; break;
+ case "middle": y = 0.5; break;
+ case "bottom": y = 1; break;
+ default: y = origin[ 0 ] / original.height;
+ }
+ switch ( origin[ 1 ] ) {
+ case "left": x = 0; break;
+ case "center": x = 0.5; break;
+ case "right": x = 1; break;
+ default: x = origin[ 1 ] / original.width;
+ }
+ return {
+ x: x,
+ y: y
+ };
+ },
+
+ // Wraps the element around a wrapper that copies position properties
+ createWrapper: function( element ) {
+
+ // if the element is already wrapped, return it
+ if ( element.parent().is( ".ui-effects-wrapper" )) {
+ return element.parent();
+ }
+
+ // wrap the element
+ var props = {
+ width: element.outerWidth(true),
+ height: element.outerHeight(true),
+ "float": element.css( "float" )
+ },
+ wrapper = $( "<div></div>" )
+ .addClass( "ui-effects-wrapper" )
+ .css({
+ fontSize: "100%",
+ background: "transparent",
+ border: "none",
+ margin: 0,
+ padding: 0
+ }),
+ // Store the size in case width/height are defined in % - Fixes #5245
+ size = {
+ width: element.width(),
+ height: element.height()
+ },
+ active = document.activeElement;
+
+ // support: Firefox
+ // Firefox incorrectly exposes anonymous content
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=561664
+ try {
+ active.id;
+ } catch ( e ) {
+ active = document.body;
+ }
+
+ element.wrap( wrapper );
+
+ // Fixes #7595 - Elements lose focus when wrapped.
+ if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
+ $( active ).focus();
+ }
+
+ wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
+
+ // transfer positioning properties to the wrapper
+ if ( element.css( "position" ) === "static" ) {
+ wrapper.css({ position: "relative" });
+ element.css({ position: "relative" });
+ } else {
+ $.extend( props, {
+ position: element.css( "position" ),
+ zIndex: element.css( "z-index" )
+ });
+ $.each([ "top", "left", "bottom", "right" ], function(i, pos) {
+ props[ pos ] = element.css( pos );
+ if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
+ props[ pos ] = "auto";
+ }
+ });
+ element.css({
+ position: "relative",
+ top: 0,
+ left: 0,
+ right: "auto",
+ bottom: "auto"
+ });
+ }
+ element.css(size);
+
+ return wrapper.css( props ).show();
+ },
+
+ removeWrapper: function( element ) {
+ var active = document.activeElement;
+
+ if ( element.parent().is( ".ui-effects-wrapper" ) ) {
+ element.parent().replaceWith( element );
+
+ // Fixes #7595 - Elements lose focus when wrapped.
+ if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
+ $( active ).focus();
+ }
+ }
+
+ return element;
+ },
+
+ setTransition: function( element, list, factor, value ) {
+ value = value || {};
+ $.each( list, function( i, x ) {
+ var unit = element.cssUnit( x );
+ if ( unit[ 0 ] > 0 ) {
+ value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
+ }
+ });
+ return value;
+ }
+});
+
+// return an effect options object for the given parameters:
+function _normalizeArguments( effect, options, speed, callback ) {
+
+ // allow passing all options as the first parameter
+ if ( $.isPlainObject( effect ) ) {
+ options = effect;
+ effect = effect.effect;
+ }
+
+ // convert to an object
+ effect = { effect: effect };
+
+ // catch (effect, null, ...)
+ if ( options == null ) {
+ options = {};
+ }
+
+ // catch (effect, callback)
+ if ( $.isFunction( options ) ) {
+ callback = options;
+ speed = null;
+ options = {};
+ }
+
+ // catch (effect, speed, ?)
+ if ( typeof options === "number" || $.fx.speeds[ options ] ) {
+ callback = speed;
+ speed = options;
+ options = {};
+ }
+
+ // catch (effect, options, callback)
+ if ( $.isFunction( speed ) ) {
+ callback = speed;
+ speed = null;
+ }
+
+ // add options to effect
+ if ( options ) {
+ $.extend( effect, options );
+ }
+
+ speed = speed || options.duration;
+ effect.duration = $.fx.off ? 0 :
+ typeof speed === "number" ? speed :
+ speed in $.fx.speeds ? $.fx.speeds[ speed ] :
+ $.fx.speeds._default;
+
+ effect.complete = callback || options.complete;
+
+ return effect;
+}
+
+function standardAnimationOption( option ) {
+ // Valid standard speeds (nothing, number, named speed)
+ if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
+ return true;
+ }
+
+ // Invalid strings - treat as "normal" speed
+ if ( typeof option === "string" && !$.effects.effect[ option ] ) {
+ return true;
+ }
+
+ // Complete callback
+ if ( $.isFunction( option ) ) {
+ return true;
+ }
+
+ // Options hash (but not naming an effect)
+ if ( typeof option === "object" && !option.effect ) {
+ return true;
+ }
+
+ // Didn't match any standard API
+ return false;
+}
+
+$.fn.extend({
+ effect: function( /* effect, options, speed, callback */ ) {
+ var args = _normalizeArguments.apply( this, arguments ),
+ mode = args.mode,
+ queue = args.queue,
+ effectMethod = $.effects.effect[ args.effect ];
+
+ if ( $.fx.off || !effectMethod ) {
+ // delegate to the original method (e.g., .show()) if possible
+ if ( mode ) {
+ return this[ mode ]( args.duration, args.complete );
+ } else {
+ return this.each( function() {
+ if ( args.complete ) {
+ args.complete.call( this );
+ }
+ });
+ }
+ }
+
+ function run( next ) {
+ var elem = $( this ),
+ complete = args.complete,
+ mode = args.mode;
+
+ function done() {
+ if ( $.isFunction( complete ) ) {
+ complete.call( elem[0] );
+ }
+ if ( $.isFunction( next ) ) {
+ next();
+ }
+ }
+
+ // If the element already has the correct final state, delegate to
+ // the core methods so the internal tracking of "olddisplay" works.
+ if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
+ elem[ mode ]();
+ done();
+ } else {
+ effectMethod.call( elem[0], args, done );
+ }
+ }
+
+ return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
+ },
+
+ show: (function( orig ) {
+ return function( option ) {
+ if ( standardAnimationOption( option ) ) {
+ return orig.apply( this, arguments );
+ } else {
+ var args = _normalizeArguments.apply( this, arguments );
+ args.mode = "show";
+ return this.effect.call( this, args );
+ }
+ };
+ })( $.fn.show ),
+
+ hide: (function( orig ) {
+ return function( option ) {
+ if ( standardAnimationOption( option ) ) {
+ return orig.apply( this, arguments );
+ } else {
+ var args = _normalizeArguments.apply( this, arguments );
+ args.mode = "hide";
+ return this.effect.call( this, args );
+ }
+ };
+ })( $.fn.hide ),
+
+ toggle: (function( orig ) {
+ return function( option ) {
+ if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
+ return orig.apply( this, arguments );
+ } else {
+ var args = _normalizeArguments.apply( this, arguments );
+ args.mode = "toggle";
+ return this.effect.call( this, args );
+ }
+ };
+ })( $.fn.toggle ),
+
+ // helper functions
+ cssUnit: function(key) {
+ var style = this.css( key ),
+ val = [];
+
+ $.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
+ if ( style.indexOf( unit ) > 0 ) {
+ val = [ parseFloat( style ), unit ];
+ }
+ });
+ return val;
+ }
+});
+
+})();
+
+/******************************************************************************/
+/*********************************** EASING ***********************************/
+/******************************************************************************/
+
+(function() {
+
+// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
+
+var baseEasings = {};
+
+$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
+ baseEasings[ name ] = function( p ) {
+ return Math.pow( p, i + 2 );
+ };
+});
+
+$.extend( baseEasings, {
+ Sine: function( p ) {
+ return 1 - Math.cos( p * Math.PI / 2 );
+ },
+ Circ: function( p ) {
+ return 1 - Math.sqrt( 1 - p * p );
+ },
+ Elastic: function( p ) {
+ return p === 0 || p === 1 ? p :
+ -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
+ },
+ Back: function( p ) {
+ return p * p * ( 3 * p - 2 );
+ },
+ Bounce: function( p ) {
+ var pow2,
+ bounce = 4;
+
+ while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
+ return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
+ }
+});
+
+$.each( baseEasings, function( name, easeIn ) {
+ $.easing[ "easeIn" + name ] = easeIn;
+ $.easing[ "easeOut" + name ] = function( p ) {
+ return 1 - easeIn( 1 - p );
+ };
+ $.easing[ "easeInOut" + name ] = function( p ) {
+ return p < 0.5 ?
+ easeIn( p * 2 ) / 2 :
+ 1 - easeIn( p * -2 + 2 ) / 2;
+ };
+});
+
+})();
+
+var effect = $.effects;
+
+
+/*!
+ * jQuery UI Effects Blind 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/blind-effect/
+ */
+
+
+var effectBlind = $.effects.effect.blind = function( o, done ) {
+ // Create element
+ var el = $( this ),
+ rvertical = /up|down|vertical/,
+ rpositivemotion = /up|left|vertical|horizontal/,
+ props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+ mode = $.effects.setMode( el, o.mode || "hide" ),
+ direction = o.direction || "up",
+ vertical = rvertical.test( direction ),
+ ref = vertical ? "height" : "width",
+ ref2 = vertical ? "top" : "left",
+ motion = rpositivemotion.test( direction ),
+ animation = {},
+ show = mode === "show",
+ wrapper, distance, margin;
+
+ // if already wrapped, the wrapper's properties are my property. #6245
+ if ( el.parent().is( ".ui-effects-wrapper" ) ) {
+ $.effects.save( el.parent(), props );
+ } else {
+ $.effects.save( el, props );
+ }
+ el.show();
+ wrapper = $.effects.createWrapper( el ).css({
+ overflow: "hidden"
+ });
+
+ distance = wrapper[ ref ]();
+ margin = parseFloat( wrapper.css( ref2 ) ) || 0;
+
+ animation[ ref ] = show ? distance : 0;
+ if ( !motion ) {
+ el
+ .css( vertical ? "bottom" : "right", 0 )
+ .css( vertical ? "top" : "left", "auto" )
+ .css({ position: "absolute" });
+
+ animation[ ref2 ] = show ? margin : distance + margin;
+ }
+
+ // start at 0 if we are showing
+ if ( show ) {
+ wrapper.css( ref, 0 );
+ if ( !motion ) {
+ wrapper.css( ref2, margin + distance );
+ }
+ }
+
+ // Animate
+ wrapper.animate( animation, {
+ duration: o.duration,
+ easing: o.easing,
+ queue: false,
+ complete: function() {
+ if ( mode === "hide" ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ $.effects.removeWrapper( el );
+ done();
+ }
+ });
+};
+
+
+/*!
+ * jQuery UI Effects Bounce 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/bounce-effect/
+ */
+
+
+var effectBounce = $.effects.effect.bounce = function( o, done ) {
+ var el = $( this ),
+ props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+
+ // defaults:
+ mode = $.effects.setMode( el, o.mode || "effect" ),
+ hide = mode === "hide",
+ show = mode === "show",
+ direction = o.direction || "up",
+ distance = o.distance,
+ times = o.times || 5,
+
+ // number of internal animations
+ anims = times * 2 + ( show || hide ? 1 : 0 ),
+ speed = o.duration / anims,
+ easing = o.easing,
+
+ // utility:
+ ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
+ motion = ( direction === "up" || direction === "left" ),
+ i,
+ upAnim,
+ downAnim,
+
+ // we will need to re-assemble the queue to stack our animations in place
+ queue = el.queue(),
+ queuelen = queue.length;
+
+ // Avoid touching opacity to prevent clearType and PNG issues in IE
+ if ( show || hide ) {
+ props.push( "opacity" );
+ }
+
+ $.effects.save( el, props );
+ el.show();
+ $.effects.createWrapper( el ); // Create Wrapper
+
+ // default distance for the BIGGEST bounce is the outer Distance / 3
+ if ( !distance ) {
+ distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
+ }
+
+ if ( show ) {
+ downAnim = { opacity: 1 };
+ downAnim[ ref ] = 0;
+
+ // if we are showing, force opacity 0 and set the initial position
+ // then do the "first" animation
+ el.css( "opacity", 0 )
+ .css( ref, motion ? -distance * 2 : distance * 2 )
+ .animate( downAnim, speed, easing );
+ }
+
+ // start at the smallest distance if we are hiding
+ if ( hide ) {
+ distance = distance / Math.pow( 2, times - 1 );
+ }
+
+ downAnim = {};
+ downAnim[ ref ] = 0;
+ // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
+ for ( i = 0; i < times; i++ ) {
+ upAnim = {};
+ upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
+
+ el.animate( upAnim, speed, easing )
+ .animate( downAnim, speed, easing );
+
+ distance = hide ? distance * 2 : distance / 2;
+ }
+
+ // Last Bounce when Hiding
+ if ( hide ) {
+ upAnim = { opacity: 0 };
+ upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
+
+ el.animate( upAnim, speed, easing );
+ }
+
+ el.queue(function() {
+ if ( hide ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ $.effects.removeWrapper( el );
+ done();
+ });
+
+ // inject all the animations we just queued to be first in line (after "inprogress")
+ if ( queuelen > 1) {
+ queue.splice.apply( queue,
+ [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
+ }
+ el.dequeue();
+
+};
+
+
+/*!
+ * jQuery UI Effects Clip 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/clip-effect/
+ */
+
+
+var effectClip = $.effects.effect.clip = function( o, done ) {
+ // Create element
+ var el = $( this ),
+ props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+ mode = $.effects.setMode( el, o.mode || "hide" ),
+ show = mode === "show",
+ direction = o.direction || "vertical",
+ vert = direction === "vertical",
+ size = vert ? "height" : "width",
+ position = vert ? "top" : "left",
+ animation = {},
+ wrapper, animate, distance;
+
+ // Save & Show
+ $.effects.save( el, props );
+ el.show();
+
+ // Create Wrapper
+ wrapper = $.effects.createWrapper( el ).css({
+ overflow: "hidden"
+ });
+ animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
+ distance = animate[ size ]();
+
+ // Shift
+ if ( show ) {
+ animate.css( size, 0 );
+ animate.css( position, distance / 2 );
+ }
+
+ // Create Animation Object:
+ animation[ size ] = show ? distance : 0;
+ animation[ position ] = show ? 0 : distance / 2;
+
+ // Animate
+ animate.animate( animation, {
+ queue: false,
+ duration: o.duration,
+ easing: o.easing,
+ complete: function() {
+ if ( !show ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ $.effects.removeWrapper( el );
+ done();
+ }
+ });
+
+};
+
+
+/*!
+ * jQuery UI Effects Drop 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/drop-effect/
+ */
+
+
+var effectDrop = $.effects.effect.drop = function( o, done ) {
+
+ var el = $( this ),
+ props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
+ mode = $.effects.setMode( el, o.mode || "hide" ),
+ show = mode === "show",
+ direction = o.direction || "left",
+ ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
+ motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
+ animation = {
+ opacity: show ? 1 : 0
+ },
+ distance;
+
+ // Adjust
+ $.effects.save( el, props );
+ el.show();
+ $.effects.createWrapper( el );
+
+ distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2;
+
+ if ( show ) {
+ el
+ .css( "opacity", 0 )
+ .css( ref, motion === "pos" ? -distance : distance );
+ }
+
+ // Animation
+ animation[ ref ] = ( show ?
+ ( motion === "pos" ? "+=" : "-=" ) :
+ ( motion === "pos" ? "-=" : "+=" ) ) +
+ distance;
+
+ // Animate
+ el.animate( animation, {
+ queue: false,
+ duration: o.duration,
+ easing: o.easing,
+ complete: function() {
+ if ( mode === "hide" ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ $.effects.removeWrapper( el );
+ done();
+ }
+ });
+};
+
+
+/*!
+ * jQuery UI Effects Explode 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/explode-effect/
+ */
+
+
+var effectExplode = $.effects.effect.explode = function( o, done ) {
+
+ var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
+ cells = rows,
+ el = $( this ),
+ mode = $.effects.setMode( el, o.mode || "hide" ),
+ show = mode === "show",
+
+ // show and then visibility:hidden the element before calculating offset
+ offset = el.show().css( "visibility", "hidden" ).offset(),
+
+ // width and height of a piece
+ width = Math.ceil( el.outerWidth() / cells ),
+ height = Math.ceil( el.outerHeight() / rows ),
+ pieces = [],
+
+ // loop
+ i, j, left, top, mx, my;
+
+ // children animate complete:
+ function childComplete() {
+ pieces.push( this );
+ if ( pieces.length === rows * cells ) {
+ animComplete();
+ }
+ }
+
+ // clone the element for each row and cell.
+ for ( i = 0; i < rows ; i++ ) { // ===>
+ top = offset.top + i * height;
+ my = i - ( rows - 1 ) / 2 ;
+
+ for ( j = 0; j < cells ; j++ ) { // |||
+ left = offset.left + j * width;
+ mx = j - ( cells - 1 ) / 2 ;
+
+ // Create a clone of the now hidden main element that will be absolute positioned
+ // within a wrapper div off the -left and -top equal to size of our pieces
+ el
+ .clone()
+ .appendTo( "body" )
+ .wrap( "<div></div>" )
+ .css({
+ position: "absolute",
+ visibility: "visible",
+ left: -j * width,
+ top: -i * height
+ })
+
+ // select the wrapper - make it overflow: hidden and absolute positioned based on
+ // where the original was located +left and +top equal to the size of pieces
+ .parent()
+ .addClass( "ui-effects-explode" )
+ .css({
+ position: "absolute",
+ overflow: "hidden",
+ width: width,
+ height: height,
+ left: left + ( show ? mx * width : 0 ),
+ top: top + ( show ? my * height : 0 ),
+ opacity: show ? 0 : 1
+ }).animate({
+ left: left + ( show ? 0 : mx * width ),
+ top: top + ( show ? 0 : my * height ),
+ opacity: show ? 1 : 0
+ }, o.duration || 500, o.easing, childComplete );
+ }
+ }
+
+ function animComplete() {
+ el.css({
+ visibility: "visible"
+ });
+ $( pieces ).remove();
+ if ( !show ) {
+ el.hide();
+ }
+ done();
+ }
+};
+
+
+/*!
+ * jQuery UI Effects Fade 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/fade-effect/
+ */
+
+
+var effectFade = $.effects.effect.fade = function( o, done ) {
+ var el = $( this ),
+ mode = $.effects.setMode( el, o.mode || "toggle" );
+
+ el.animate({
+ opacity: mode
+ }, {
+ queue: false,
+ duration: o.duration,
+ easing: o.easing,
+ complete: done
+ });
+};
+
+
+/*!
+ * jQuery UI Effects Fold 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/fold-effect/
+ */
+
+
+var effectFold = $.effects.effect.fold = function( o, done ) {
+
+ // Create element
+ var el = $( this ),
+ props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+ mode = $.effects.setMode( el, o.mode || "hide" ),
+ show = mode === "show",
+ hide = mode === "hide",
+ size = o.size || 15,
+ percent = /([0-9]+)%/.exec( size ),
+ horizFirst = !!o.horizFirst,
+ widthFirst = show !== horizFirst,
+ ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
+ duration = o.duration / 2,
+ wrapper, distance,
+ animation1 = {},
+ animation2 = {};
+
+ $.effects.save( el, props );
+ el.show();
+
+ // Create Wrapper
+ wrapper = $.effects.createWrapper( el ).css({
+ overflow: "hidden"
+ });
+ distance = widthFirst ?
+ [ wrapper.width(), wrapper.height() ] :
+ [ wrapper.height(), wrapper.width() ];
+
+ if ( percent ) {
+ size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
+ }
+ if ( show ) {
+ wrapper.css( horizFirst ? {
+ height: 0,
+ width: size
+ } : {
+ height: size,
+ width: 0
+ });
+ }
+
+ // Animation
+ animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
+ animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
+
+ // Animate
+ wrapper
+ .animate( animation1, duration, o.easing )
+ .animate( animation2, duration, o.easing, function() {
+ if ( hide ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ $.effects.removeWrapper( el );
+ done();
+ });
+
+};
+
+
+/*!
+ * jQuery UI Effects Highlight 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/highlight-effect/
+ */
+
+
+var effectHighlight = $.effects.effect.highlight = function( o, done ) {
+ var elem = $( this ),
+ props = [ "backgroundImage", "backgroundColor", "opacity" ],
+ mode = $.effects.setMode( elem, o.mode || "show" ),
+ animation = {
+ backgroundColor: elem.css( "backgroundColor" )
+ };
+
+ if (mode === "hide") {
+ animation.opacity = 0;
+ }
+
+ $.effects.save( elem, props );
+
+ elem
+ .show()
+ .css({
+ backgroundImage: "none",
+ backgroundColor: o.color || "#ffff99"
+ })
+ .animate( animation, {
+ queue: false,
+ duration: o.duration,
+ easing: o.easing,
+ complete: function() {
+ if ( mode === "hide" ) {
+ elem.hide();
+ }
+ $.effects.restore( elem, props );
+ done();
+ }
+ });
+};
+
+
+/*!
+ * jQuery UI Effects Size 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/size-effect/
+ */
+
+
+var effectSize = $.effects.effect.size = function( o, done ) {
+
+ // Create element
+ var original, baseline, factor,
+ el = $( this ),
+ props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],
+
+ // Always restore
+ props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],
+
+ // Copy for children
+ props2 = [ "width", "height", "overflow" ],
+ cProps = [ "fontSize" ],
+ vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
+ hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
+
+ // Set options
+ mode = $.effects.setMode( el, o.mode || "effect" ),
+ restore = o.restore || mode !== "effect",
+ scale = o.scale || "both",
+ origin = o.origin || [ "middle", "center" ],
+ position = el.css( "position" ),
+ props = restore ? props0 : props1,
+ zero = {
+ height: 0,
+ width: 0,
+ outerHeight: 0,
+ outerWidth: 0
+ };
+
+ if ( mode === "show" ) {
+ el.show();
+ }
+ original = {
+ height: el.height(),
+ width: el.width(),
+ outerHeight: el.outerHeight(),
+ outerWidth: el.outerWidth()
+ };
+
+ if ( o.mode === "toggle" && mode === "show" ) {
+ el.from = o.to || zero;
+ el.to = o.from || original;
+ } else {
+ el.from = o.from || ( mode === "show" ? zero : original );
+ el.to = o.to || ( mode === "hide" ? zero : original );
+ }
+
+ // Set scaling factor
+ factor = {
+ from: {
+ y: el.from.height / original.height,
+ x: el.from.width / original.width
+ },
+ to: {
+ y: el.to.height / original.height,
+ x: el.to.width / original.width
+ }
+ };
+
+ // Scale the css box
+ if ( scale === "box" || scale === "both" ) {
+
+ // Vertical props scaling
+ if ( factor.from.y !== factor.to.y ) {
+ props = props.concat( vProps );
+ el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
+ el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
+ }
+
+ // Horizontal props scaling
+ if ( factor.from.x !== factor.to.x ) {
+ props = props.concat( hProps );
+ el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
+ el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
+ }
+ }
+
+ // Scale the content
+ if ( scale === "content" || scale === "both" ) {
+
+ // Vertical props scaling
+ if ( factor.from.y !== factor.to.y ) {
+ props = props.concat( cProps ).concat( props2 );
+ el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
+ el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
+ }
+ }
+
+ $.effects.save( el, props );
+ el.show();
+ $.effects.createWrapper( el );
+ el.css( "overflow", "hidden" ).css( el.from );
+
+ // Adjust
+ if (origin) { // Calculate baseline shifts
+ baseline = $.effects.getBaseline( origin, original );
+ el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
+ el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
+ el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
+ el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
+ }
+ el.css( el.from ); // set top & left
+
+ // Animate
+ if ( scale === "content" || scale === "both" ) { // Scale the children
+
+ // Add margins/font-size
+ vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
+ hProps = hProps.concat([ "marginLeft", "marginRight" ]);
+ props2 = props0.concat(vProps).concat(hProps);
+
+ el.find( "*[width]" ).each( function() {
+ var child = $( this ),
+ c_original = {
+ height: child.height(),
+ width: child.width(),
+ outerHeight: child.outerHeight(),
+ outerWidth: child.outerWidth()
+ };
+ if (restore) {
+ $.effects.save(child, props2);
+ }
+
+ child.from = {
+ height: c_original.height * factor.from.y,
+ width: c_original.width * factor.from.x,
+ outerHeight: c_original.outerHeight * factor.from.y,
+ outerWidth: c_original.outerWidth * factor.from.x
+ };
+ child.to = {
+ height: c_original.height * factor.to.y,
+ width: c_original.width * factor.to.x,
+ outerHeight: c_original.height * factor.to.y,
+ outerWidth: c_original.width * factor.to.x
+ };
+
+ // Vertical props scaling
+ if ( factor.from.y !== factor.to.y ) {
+ child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
+ child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
+ }
+
+ // Horizontal props scaling
+ if ( factor.from.x !== factor.to.x ) {
+ child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
+ child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
+ }
+
+ // Animate children
+ child.css( child.from );
+ child.animate( child.to, o.duration, o.easing, function() {
+
+ // Restore children
+ if ( restore ) {
+ $.effects.restore( child, props2 );
+ }
+ });
+ });
+ }
+
+ // Animate
+ el.animate( el.to, {
+ queue: false,
+ duration: o.duration,
+ easing: o.easing,
+ complete: function() {
+ if ( el.to.opacity === 0 ) {
+ el.css( "opacity", el.from.opacity );
+ }
+ if ( mode === "hide" ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ if ( !restore ) {
+
+ // we need to calculate our new positioning based on the scaling
+ if ( position === "static" ) {
+ el.css({
+ position: "relative",
+ top: el.to.top,
+ left: el.to.left
+ });
+ } else {
+ $.each([ "top", "left" ], function( idx, pos ) {
+ el.css( pos, function( _, str ) {
+ var val = parseInt( str, 10 ),
+ toRef = idx ? el.to.left : el.to.top;
+
+ // if original was "auto", recalculate the new value from wrapper
+ if ( str === "auto" ) {
+ return toRef + "px";
+ }
+
+ return val + toRef + "px";
+ });
+ });
+ }
+ }
+
+ $.effects.removeWrapper( el );
+ done();
+ }
+ });
+
+};
+
+
+/*!
+ * jQuery UI Effects Scale 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/scale-effect/
+ */
+
+
+var effectScale = $.effects.effect.scale = function( o, done ) {
+
+ // Create element
+ var el = $( this ),
+ options = $.extend( true, {}, o ),
+ mode = $.effects.setMode( el, o.mode || "effect" ),
+ percent = parseInt( o.percent, 10 ) ||
+ ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
+ direction = o.direction || "both",
+ origin = o.origin,
+ original = {
+ height: el.height(),
+ width: el.width(),
+ outerHeight: el.outerHeight(),
+ outerWidth: el.outerWidth()
+ },
+ factor = {
+ y: direction !== "horizontal" ? (percent / 100) : 1,
+ x: direction !== "vertical" ? (percent / 100) : 1
+ };
+
+ // We are going to pass this effect to the size effect:
+ options.effect = "size";
+ options.queue = false;
+ options.complete = done;
+
+ // Set default origin and restore for show/hide
+ if ( mode !== "effect" ) {
+ options.origin = origin || [ "middle", "center" ];
+ options.restore = true;
+ }
+
+ options.from = o.from || ( mode === "show" ? {
+ height: 0,
+ width: 0,
+ outerHeight: 0,
+ outerWidth: 0
+ } : original );
+ options.to = {
+ height: original.height * factor.y,
+ width: original.width * factor.x,
+ outerHeight: original.outerHeight * factor.y,
+ outerWidth: original.outerWidth * factor.x
+ };
+
+ // Fade option to support puff
+ if ( options.fade ) {
+ if ( mode === "show" ) {
+ options.from.opacity = 0;
+ options.to.opacity = 1;
+ }
+ if ( mode === "hide" ) {
+ options.from.opacity = 1;
+ options.to.opacity = 0;
+ }
+ }
+
+ // Animate
+ el.effect( options );
+
+};
+
+
+/*!
+ * jQuery UI Effects Puff 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/puff-effect/
+ */
+
+
+var effectPuff = $.effects.effect.puff = function( o, done ) {
+ var elem = $( this ),
+ mode = $.effects.setMode( elem, o.mode || "hide" ),
+ hide = mode === "hide",
+ percent = parseInt( o.percent, 10 ) || 150,
+ factor = percent / 100,
+ original = {
+ height: elem.height(),
+ width: elem.width(),
+ outerHeight: elem.outerHeight(),
+ outerWidth: elem.outerWidth()
+ };
+
+ $.extend( o, {
+ effect: "scale",
+ queue: false,
+ fade: true,
+ mode: mode,
+ complete: done,
+ percent: hide ? percent : 100,
+ from: hide ?
+ original :
+ {
+ height: original.height * factor,
+ width: original.width * factor,
+ outerHeight: original.outerHeight * factor,
+ outerWidth: original.outerWidth * factor
+ }
+ });
+
+ elem.effect( o );
+};
+
+
+/*!
+ * jQuery UI Effects Pulsate 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/pulsate-effect/
+ */
+
+
+var effectPulsate = $.effects.effect.pulsate = function( o, done ) {
+ var elem = $( this ),
+ mode = $.effects.setMode( elem, o.mode || "show" ),
+ show = mode === "show",
+ hide = mode === "hide",
+ showhide = ( show || mode === "hide" ),
+
+ // showing or hiding leaves of the "last" animation
+ anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
+ duration = o.duration / anims,
+ animateTo = 0,
+ queue = elem.queue(),
+ queuelen = queue.length,
+ i;
+
+ if ( show || !elem.is(":visible")) {
+ elem.css( "opacity", 0 ).show();
+ animateTo = 1;
+ }
+
+ // anims - 1 opacity "toggles"
+ for ( i = 1; i < anims; i++ ) {
+ elem.animate({
+ opacity: animateTo
+ }, duration, o.easing );
+ animateTo = 1 - animateTo;
+ }
+
+ elem.animate({
+ opacity: animateTo
+ }, duration, o.easing);
+
+ elem.queue(function() {
+ if ( hide ) {
+ elem.hide();
+ }
+ done();
+ });
+
+ // We just queued up "anims" animations, we need to put them next in the queue
+ if ( queuelen > 1 ) {
+ queue.splice.apply( queue,
+ [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
+ }
+ elem.dequeue();
+};
+
+
+/*!
+ * jQuery UI Effects Shake 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/shake-effect/
+ */
+
+
+var effectShake = $.effects.effect.shake = function( o, done ) {
+
+ var el = $( this ),
+ props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+ mode = $.effects.setMode( el, o.mode || "effect" ),
+ direction = o.direction || "left",
+ distance = o.distance || 20,
+ times = o.times || 3,
+ anims = times * 2 + 1,
+ speed = Math.round( o.duration / anims ),
+ ref = (direction === "up" || direction === "down") ? "top" : "left",
+ positiveMotion = (direction === "up" || direction === "left"),
+ animation = {},
+ animation1 = {},
+ animation2 = {},
+ i,
+
+ // we will need to re-assemble the queue to stack our animations in place
+ queue = el.queue(),
+ queuelen = queue.length;
+
+ $.effects.save( el, props );
+ el.show();
+ $.effects.createWrapper( el );
+
+ // Animation
+ animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
+ animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
+ animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
+
+ // Animate
+ el.animate( animation, speed, o.easing );
+
+ // Shakes
+ for ( i = 1; i < times; i++ ) {
+ el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
+ }
+ el
+ .animate( animation1, speed, o.easing )
+ .animate( animation, speed / 2, o.easing )
+ .queue(function() {
+ if ( mode === "hide" ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ $.effects.removeWrapper( el );
+ done();
+ });
+
+ // inject all the animations we just queued to be first in line (after "inprogress")
+ if ( queuelen > 1) {
+ queue.splice.apply( queue,
+ [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
+ }
+ el.dequeue();
+
+};
+
+
+/*!
+ * jQuery UI Effects Slide 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/slide-effect/
+ */
+
+
+var effectSlide = $.effects.effect.slide = function( o, done ) {
+
+ // Create element
+ var el = $( this ),
+ props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
+ mode = $.effects.setMode( el, o.mode || "show" ),
+ show = mode === "show",
+ direction = o.direction || "left",
+ ref = (direction === "up" || direction === "down") ? "top" : "left",
+ positiveMotion = (direction === "up" || direction === "left"),
+ distance,
+ animation = {};
+
+ // Adjust
+ $.effects.save( el, props );
+ el.show();
+ distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );
+
+ $.effects.createWrapper( el ).css({
+ overflow: "hidden"
+ });
+
+ if ( show ) {
+ el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
+ }
+
+ // Animation
+ animation[ ref ] = ( show ?
+ ( positiveMotion ? "+=" : "-=") :
+ ( positiveMotion ? "-=" : "+=")) +
+ distance;
+
+ // Animate
+ el.animate( animation, {
+ queue: false,
+ duration: o.duration,
+ easing: o.easing,
+ complete: function() {
+ if ( mode === "hide" ) {
+ el.hide();
+ }
+ $.effects.restore( el, props );
+ $.effects.removeWrapper( el );
+ done();
+ }
+ });
+};
+
+
+/*!
+ * jQuery UI Effects Transfer 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/transfer-effect/
+ */
+
+
+var effectTransfer = $.effects.effect.transfer = function( o, done ) {
+ var elem = $( this ),
+ target = $( o.to ),
+ targetFixed = target.css( "position" ) === "fixed",
+ body = $("body"),
+ fixTop = targetFixed ? body.scrollTop() : 0,
+ fixLeft = targetFixed ? body.scrollLeft() : 0,
+ endPosition = target.offset(),
+ animation = {
+ top: endPosition.top - fixTop,
+ left: endPosition.left - fixLeft,
+ height: target.innerHeight(),
+ width: target.innerWidth()
+ },
+ startPosition = elem.offset(),
+ transfer = $( "<div class='ui-effects-transfer'></div>" )
+ .appendTo( document.body )
+ .addClass( o.className )
+ .css({
+ top: startPosition.top - fixTop,
+ left: startPosition.left - fixLeft,
+ height: elem.innerHeight(),
+ width: elem.innerWidth(),
+ position: targetFixed ? "fixed" : "absolute"
+ })
+ .animate( animation, o.duration, o.easing, function() {
+ transfer.remove();
+ done();
+ });
+};
+
+
+/*!
+ * jQuery UI Progressbar 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/progressbar/
+ */
+
+
+var progressbar = $.widget( "ui.progressbar", {
+ version: "1.11.2",
+ options: {
+ max: 100,
+ value: 0,
+
+ change: null,
+ complete: null
+ },
+
+ min: 0,
+
+ _create: function() {
+ // Constrain initial value
+ this.oldValue = this.options.value = this._constrainedValue();
+
+ this.element
+ .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
+ .attr({
+ // Only set static values, aria-valuenow and aria-valuemax are
+ // set inside _refreshValue()
+ role: "progressbar",
+ "aria-valuemin": this.min
+ });
+
+ this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
+ .appendTo( this.element );
+
+ this._refreshValue();
+ },
+
+ _destroy: function() {
+ this.element
+ .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
+ .removeAttr( "role" )
+ .removeAttr( "aria-valuemin" )
+ .removeAttr( "aria-valuemax" )
+ .removeAttr( "aria-valuenow" );
+
+ this.valueDiv.remove();
+ },
+
+ value: function( newValue ) {
+ if ( newValue === undefined ) {
+ return this.options.value;
+ }
+
+ this.options.value = this._constrainedValue( newValue );
+ this._refreshValue();
+ },
+
+ _constrainedValue: function( newValue ) {
+ if ( newValue === undefined ) {
+ newValue = this.options.value;
+ }
+
+ this.indeterminate = newValue === false;
+
+ // sanitize value
+ if ( typeof newValue !== "number" ) {
+ newValue = 0;
+ }
+
+ return this.indeterminate ? false :
+ Math.min( this.options.max, Math.max( this.min, newValue ) );
+ },
+
+ _setOptions: function( options ) {
+ // Ensure "value" option is set after other values (like max)
+ var value = options.value;
+ delete options.value;
+
+ this._super( options );
+
+ this.options.value = this._constrainedValue( value );
+ this._refreshValue();
+ },
+
+ _setOption: function( key, value ) {
+ if ( key === "max" ) {
+ // Don't allow a max less than min
+ value = Math.max( this.min, value );
+ }
+ if ( key === "disabled" ) {
+ this.element
+ .toggleClass( "ui-state-disabled", !!value )
+ .attr( "aria-disabled", value );
+ }
+ this._super( key, value );
+ },
+
+ _percentage: function() {
+ return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
+ },
+
+ _refreshValue: function() {
+ var value = this.options.value,
+ percentage = this._percentage();
+
+ this.valueDiv
+ .toggle( this.indeterminate || value > this.min )
+ .toggleClass( "ui-corner-right", value === this.options.max )
+ .width( percentage.toFixed(0) + "%" );
+
+ this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );
+
+ if ( this.indeterminate ) {
+ this.element.removeAttr( "aria-valuenow" );
+ if ( !this.overlayDiv ) {
+ this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
+ }
+ } else {
+ this.element.attr({
+ "aria-valuemax": this.options.max,
+ "aria-valuenow": value
+ });
+ if ( this.overlayDiv ) {
+ this.overlayDiv.remove();
+ this.overlayDiv = null;
+ }
+ }
+
+ if ( this.oldValue !== value ) {
+ this.oldValue = value;
+ this._trigger( "change" );
+ }
+ if ( value === this.options.max ) {
+ this._trigger( "complete" );
+ }
+ }
+});
+
+
+/*!
+ * jQuery UI Selectable 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/selectable/
+ */
+
+
+var selectable = $.widget("ui.selectable", $.ui.mouse, {
+ version: "1.11.2",
+ options: {
+ appendTo: "body",
+ autoRefresh: true,
+ distance: 0,
+ filter: "*",
+ tolerance: "touch",
+
+ // callbacks
+ selected: null,
+ selecting: null,
+ start: null,
+ stop: null,
+ unselected: null,
+ unselecting: null
+ },
+ _create: function() {
+ var selectees,
+ that = this;
+
+ this.element.addClass("ui-selectable");
+
+ this.dragged = false;
+
+ // cache selectee children based on filter
+ this.refresh = function() {
+ selectees = $(that.options.filter, that.element[0]);
+ selectees.addClass("ui-selectee");
+ selectees.each(function() {
+ var $this = $(this),
+ pos = $this.offset();
+ $.data(this, "selectable-item", {
+ element: this,
+ $element: $this,
+ left: pos.left,
+ top: pos.top,
+ right: pos.left + $this.outerWidth(),
+ bottom: pos.top + $this.outerHeight(),
+ startselected: false,
+ selected: $this.hasClass("ui-selected"),
+ selecting: $this.hasClass("ui-selecting"),
+ unselecting: $this.hasClass("ui-unselecting")
+ });
+ });
+ };
+ this.refresh();
+
+ this.selectees = selectees.addClass("ui-selectee");
+
+ this._mouseInit();
+
+ this.helper = $("<div class='ui-selectable-helper'></div>");
+ },
+
+ _destroy: function() {
+ this.selectees
+ .removeClass("ui-selectee")
+ .removeData("selectable-item");
+ this.element
+ .removeClass("ui-selectable ui-selectable-disabled");
+ this._mouseDestroy();
+ },
+
+ _mouseStart: function(event) {
+ var that = this,
+ options = this.options;
+
+ this.opos = [ event.pageX, event.pageY ];
+
+ if (this.options.disabled) {
+ return;
+ }
+
+ this.selectees = $(options.filter, this.element[0]);
+
+ this._trigger("start", event);
+
+ $(options.appendTo).append(this.helper);
+ // position helper (lasso)
+ this.helper.css({
+ "left": event.pageX,
+ "top": event.pageY,
+ "width": 0,
+ "height": 0
+ });
+
+ if (options.autoRefresh) {
+ this.refresh();
+ }
+
+ this.selectees.filter(".ui-selected").each(function() {
+ var selectee = $.data(this, "selectable-item");
+ selectee.startselected = true;
+ if (!event.metaKey && !event.ctrlKey) {
+ selectee.$element.removeClass("ui-selected");
+ selectee.selected = false;
+ selectee.$element.addClass("ui-unselecting");
+ selectee.unselecting = true;
+ // selectable UNSELECTING callback
+ that._trigger("unselecting", event, {
+ unselecting: selectee.element
+ });
+ }
+ });
+
+ $(event.target).parents().addBack().each(function() {
+ var doSelect,
+ selectee = $.data(this, "selectable-item");
+ if (selectee) {
+ doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
+ selectee.$element
+ .removeClass(doSelect ? "ui-unselecting" : "ui-selected")
+ .addClass(doSelect ? "ui-selecting" : "ui-unselecting");
+ selectee.unselecting = !doSelect;
+ selectee.selecting = doSelect;
+ selectee.selected = doSelect;
+ // selectable (UN)SELECTING callback
+ if (doSelect) {
+ that._trigger("selecting", event, {
+ selecting: selectee.element
+ });
+ } else {
+ that._trigger("unselecting", event, {
+ unselecting: selectee.element
+ });
+ }
+ return false;
+ }
+ });
+
+ },
+
+ _mouseDrag: function(event) {
+
+ this.dragged = true;
+
+ if (this.options.disabled) {
+ return;
+ }
+
+ var tmp,
+ that = this,
+ options = this.options,
+ x1 = this.opos[0],
+ y1 = this.opos[1],
+ x2 = event.pageX,
+ y2 = event.pageY;
+
+ if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
+ if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
+ this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 });
+
+ this.selectees.each(function() {
+ var selectee = $.data(this, "selectable-item"),
+ hit = false;
+
+ //prevent helper from being selected if appendTo: selectable
+ if (!selectee || selectee.element === that.element[0]) {
+ return;
+ }
+
+ if (options.tolerance === "touch") {
+ hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
+ } else if (options.tolerance === "fit") {
+ hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
+ }
+
+ if (hit) {
+ // SELECT
+ if (selectee.selected) {
+ selectee.$element.removeClass("ui-selected");
+ selectee.selected = false;
+ }
+ if (selectee.unselecting) {
+ selectee.$element.removeClass("ui-unselecting");
+ selectee.unselecting = false;
+ }
+ if (!selectee.selecting) {
+ selectee.$element.addClass("ui-selecting");
+ selectee.selecting = true;
+ // selectable SELECTING callback
+ that._trigger("selecting", event, {
+ selecting: selectee.element
+ });
+ }
+ } else {
+ // UNSELECT
+ if (selectee.selecting) {
+ if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
+ selectee.$element.removeClass("ui-selecting");
+ selectee.selecting = false;
+ selectee.$element.addClass("ui-selected");
+ selectee.selected = true;
+ } else {
+ selectee.$element.removeClass("ui-selecting");
+ selectee.selecting = false;
+ if (selectee.startselected) {
+ selectee.$element.addClass("ui-unselecting");
+ selectee.unselecting = true;
+ }
+ // selectable UNSELECTING callback
+ that._trigger("unselecting", event, {
+ unselecting: selectee.element
+ });
+ }
+ }
+ if (selectee.selected) {
+ if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
+ selectee.$element.removeClass("ui-selected");
+ selectee.selected = false;
+
+ selectee.$element.addClass("ui-unselecting");
+ selectee.unselecting = true;
+ // selectable UNSELECTING callback
+ that._trigger("unselecting", event, {
+ unselecting: selectee.element
+ });
+ }
+ }
+ }
+ });
+
+ return false;
+ },
+
+ _mouseStop: function(event) {
+ var that = this;
+
+ this.dragged = false;
+
+ $(".ui-unselecting", this.element[0]).each(function() {
+ var selectee = $.data(this, "selectable-item");
+ selectee.$element.removeClass("ui-unselecting");
+ selectee.unselecting = false;
+ selectee.startselected = false;
+ that._trigger("unselected", event, {
+ unselected: selectee.element
+ });
+ });
+ $(".ui-selecting", this.element[0]).each(function() {
+ var selectee = $.data(this, "selectable-item");
+ selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
+ selectee.selecting = false;
+ selectee.selected = true;
+ selectee.startselected = true;
+ that._trigger("selected", event, {
+ selected: selectee.element
+ });
+ });
+ this._trigger("stop", event);
+
+ this.helper.remove();
+
+ return false;
+ }
+
+});
+
+
+/*!
+ * jQuery UI Selectmenu 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/selectmenu
+ */
+
+
+var selectmenu = $.widget( "ui.selectmenu", {
+ version: "1.11.2",
+ defaultElement: "<select>",
+ options: {
+ appendTo: null,
+ disabled: null,
+ icons: {
+ button: "ui-icon-triangle-1-s"
+ },
+ position: {
+ my: "left top",
+ at: "left bottom",
+ collision: "none"
+ },
+ width: null,
+
+ // callbacks
+ change: null,
+ close: null,
+ focus: null,
+ open: null,
+ select: null
+ },
+
+ _create: function() {
+ var selectmenuId = this.element.uniqueId().attr( "id" );
+ this.ids = {
+ element: selectmenuId,
+ button: selectmenuId + "-button",
+ menu: selectmenuId + "-menu"
+ };
+
+ this._drawButton();
+ this._drawMenu();
+
+ if ( this.options.disabled ) {
+ this.disable();
+ }
+ },
+
+ _drawButton: function() {
+ var that = this,
+ tabindex = this.element.attr( "tabindex" );
+
+ // Associate existing label with the new button
+ this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button );
+ this._on( this.label, {
+ click: function( event ) {
+ this.button.focus();
+ event.preventDefault();
+ }
+ });
+
+ // Hide original select element
+ this.element.hide();
+
+ // Create button
+ this.button = $( "<span>", {
+ "class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all",
+ tabindex: tabindex || this.options.disabled ? -1 : 0,
+ id: this.ids.button,
+ role: "combobox",
+ "aria-expanded": "false",
+ "aria-autocomplete": "list",
+ "aria-owns": this.ids.menu,
+ "aria-haspopup": "true"
+ })
+ .insertAfter( this.element );
+
+ $( "<span>", {
+ "class": "ui-icon " + this.options.icons.button
+ })
+ .prependTo( this.button );
+
+ this.buttonText = $( "<span>", {
+ "class": "ui-selectmenu-text"
+ })
+ .appendTo( this.button );
+
+ this._setText( this.buttonText, this.element.find( "option:selected" ).text() );
+ this._resizeButton();
+
+ this._on( this.button, this._buttonEvents );
+ this.button.one( "focusin", function() {
+
+ // Delay rendering the menu items until the button receives focus.
+ // The menu may have already been rendered via a programmatic open.
+ if ( !that.menuItems ) {
+ that._refreshMenu();
+ }
+ });
+ this._hoverable( this.button );
+ this._focusable( this.button );
+ },
+
+ _drawMenu: function() {
+ var that = this;
+
+ // Create menu
+ this.menu = $( "<ul>", {
+ "aria-hidden": "true",
+ "aria-labelledby": this.ids.button,
+ id: this.ids.menu
+ });
+
+ // Wrap menu
+ this.menuWrap = $( "<div>", {
+ "class": "ui-selectmenu-menu ui-front"
+ })
+ .append( this.menu )
+ .appendTo( this._appendTo() );
+
+ // Initialize menu widget
+ this.menuInstance = this.menu
+ .menu({
+ role: "listbox",
+ select: function( event, ui ) {
+ event.preventDefault();
+
+ // support: IE8
+ // If the item was selected via a click, the text selection
+ // will be destroyed in IE
+ that._setSelection();
+
+ that._select( ui.item.data( "ui-selectmenu-item" ), event );
+ },
+ focus: function( event, ui ) {
+ var item = ui.item.data( "ui-selectmenu-item" );
+
+ // Prevent inital focus from firing and check if its a newly focused item
+ if ( that.focusIndex != null && item.index !== that.focusIndex ) {
+ that._trigger( "focus", event, { item: item } );
+ if ( !that.isOpen ) {
+ that._select( item, event );
+ }
+ }
+ that.focusIndex = item.index;
+
+ that.button.attr( "aria-activedescendant",
+ that.menuItems.eq( item.index ).attr( "id" ) );
+ }
+ })
+ .menu( "instance" );
+
+ // Adjust menu styles to dropdown
+ this.menu
+ .addClass( "ui-corner-bottom" )
+ .removeClass( "ui-corner-all" );
+
+ // Don't close the menu on mouseleave
+ this.menuInstance._off( this.menu, "mouseleave" );
+
+ // Cancel the menu's collapseAll on document click
+ this.menuInstance._closeOnDocumentClick = function() {
+ return false;
+ };
+
+ // Selects often contain empty items, but never contain dividers
+ this.menuInstance._isDivider = function() {
+ return false;
+ };
+ },
+
+ refresh: function() {
+ this._refreshMenu();
+ this._setText( this.buttonText, this._getSelectedItem().text() );
+ if ( !this.options.width ) {
+ this._resizeButton();
+ }
+ },
+
+ _refreshMenu: function() {
+ this.menu.empty();
+
+ var item,
+ options = this.element.find( "option" );
+
+ if ( !options.length ) {
+ return;
+ }
+
+ this._parseOptions( options );
+ this._renderMenu( this.menu, this.items );
+
+ this.menuInstance.refresh();
+ this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" );
+
+ item = this._getSelectedItem();
+
+ // Update the menu to have the correct item focused
+ this.menuInstance.focus( null, item );
+ this._setAria( item.data( "ui-selectmenu-item" ) );
+
+ // Set disabled state
+ this._setOption( "disabled", this.element.prop( "disabled" ) );
+ },
+
+ open: function( event ) {
+ if ( this.options.disabled ) {
+ return;
+ }
+
+ // If this is the first time the menu is being opened, render the items
+ if ( !this.menuItems ) {
+ this._refreshMenu();
+ } else {
+
+ // Menu clears focus on close, reset focus to selected item
+ this.menu.find( ".ui-state-focus" ).removeClass( "ui-state-focus" );
+ this.menuInstance.focus( null, this._getSelectedItem() );
+ }
+
+ this.isOpen = true;
+ this._toggleAttr();
+ this._resizeMenu();
+ this._position();
+
+ this._on( this.document, this._documentClick );
+
+ this._trigger( "open", event );
+ },
+
+ _position: function() {
+ this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );
+ },
+
+ close: function( event ) {
+ if ( !this.isOpen ) {
+ return;
+ }
+
+ this.isOpen = false;
+ this._toggleAttr();
+
+ this.range = null;
+ this._off( this.document );
+
+ this._trigger( "close", event );
+ },
+
+ widget: function() {
+ return this.button;
+ },
+
+ menuWidget: function() {
+ return this.menu;
+ },
+
+ _renderMenu: function( ul, items ) {
+ var that = this,
+ currentOptgroup = "";
+
+ $.each( items, function( index, item ) {
+ if ( item.optgroup !== currentOptgroup ) {
+ $( "<li>", {
+ "class": "ui-selectmenu-optgroup ui-menu-divider" +
+ ( item.element.parent( "optgroup" ).prop( "disabled" ) ?
+ " ui-state-disabled" :
+ "" ),
+ text: item.optgroup
+ })
+ .appendTo( ul );
+
+ currentOptgroup = item.optgroup;
+ }
+
+ that._renderItemData( ul, item );
+ });
+ },
+
+ _renderItemData: function( ul, item ) {
+ return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
+ },
+
+ _renderItem: function( ul, item ) {
+ var li = $( "<li>" );
+
+ if ( item.disabled ) {
+ li.addClass( "ui-state-disabled" );
+ }
+ this._setText( li, item.label );
+
+ return li.appendTo( ul );
+ },
+
+ _setText: function( element, value ) {
+ if ( value ) {
+ element.text( value );
+ } else {
+ element.html( " " );
+ }
+ },
+
+ _move: function( direction, event ) {
+ var item, next,
+ filter = ".ui-menu-item";
+
+ if ( this.isOpen ) {
+ item = this.menuItems.eq( this.focusIndex );
+ } else {
+ item = this.menuItems.eq( this.element[ 0 ].selectedIndex );
+ filter += ":not(.ui-state-disabled)";
+ }
+
+ if ( direction === "first" || direction === "last" ) {
+ next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 );
+ } else {
+ next = item[ direction + "All" ]( filter ).eq( 0 );
+ }
+
+ if ( next.length ) {
+ this.menuInstance.focus( event, next );
+ }
+ },
+
+ _getSelectedItem: function() {
+ return this.menuItems.eq( this.element[ 0 ].selectedIndex );
+ },
+
+ _toggle: function( event ) {
+ this[ this.isOpen ? "close" : "open" ]( event );
+ },
+
+ _setSelection: function() {
+ var selection;
+
+ if ( !this.range ) {
+ return;
+ }
+
+ if ( window.getSelection ) {
+ selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange( this.range );
+
+ // support: IE8
+ } else {
+ this.range.select();
+ }
+
+ // support: IE
+ // Setting the text selection kills the button focus in IE, but
+ // restoring the focus doesn't kill the selection.
+ this.button.focus();
+ },
+
+ _documentClick: {
+ mousedown: function( event ) {
+ if ( !this.isOpen ) {
+ return;
+ }
+
+ if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" + this.ids.button ).length ) {
+ this.close( event );
+ }
+ }
+ },
+
+ _buttonEvents: {
+
+ // Prevent text selection from being reset when interacting with the selectmenu (#10144)
+ mousedown: function() {
+ var selection;
+
+ if ( window.getSelection ) {
+ selection = window.getSelection();
+ if ( selection.rangeCount ) {
+ this.range = selection.getRangeAt( 0 );
+ }
+
+ // support: IE8
+ } else {
+ this.range = document.selection.createRange();
+ }
+ },
+
+ click: function( event ) {
+ this._setSelection();
+ this._toggle( event );
+ },
+
+ keydown: function( event ) {
+ var preventDefault = true;
+ switch ( event.keyCode ) {
+ case $.ui.keyCode.TAB:
+ case $.ui.keyCode.ESCAPE:
+ this.close( event );
+ preventDefault = false;
+ break;
+ case $.ui.keyCode.ENTER:
+ if ( this.isOpen ) {
+ this._selectFocusedItem( event );
+ }
+ break;
+ case $.ui.keyCode.UP:
+ if ( event.altKey ) {
+ this._toggle( event );
+ } else {
+ this._move( "prev", event );
+ }
+ break;
+ case $.ui.keyCode.DOWN:
+ if ( event.altKey ) {
+ this._toggle( event );
+ } else {
+ this._move( "next", event );
+ }
+ break;
+ case $.ui.keyCode.SPACE:
+ if ( this.isOpen ) {
+ this._selectFocusedItem( event );
+ } else {
+ this._toggle( event );
+ }
+ break;
+ case $.ui.keyCode.LEFT:
+ this._move( "prev", event );
+ break;
+ case $.ui.keyCode.RIGHT:
+ this._move( "next", event );
+ break;
+ case $.ui.keyCode.HOME:
+ case $.ui.keyCode.PAGE_UP:
+ this._move( "first", event );
+ break;
+ case $.ui.keyCode.END:
+ case $.ui.keyCode.PAGE_DOWN:
+ this._move( "last", event );
+ break;
+ default:
+ this.menu.trigger( event );
+ preventDefault = false;
+ }
+
+ if ( preventDefault ) {
+ event.preventDefault();
+ }
+ }
+ },
+
+ _selectFocusedItem: function( event ) {
+ var item = this.menuItems.eq( this.focusIndex );
+ if ( !item.hasClass( "ui-state-disabled" ) ) {
+ this._select( item.data( "ui-selectmenu-item" ), event );
+ }
+ },
+
+ _select: function( item, event ) {
+ var oldIndex = this.element[ 0 ].selectedIndex;
+
+ // Change native select element
+ this.element[ 0 ].selectedIndex = item.index;
+ this._setText( this.buttonText, item.label );
+ this._setAria( item );
+ this._trigger( "select", event, { item: item } );
+
+ if ( item.index !== oldIndex ) {
+ this._trigger( "change", event, { item: item } );
+ }
+
+ this.close( event );
+ },
+
+ _setAria: function( item ) {
+ var id = this.menuItems.eq( item.index ).attr( "id" );
+
+ this.button.attr({
+ "aria-labelledby": id,
+ "aria-activedescendant": id
+ });
+ this.menu.attr( "aria-activedescendant", id );
+ },
+
+ _setOption: function( key, value ) {
+ if ( key === "icons" ) {
+ this.button.find( "span.ui-icon" )
+ .removeClass( this.options.icons.button )
+ .addClass( value.button );
+ }
+
+ this._super( key, value );
+
+ if ( key === "appendTo" ) {
+ this.menuWrap.appendTo( this._appendTo() );
+ }
+
+ if ( key === "disabled" ) {
+ this.menuInstance.option( "disabled", value );
+ this.button
+ .toggleClass( "ui-state-disabled", value )
+ .attr( "aria-disabled", value );
+
+ this.element.prop( "disabled", value );
+ if ( value ) {
+ this.button.attr( "tabindex", -1 );
+ this.close();
+ } else {
+ this.button.attr( "tabindex", 0 );
+ }
+ }
+
+ if ( key === "width" ) {
+ this._resizeButton();
+ }
+ },
+
+ _appendTo: function() {
+ var element = this.options.appendTo;
+
+ if ( element ) {
+ element = element.jquery || element.nodeType ?
+ $( element ) :
+ this.document.find( element ).eq( 0 );
+ }
+
+ if ( !element || !element[ 0 ] ) {
+ element = this.element.closest( ".ui-front" );
+ }
+
+ if ( !element.length ) {
+ element = this.document[ 0 ].body;
+ }
+
+ return element;
+ },
+
+ _toggleAttr: function() {
+ this.button
+ .toggleClass( "ui-corner-top", this.isOpen )
+ .toggleClass( "ui-corner-all", !this.isOpen )
+ .attr( "aria-expanded", this.isOpen );
+ this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen );
+ this.menu.attr( "aria-hidden", !this.isOpen );
+ },
+
+ _resizeButton: function() {
+ var width = this.options.width;
+
+ if ( !width ) {
+ width = this.element.show().outerWidth();
+ this.element.hide();
+ }
+
+ this.button.outerWidth( width );
+ },
+
+ _resizeMenu: function() {
+ this.menu.outerWidth( Math.max(
+ this.button.outerWidth(),
+
+ // support: IE10
+ // IE10 wraps long text (possibly a rounding bug)
+ // so we add 1px to avoid the wrapping
+ this.menu.width( "" ).outerWidth() + 1
+ ) );
+ },
+
+ _getCreateOptions: function() {
+ return { disabled: this.element.prop( "disabled" ) };
+ },
+
+ _parseOptions: function( options ) {
+ var data = [];
+ options.each(function( index, item ) {
+ var option = $( item ),
+ optgroup = option.parent( "optgroup" );
+ data.push({
+ element: option,
+ index: index,
+ value: option.attr( "value" ),
+ label: option.text(),
+ optgroup: optgroup.attr( "label" ) || "",
+ disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" )
+ });
+ });
+ this.items = data;
+ },
+
+ _destroy: function() {
+ this.menuWrap.remove();
+ this.button.remove();
+ this.element.show();
+ this.element.removeUniqueId();
+ this.label.attr( "for", this.ids.element );
+ }
+});
+
+
+/*!
+ * jQuery UI Slider 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/slider/
+ */
+
+
+var slider = $.widget( "ui.slider", $.ui.mouse, {
+ version: "1.11.2",
+ widgetEventPrefix: "slide",
+
+ options: {
+ animate: false,
+ distance: 0,
+ max: 100,
+ min: 0,
+ orientation: "horizontal",
+ range: false,
+ step: 1,
+ value: 0,
+ values: null,
+
+ // callbacks
+ change: null,
+ slide: null,
+ start: null,
+ stop: null
+ },
+
+ // number of pages in a slider
+ // (how many times can you page up/down to go through the whole range)
+ numPages: 5,
+
+ _create: function() {
+ this._keySliding = false;
+ this._mouseSliding = false;
+ this._animateOff = true;
+ this._handleIndex = null;
+ this._detectOrientation();
+ this._mouseInit();
+ this._calculateNewMax();
+
+ this.element
+ .addClass( "ui-slider" +
+ " ui-slider-" + this.orientation +
+ " ui-widget" +
+ " ui-widget-content" +
+ " ui-corner-all");
+
+ this._refresh();
+ this._setOption( "disabled", this.options.disabled );
+
+ this._animateOff = false;
+ },
+
+ _refresh: function() {
+ this._createRange();
+ this._createHandles();
+ this._setupEvents();
+ this._refreshValue();
+ },
+
+ _createHandles: function() {
+ var i, handleCount,
+ options = this.options,
+ existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
+ handle = "<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>",
+ handles = [];
+
+ handleCount = ( options.values && options.values.length ) || 1;
+
+ if ( existingHandles.length > handleCount ) {
+ existingHandles.slice( handleCount ).remove();
+ existingHandles = existingHandles.slice( 0, handleCount );
+ }
+
+ for ( i = existingHandles.length; i < handleCount; i++ ) {
+ handles.push( handle );
+ }
+
+ this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );
+
+ this.handle = this.handles.eq( 0 );
+
+ this.handles.each(function( i ) {
+ $( this ).data( "ui-slider-handle-index", i );
+ });
+ },
+
+ _createRange: function() {
+ var options = this.options,
+ classes = "";
+
+ if ( options.range ) {
+ if ( options.range === true ) {
+ if ( !options.values ) {
+ options.values = [ this._valueMin(), this._valueMin() ];
+ } else if ( options.values.length && options.values.length !== 2 ) {
+ options.values = [ options.values[0], options.values[0] ];
+ } else if ( $.isArray( options.values ) ) {
+ options.values = options.values.slice(0);
+ }
+ }
+
+ if ( !this.range || !this.range.length ) {
+ this.range = $( "<div></div>" )
+ .appendTo( this.element );
+
+ classes = "ui-slider-range" +
+ // note: this isn't the most fittingly semantic framework class for this element,
+ // but worked best visually with a variety of themes
+ " ui-widget-header ui-corner-all";
+ } else {
+ this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
+ // Handle range switching from true to min/max
+ .css({
+ "left": "",
+ "bottom": ""
+ });
+ }
+
+ this.range.addClass( classes +
+ ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
+ } else {
+ if ( this.range ) {
+ this.range.remove();
+ }
+ this.range = null;
+ }
+ },
+
+ _setupEvents: function() {
+ this._off( this.handles );
+ this._on( this.handles, this._handleEvents );
+ this._hoverable( this.handles );
+ this._focusable( this.handles );
+ },
+
+ _destroy: function() {
+ this.handles.remove();
+ if ( this.range ) {
+ this.range.remove();
+ }
+
+ this.element
+ .removeClass( "ui-slider" +
+ " ui-slider-horizontal" +
+ " ui-slider-vertical" +
+ " ui-widget" +
+ " ui-widget-content" +
+ " ui-corner-all" );
+
+ this._mouseDestroy();
+ },
+
+ _mouseCapture: function( event ) {
+ var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
+ that = this,
+ o = this.options;
+
+ if ( o.disabled ) {
+ return false;
+ }
+
+ this.elementSize = {
+ width: this.element.outerWidth(),
+ height: this.element.outerHeight()
+ };
+ this.elementOffset = this.element.offset();
+
+ position = { x: event.pageX, y: event.pageY };
+ normValue = this._normValueFromMouse( position );
+ distance = this._valueMax() - this._valueMin() + 1;
+ this.handles.each(function( i ) {
+ var thisDistance = Math.abs( normValue - that.values(i) );
+ if (( distance > thisDistance ) ||
+ ( distance === thisDistance &&
+ (i === that._lastChangedValue || that.values(i) === o.min ))) {
+ distance = thisDistance;
+ closestHandle = $( this );
+ index = i;
+ }
+ });
+
+ allowed = this._start( event, index );
+ if ( allowed === false ) {
+ return false;
+ }
+ this._mouseSliding = true;
+
+ this._handleIndex = index;
+
+ closestHandle
+ .addClass( "ui-state-active" )
+ .focus();
+
+ offset = closestHandle.offset();
+ mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
+ this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
+ left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
+ top: event.pageY - offset.top -
+ ( closestHandle.height() / 2 ) -
+ ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
+ ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
+ ( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
+ };
+
+ if ( !this.handles.hasClass( "ui-state-hover" ) ) {
+ this._slide( event, index, normValue );
+ }
+ this._animateOff = true;
+ return true;
+ },
+
+ _mouseStart: function() {
+ return true;
+ },
+
+ _mouseDrag: function( event ) {
+ var position = { x: event.pageX, y: event.pageY },
+ normValue = this._normValueFromMouse( position );
+
+ this._slide( event, this._handleIndex, normValue );
+
+ return false;
+ },
+
+ _mouseStop: function( event ) {
+ this.handles.removeClass( "ui-state-active" );
+ this._mouseSliding = false;
+
+ this._stop( event, this._handleIndex );
+ this._change( event, this._handleIndex );
+
+ this._handleIndex = null;
+ this._clickOffset = null;
+ this._animateOff = false;
+
+ return false;
+ },
+
+ _detectOrientation: function() {
+ this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
+ },
+
+ _normValueFromMouse: function( position ) {
+ var pixelTotal,
+ pixelMouse,
+ percentMouse,
+ valueTotal,
+ valueMouse;
+
+ if ( this.orientation === "horizontal" ) {
+ pixelTotal = this.elementSize.width;
+ pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
+ } else {
+ pixelTotal = this.elementSize.height;
+ pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
+ }
+
+ percentMouse = ( pixelMouse / pixelTotal );
+ if ( percentMouse > 1 ) {
+ percentMouse = 1;
+ }
+ if ( percentMouse < 0 ) {
+ percentMouse = 0;
+ }
+ if ( this.orientation === "vertical" ) {
+ percentMouse = 1 - percentMouse;
+ }
+
+ valueTotal = this._valueMax() - this._valueMin();
+ valueMouse = this._valueMin() + percentMouse * valueTotal;
+
+ return this._trimAlignValue( valueMouse );
+ },
+
+ _start: function( event, index ) {
+ var uiHash = {
+ handle: this.handles[ index ],
+ value: this.value()
+ };
+ if ( this.options.values && this.options.values.length ) {
+ uiHash.value = this.values( index );
+ uiHash.values = this.values();
+ }
+ return this._trigger( "start", event, uiHash );
+ },
+
+ _slide: function( event, index, newVal ) {
+ var otherVal,
+ newValues,
+ allowed;
+
+ if ( this.options.values && this.options.values.length ) {
+ otherVal = this.values( index ? 0 : 1 );
+
+ if ( ( this.options.values.length === 2 && this.options.range === true ) &&
+ ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
+ ) {
+ newVal = otherVal;
+ }
+
+ if ( newVal !== this.values( index ) ) {
+ newValues = this.values();
+ newValues[ index ] = newVal;
+ // A slide can be canceled by returning false from the slide callback
+ allowed = this._trigger( "slide", event, {
+ handle: this.handles[ index ],
+ value: newVal,
+ values: newValues
+ } );
+ otherVal = this.values( index ? 0 : 1 );
+ if ( allowed !== false ) {
+ this.values( index, newVal );
+ }
+ }
+ } else {
+ if ( newVal !== this.value() ) {
+ // A slide can be canceled by returning false from the slide callback
+ allowed = this._trigger( "slide", event, {
+ handle: this.handles[ index ],
+ value: newVal
+ } );
+ if ( allowed !== false ) {
+ this.value( newVal );
+ }
+ }
+ }
+ },
+
+ _stop: function( event, index ) {
+ var uiHash = {
+ handle: this.handles[ index ],
+ value: this.value()
+ };
+ if ( this.options.values && this.options.values.length ) {
+ uiHash.value = this.values( index );
+ uiHash.values = this.values();
+ }
+
+ this._trigger( "stop", event, uiHash );
+ },
+
+ _change: function( event, index ) {
+ if ( !this._keySliding && !this._mouseSliding ) {
+ var uiHash = {
+ handle: this.handles[ index ],
+ value: this.value()
+ };
+ if ( this.options.values && this.options.values.length ) {
+ uiHash.value = this.values( index );
+ uiHash.values = this.values();
+ }
+
+ //store the last changed value index for reference when handles overlap
+ this._lastChangedValue = index;
+
+ this._trigger( "change", event, uiHash );
+ }
+ },
+
+ value: function( newValue ) {
+ if ( arguments.length ) {
+ this.options.value = this._trimAlignValue( newValue );
+ this._refreshValue();
+ this._change( null, 0 );
+ return;
+ }
+
+ return this._value();
+ },
+
+ values: function( index, newValue ) {
+ var vals,
+ newValues,
+ i;
+
+ if ( arguments.length > 1 ) {
+ this.options.values[ index ] = this._trimAlignValue( newValue );
+ this._refreshValue();
+ this._change( null, index );
+ return;
+ }
+
+ if ( arguments.length ) {
+ if ( $.isArray( arguments[ 0 ] ) ) {
+ vals = this.options.values;
+ newValues = arguments[ 0 ];
+ for ( i = 0; i < vals.length; i += 1 ) {
+ vals[ i ] = this._trimAlignValue( newValues[ i ] );
+ this._change( null, i );
+ }
+ this._refreshValue();
+ } else {
+ if ( this.options.values && this.options.values.length ) {
+ return this._values( index );
+ } else {
+ return this.value();
+ }
+ }
+ } else {
+ return this._values();
+ }
+ },
+
+ _setOption: function( key, value ) {
+ var i,
+ valsLength = 0;
+
+ if ( key === "range" && this.options.range === true ) {
+ if ( value === "min" ) {
+ this.options.value = this._values( 0 );
+ this.options.values = null;
+ } else if ( value === "max" ) {
+ this.options.value = this._values( this.options.values.length - 1 );
+ this.options.values = null;
+ }
+ }
+
+ if ( $.isArray( this.options.values ) ) {
+ valsLength = this.options.values.length;
+ }
+
+ if ( key === "disabled" ) {
+ this.element.toggleClass( "ui-state-disabled", !!value );
+ }
+
+ this._super( key, value );
+
+ switch ( key ) {
+ case "orientation":
+ this._detectOrientation();
+ this.element
+ .removeClass( "ui-slider-horizontal ui-slider-vertical" )
+ .addClass( "ui-slider-" + this.orientation );
+ this._refreshValue();
+
+ // Reset positioning from previous orientation
+ this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
+ break;
+ case "value":
+ this._animateOff = true;
+ this._refreshValue();
+ this._change( null, 0 );
+ this._animateOff = false;
+ break;
+ case "values":
+ this._animateOff = true;
+ this._refreshValue();
+ for ( i = 0; i < valsLength; i += 1 ) {
+ this._change( null, i );
+ }
+ this._animateOff = false;
+ break;
+ case "step":
+ case "min":
+ case "max":
+ this._animateOff = true;
+ this._calculateNewMax();
+ this._refreshValue();
+ this._animateOff = false;
+ break;
+ case "range":
+ this._animateOff = true;
+ this._refresh();
+ this._animateOff = false;
+ break;
+ }
+ },
+
+ //internal value getter
+ // _value() returns value trimmed by min and max, aligned by step
+ _value: function() {
+ var val = this.options.value;
+ val = this._trimAlignValue( val );
+
+ return val;
+ },
+
+ //internal values getter
+ // _values() returns array of values trimmed by min and max, aligned by step
+ // _values( index ) returns single value trimmed by min and max, aligned by step
+ _values: function( index ) {
+ var val,
+ vals,
+ i;
+
+ if ( arguments.length ) {
+ val = this.options.values[ index ];
+ val = this._trimAlignValue( val );
+
+ return val;
+ } else if ( this.options.values && this.options.values.length ) {
+ // .slice() creates a copy of the array
+ // this copy gets trimmed by min and max and then returned
+ vals = this.options.values.slice();
+ for ( i = 0; i < vals.length; i += 1) {
+ vals[ i ] = this._trimAlignValue( vals[ i ] );
+ }
+
+ return vals;
+ } else {
+ return [];
+ }
+ },
+
+ // returns the step-aligned value that val is closest to, between (inclusive) min and max
+ _trimAlignValue: function( val ) {
+ if ( val <= this._valueMin() ) {
+ return this._valueMin();
+ }
+ if ( val >= this._valueMax() ) {
+ return this._valueMax();
+ }
+ var step = ( this.options.step > 0 ) ? this.options.step : 1,
+ valModStep = (val - this._valueMin()) % step,
+ alignValue = val - valModStep;
+
+ if ( Math.abs(valModStep) * 2 >= step ) {
+ alignValue += ( valModStep > 0 ) ? step : ( -step );
+ }
+
+ // Since JavaScript has problems with large floats, round
+ // the final value to 5 digits after the decimal point (see #4124)
+ return parseFloat( alignValue.toFixed(5) );
+ },
+
+ _calculateNewMax: function() {
+ var remainder = ( this.options.max - this._valueMin() ) % this.options.step;
+ this.max = this.options.max - remainder;
+ },
+
+ _valueMin: function() {
+ return this.options.min;
+ },
+
+ _valueMax: function() {
+ return this.max;
+ },
+
+ _refreshValue: function() {
+ var lastValPercent, valPercent, value, valueMin, valueMax,
+ oRange = this.options.range,
+ o = this.options,
+ that = this,
+ animate = ( !this._animateOff ) ? o.animate : false,
+ _set = {};
+
+ if ( this.options.values && this.options.values.length ) {
+ this.handles.each(function( i ) {
+ valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
+ _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
+ $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
+ if ( that.options.range === true ) {
+ if ( that.orientation === "horizontal" ) {
+ if ( i === 0 ) {
+ that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
+ }
+ if ( i === 1 ) {
+ that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
+ }
+ } else {
+ if ( i === 0 ) {
+ that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
+ }
+ if ( i === 1 ) {
+ that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
+ }
+ }
+ }
+ lastValPercent = valPercent;
+ });
+ } else {
+ value = this.value();
+ valueMin = this._valueMin();
+ valueMax = this._valueMax();
+ valPercent = ( valueMax !== valueMin ) ?
+ ( value - valueMin ) / ( valueMax - valueMin ) * 100 :
+ 0;
+ _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
+ this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
+
+ if ( oRange === "min" && this.orientation === "horizontal" ) {
+ this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
+ }
+ if ( oRange === "max" && this.orientation === "horizontal" ) {
+ this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
+ }
+ if ( oRange === "min" && this.orientation === "vertical" ) {
+ this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
+ }
+ if ( oRange === "max" && this.orientation === "vertical" ) {
+ this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
+ }
+ }
+ },
+
+ _handleEvents: {
+ keydown: function( event ) {
+ var allowed, curVal, newVal, step,
+ index = $( event.target ).data( "ui-slider-handle-index" );
+
+ switch ( event.keyCode ) {
+ case $.ui.keyCode.HOME:
+ case $.ui.keyCode.END:
+ case $.ui.keyCode.PAGE_UP:
+ case $.ui.keyCode.PAGE_DOWN:
+ case $.ui.keyCode.UP:
+ case $.ui.keyCode.RIGHT:
+ case $.ui.keyCode.DOWN:
+ case $.ui.keyCode.LEFT:
+ event.preventDefault();
+ if ( !this._keySliding ) {
+ this._keySliding = true;
+ $( event.target ).addClass( "ui-state-active" );
+ allowed = this._start( event, index );
+ if ( allowed === false ) {
+ return;
+ }
+ }
+ break;
+ }
+
+ step = this.options.step;
+ if ( this.options.values && this.options.values.length ) {
+ curVal = newVal = this.values( index );
+ } else {
+ curVal = newVal = this.value();
+ }
+
+ switch ( event.keyCode ) {
+ case $.ui.keyCode.HOME:
+ newVal = this._valueMin();
+ break;
+ case $.ui.keyCode.END:
+ newVal = this._valueMax();
+ break;
+ case $.ui.keyCode.PAGE_UP:
+ newVal = this._trimAlignValue(
+ curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
+ );
+ break;
+ case $.ui.keyCode.PAGE_DOWN:
+ newVal = this._trimAlignValue(
+ curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) );
+ break;
+ case $.ui.keyCode.UP:
+ case $.ui.keyCode.RIGHT:
+ if ( curVal === this._valueMax() ) {
+ return;
+ }
+ newVal = this._trimAlignValue( curVal + step );
+ break;
+ case $.ui.keyCode.DOWN:
+ case $.ui.keyCode.LEFT:
+ if ( curVal === this._valueMin() ) {
+ return;
+ }
+ newVal = this._trimAlignValue( curVal - step );
+ break;
+ }
+
+ this._slide( event, index, newVal );
+ },
+ keyup: function( event ) {
+ var index = $( event.target ).data( "ui-slider-handle-index" );
+
+ if ( this._keySliding ) {
+ this._keySliding = false;
+ this._stop( event, index );
+ this._change( event, index );
+ $( event.target ).removeClass( "ui-state-active" );
+ }
+ }
+ }
+});
+
+
+/*!
+ * jQuery UI Sortable 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/sortable/
+ */
+
+
+var sortable = $.widget("ui.sortable", $.ui.mouse, {
+ version: "1.11.2",
+ widgetEventPrefix: "sort",
+ ready: false,
+ options: {
+ appendTo: "parent",
+ axis: false,
+ connectWith: false,
+ containment: false,
+ cursor: "auto",
+ cursorAt: false,
+ dropOnEmpty: true,
+ forcePlaceholderSize: false,
+ forceHelperSize: false,
+ grid: false,
+ handle: false,
+ helper: "original",
+ items: "> *",
+ opacity: false,
+ placeholder: false,
+ revert: false,
+ scroll: true,
+ scrollSensitivity: 20,
+ scrollSpeed: 20,
+ scope: "default",
+ tolerance: "intersect",
+ zIndex: 1000,
+
+ // callbacks
+ activate: null,
+ beforeStop: null,
+ change: null,
+ deactivate: null,
+ out: null,
+ over: null,
+ receive: null,
+ remove: null,
+ sort: null,
+ start: null,
+ stop: null,
+ update: null
+ },
+
+ _isOverAxis: function( x, reference, size ) {
+ return ( x >= reference ) && ( x < ( reference + size ) );
+ },
+
+ _isFloating: function( item ) {
+ return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
+ },
+
+ _create: function() {
+
+ var o = this.options;
+ this.containerCache = {};
+ this.element.addClass("ui-sortable");
+
+ //Get the items
+ this.refresh();
+
+ //Let's determine if the items are being displayed horizontally
+ this.floating = this.items.length ? o.axis === "x" || this._isFloating(this.items[0].item) : false;
+
+ //Let's determine the parent's offset
+ this.offset = this.element.offset();
+
+ //Initialize mouse events for interaction
+ this._mouseInit();
+
+ this._setHandleClassName();
+
+ //We're ready to go
+ this.ready = true;
+
+ },
+
+ _setOption: function( key, value ) {
+ this._super( key, value );
+
+ if ( key === "handle" ) {
+ this._setHandleClassName();
+ }
+ },
+
+ _setHandleClassName: function() {
+ this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" );
+ $.each( this.items, function() {
+ ( this.instance.options.handle ?
+ this.item.find( this.instance.options.handle ) : this.item )
+ .addClass( "ui-sortable-handle" );
+ });
+ },
+
+ _destroy: function() {
+ this.element
+ .removeClass( "ui-sortable ui-sortable-disabled" )
+ .find( ".ui-sortable-handle" )
+ .removeClass( "ui-sortable-handle" );
+ this._mouseDestroy();
+
+ for ( var i = this.items.length - 1; i >= 0; i-- ) {
+ this.items[i].item.removeData(this.widgetName + "-item");
+ }
+
+ return this;
+ },
+
+ _mouseCapture: function(event, overrideHandle) {
+ var currentItem = null,
+ validHandle = false,
+ that = this;
+
+ if (this.reverting) {
+ return false;
+ }
+
+ if(this.options.disabled || this.options.type === "static") {
+ return false;
+ }
+
+ //We have to refresh the items data once first
+ this._refreshItems(event);
+
+ //Find out if the clicked node (or one of its parents) is a actual item in this.items
+ $(event.target).parents().each(function() {
+ if($.data(this, that.widgetName + "-item") === that) {
+ currentItem = $(this);
+ return false;
+ }
+ });
+ if($.data(event.target, that.widgetName + "-item") === that) {
+ currentItem = $(event.target);
+ }
+
+ if(!currentItem) {
+ return false;
+ }
+ if(this.options.handle && !overrideHandle) {
+ $(this.options.handle, currentItem).find("*").addBack().each(function() {
+ if(this === event.target) {
+ validHandle = true;
+ }
+ });
+ if(!validHandle) {
+ return false;
+ }
+ }
+
+ this.currentItem = currentItem;
+ this._removeCurrentsFromItems();
+ return true;
+
+ },
+
+ _mouseStart: function(event, overrideHandle, noActivation) {
+
+ var i, body,
+ o = this.options;
+
+ this.currentContainer = this;
+
+ //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
+ this.refreshPositions();
+
+ //Create and append the visible helper
+ this.helper = this._createHelper(event);
+
+ //Cache the helper size
+ this._cacheHelperProportions();
+
+ /*
+ * - Position generation -
+ * This block generates everything position related - it's the core of draggables.
+ */
+
+ //Cache the margins of the original element
+ this._cacheMargins();
+
+ //Get the next scrolling parent
+ this.scrollParent = this.helper.scrollParent();
+
+ //The element's absolute position on the page minus margins
+ this.offset = this.currentItem.offset();
+ this.offset = {
+ top: this.offset.top - this.margins.top,
+ left: this.offset.left - this.margins.left
+ };
+
+ $.extend(this.offset, {
+ click: { //Where the click happened, relative to the element
+ left: event.pageX - this.offset.left,
+ top: event.pageY - this.offset.top
+ },
+ parent: this._getParentOffset(),
+ relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
+ });
+
+ // Only after we got the offset, we can change the helper's position to absolute
+ // TODO: Still need to figure out a way to make relative sorting possible
+ this.helper.css("position", "absolute");
+ this.cssPosition = this.helper.css("position");
+
+ //Generate the original position
+ this.originalPosition = this._generatePosition(event);
+ this.originalPageX = event.pageX;
+ this.originalPageY = event.pageY;
+
+ //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
+ (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
+
+ //Cache the former DOM position
+ this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
+
+ //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
+ if(this.helper[0] !== this.currentItem[0]) {
+ this.currentItem.hide();
+ }
+
+ //Create the placeholder
+ this._createPlaceholder();
+
+ //Set a containment if given in the options
+ if(o.containment) {
+ this._setContainment();
+ }
+
+ if( o.cursor && o.cursor !== "auto" ) { // cursor option
+ body = this.document.find( "body" );
+
+ // support: IE
+ this.storedCursor = body.css( "cursor" );
+ body.css( "cursor", o.cursor );
+
+ this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
+ }
+
+ if(o.opacity) { // opacity option
+ if (this.helper.css("opacity")) {
+ this._storedOpacity = this.helper.css("opacity");
+ }
+ this.helper.css("opacity", o.opacity);
+ }
+
+ if(o.zIndex) { // zIndex option
+ if (this.helper.css("zIndex")) {
+ this._storedZIndex = this.helper.css("zIndex");
+ }
+ this.helper.css("zIndex", o.zIndex);
+ }
+
+ //Prepare scrolling
+ if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
+ this.overflowOffset = this.scrollParent.offset();
+ }
+
+ //Call callbacks
+ this._trigger("start", event, this._uiHash());
+
+ //Recache the helper size
+ if(!this._preserveHelperProportions) {
+ this._cacheHelperProportions();
+ }
+
+
+ //Post "activate" events to possible containers
+ if( !noActivation ) {
+ for ( i = this.containers.length - 1; i >= 0; i-- ) {
+ this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
+ }
+ }
+
+ //Prepare possible droppables
+ if($.ui.ddmanager) {
+ $.ui.ddmanager.current = this;
+ }
+
+ if ($.ui.ddmanager && !o.dropBehaviour) {
+ $.ui.ddmanager.prepareOffsets(this, event);
+ }
+
+ this.dragging = true;
+
+ this.helper.addClass("ui-sortable-helper");
+ this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
+ return true;
+
+ },
+
+ _mouseDrag: function(event) {
+ var i, item, itemElement, intersection,
+ o = this.options,
+ scrolled = false;
+
+ //Compute the helpers position
+ this.position = this._generatePosition(event);
+ this.positionAbs = this._convertPositionTo("absolute");
+
+ if (!this.lastPositionAbs) {
+ this.lastPositionAbs = this.positionAbs;
+ }
+
+ //Do scrolling
+ if(this.options.scroll) {
+ if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
+
+ if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
+ this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
+ } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
+ this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
+ }
+
+ if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
+ this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
+ } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
+ this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
+ }
+
+ } else {
+
+ if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
+ scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
+ } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
+ scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
+ }
+
+ if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
+ scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
+ } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
+ scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
+ }
+
+ }
+
+ if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
+ $.ui.ddmanager.prepareOffsets(this, event);
+ }
+ }
+
+ //Regenerate the absolute position used for position checks
+ this.positionAbs = this._convertPositionTo("absolute");
+
+ //Set the helper position
+ if(!this.options.axis || this.options.axis !== "y") {
+ this.helper[0].style.left = this.position.left+"px";
+ }
+ if(!this.options.axis || this.options.axis !== "x") {
+ this.helper[0].style.top = this.position.top+"px";
+ }
+
+ //Rearrange
+ for (i = this.items.length - 1; i >= 0; i--) {
+
+ //Cache variables and intersection, continue if no intersection
+ item = this.items[i];
+ itemElement = item.item[0];
+ intersection = this._intersectsWithPointer(item);
+ if (!intersection) {
+ continue;
+ }
+
+ // Only put the placeholder inside the current Container, skip all
+ // items from other containers. This works because when moving
+ // an item from one container to another the
+ // currentContainer is switched before the placeholder is moved.
+ //
+ // Without this, moving items in "sub-sortables" can cause
+ // the placeholder to jitter between the outer and inner container.
+ if (item.instance !== this.currentContainer) {
+ continue;
+ }
+
+ // cannot intersect with itself
+ // no useless actions that have been done before
+ // no action if the item moved is the parent of the item checked
+ if (itemElement !== this.currentItem[0] &&
+ this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
+ !$.contains(this.placeholder[0], itemElement) &&
+ (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
+ ) {
+
+ this.direction = intersection === 1 ? "down" : "up";
+
+ if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
+ this._rearrange(event, item);
+ } else {
+ break;
+ }
+
+ this._trigger("change", event, this._uiHash());
+ break;
+ }
+ }
+
+ //Post events to containers
+ this._contactContainers(event);
+
+ //Interconnect with droppables
+ if($.ui.ddmanager) {
+ $.ui.ddmanager.drag(this, event);
+ }
+
+ //Call callbacks
+ this._trigger("sort", event, this._uiHash());
+
+ this.lastPositionAbs = this.positionAbs;
+ return false;
+
+ },
+
+ _mouseStop: function(event, noPropagation) {
+
+ if(!event) {
+ return;
+ }
+
+ //If we are using droppables, inform the manager about the drop
+ if ($.ui.ddmanager && !this.options.dropBehaviour) {
+ $.ui.ddmanager.drop(this, event);
+ }
+
+ if(this.options.revert) {
+ var that = this,
+ cur = this.placeholder.offset(),
+ axis = this.options.axis,
+ animation = {};
+
+ if ( !axis || axis === "x" ) {
+ animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
+ }
+ if ( !axis || axis === "y" ) {
+ animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
+ }
+ this.reverting = true;
+ $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
+ that._clear(event);
+ });
+ } else {
+ this._clear(event, noPropagation);
+ }
+
+ return false;
+
+ },
+
+ cancel: function() {
+
+ if(this.dragging) {
+
+ this._mouseUp({ target: null });
+
+ if(this.options.helper === "original") {
+ this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
+ } else {
+ this.currentItem.show();
+ }
+
+ //Post deactivating events to containers
+ for (var i = this.containers.length - 1; i >= 0; i--){
+ this.containers[i]._trigger("deactivate", null, this._uiHash(this));
+ if(this.containers[i].containerCache.over) {
+ this.containers[i]._trigger("out", null, this._uiHash(this));
+ this.containers[i].containerCache.over = 0;
+ }
+ }
+
+ }
+
+ if (this.placeholder) {
+ //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
+ if(this.placeholder[0].parentNode) {
+ this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
+ }
+ if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
+ this.helper.remove();
+ }
+
+ $.extend(this, {
+ helper: null,
+ dragging: false,
+ reverting: false,
+ _noFinalSort: null
+ });
+
+ if(this.domPosition.prev) {
+ $(this.domPosition.prev).after(this.currentItem);
+ } else {
+ $(this.domPosition.parent).prepend(this.currentItem);
+ }
+ }
+
+ return this;
+
+ },
+
+ serialize: function(o) {
+
+ var items = this._getItemsAsjQuery(o && o.connected),
+ str = [];
+ o = o || {};
+
+ $(items).each(function() {
+ var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
+ if (res) {
+ str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
+ }
+ });
+
+ if(!str.length && o.key) {
+ str.push(o.key + "=");
+ }
+
+ return str.join("&");
+
+ },
+
+ toArray: function(o) {
+
+ var items = this._getItemsAsjQuery(o && o.connected),
+ ret = [];
+
+ o = o || {};
+
+ items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
+ return ret;
+
+ },
+
+ /* Be careful with the following core functions */
+ _intersectsWith: function(item) {
+
+ var x1 = this.positionAbs.left,
+ x2 = x1 + this.helperProportions.width,
+ y1 = this.positionAbs.top,
+ y2 = y1 + this.helperProportions.height,
+ l = item.left,
+ r = l + item.width,
+ t = item.top,
+ b = t + item.height,
+ dyClick = this.offset.click.top,
+ dxClick = this.offset.click.left,
+ isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
+ isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
+ isOverElement = isOverElementHeight && isOverElementWidth;
+
+ if ( this.options.tolerance === "pointer" ||
+ this.options.forcePointerForContainers ||
+ (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
+ ) {
+ return isOverElement;
+ } else {
+
+ return (l < x1 + (this.helperProportions.width / 2) && // Right Half
+ x2 - (this.helperProportions.width / 2) < r && // Left Half
+ t < y1 + (this.helperProportions.height / 2) && // Bottom Half
+ y2 - (this.helperProportions.height / 2) < b ); // Top Half
+
+ }
+ },
+
+ _intersectsWithPointer: function(item) {
+
+ var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
+ isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
+ isOverElement = isOverElementHeight && isOverElementWidth,
+ verticalDirection = this._getDragVerticalDirection(),
+ horizontalDirection = this._getDragHorizontalDirection();
+
+ if (!isOverElement) {
+ return false;
+ }
+
+ return this.floating ?
+ ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
+ : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
+
+ },
+
+ _intersectsWithSides: function(item) {
+
+ var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
+ isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
+ verticalDirection = this._getDragVerticalDirection(),
+ horizontalDirection = this._getDragHorizontalDirection();
+
+ if (this.floating && horizontalDirection) {
+ return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
+ } else {
+ return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
+ }
+
+ },
+
+ _getDragVerticalDirection: function() {
+ var delta = this.positionAbs.top - this.lastPositionAbs.top;
+ return delta !== 0 && (delta > 0 ? "down" : "up");
+ },
+
+ _getDragHorizontalDirection: function() {
+ var delta = this.positionAbs.left - this.lastPositionAbs.left;
+ return delta !== 0 && (delta > 0 ? "right" : "left");
+ },
+
+ refresh: function(event) {
+ this._refreshItems(event);
+ this._setHandleClassName();
+ this.refreshPositions();
+ return this;
+ },
+
+ _connectWith: function() {
+ var options = this.options;
+ return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
+ },
+
+ _getItemsAsjQuery: function(connected) {
+
+ var i, j, cur, inst,
+ items = [],
+ queries = [],
+ connectWith = this._connectWith();
+
+ if(connectWith && connected) {
+ for (i = connectWith.length - 1; i >= 0; i--){
+ cur = $(connectWith[i]);
+ for ( j = cur.length - 1; j >= 0; j--){
+ inst = $.data(cur[j], this.widgetFullName);
+ if(inst && inst !== this && !inst.options.disabled) {
+ queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
+ }
+ }
+ }
+ }
+
+ queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
+
+ function addItems() {
+ items.push( this );
+ }
+ for (i = queries.length - 1; i >= 0; i--){
+ queries[i][0].each( addItems );
+ }
+
+ return $(items);
+
+ },
+
+ _removeCurrentsFromItems: function() {
+
+ var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
+
+ this.items = $.grep(this.items, function (item) {
+ for (var j=0; j < list.length; j++) {
+ if(list[j] === item.item[0]) {
+ return false;
+ }
+ }
+ return true;
+ });
+
+ },
+
+ _refreshItems: function(event) {
+
+ this.items = [];
+ this.containers = [this];
+
+ var i, j, cur, inst, targetData, _queries, item, queriesLength,
+ items = this.items,
+ queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
+ connectWith = this._connectWith();
+
+ if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
+ for (i = connectWith.length - 1; i >= 0; i--){
+ cur = $(connectWith[i]);
+ for (j = cur.length - 1; j >= 0; j--){
+ inst = $.data(cur[j], this.widgetFullName);
+ if(inst && inst !== this && !inst.options.disabled) {
+ queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
+ this.containers.push(inst);
+ }
+ }
+ }
+ }
+
+ for (i = queries.length - 1; i >= 0; i--) {
+ targetData = queries[i][1];
+ _queries = queries[i][0];
+
+ for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
+ item = $(_queries[j]);
+
+ item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
+
+ items.push({
+ item: item,
+ instance: targetData,
+ width: 0, height: 0,
+ left: 0, top: 0
+ });
+ }
+ }
+
+ },
+
+ refreshPositions: function(fast) {
+
+ //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
+ if(this.offsetParent && this.helper) {
+ this.offset.parent = this._getParentOffset();
+ }
+
+ var i, item, t, p;
+
+ for (i = this.items.length - 1; i >= 0; i--){
+ item = this.items[i];
+
+ //We ignore calculating positions of all connected containers when we're not over them
+ if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
+ continue;
+ }
+
+ t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
+
+ if (!fast) {
+ item.width = t.outerWidth();
+ item.height = t.outerHeight();
+ }
+
+ p = t.offset();
+ item.left = p.left;
+ item.top = p.top;
+ }
+
+ if(this.options.custom && this.options.custom.refreshContainers) {
+ this.options.custom.refreshContainers.call(this);
+ } else {
+ for (i = this.containers.length - 1; i >= 0; i--){
+ p = this.containers[i].element.offset();
+ this.containers[i].containerCache.left = p.left;
+ this.containers[i].containerCache.top = p.top;
+ this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
+ this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
+ }
+ }
+
+ return this;
+ },
+
+ _createPlaceholder: function(that) {
+ that = that || this;
+ var className,
+ o = that.options;
+
+ if(!o.placeholder || o.placeholder.constructor === String) {
+ className = o.placeholder;
+ o.placeholder = {
+ element: function() {
+
+ var nodeName = that.currentItem[0].nodeName.toLowerCase(),
+ element = $( "<" + nodeName + ">", that.document[0] )
+ .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
+ .removeClass("ui-sortable-helper");
+
+ if ( nodeName === "tr" ) {
+ that.currentItem.children().each(function() {
+ $( "<td> </td>", that.document[0] )
+ .attr( "colspan", $( this ).attr( "colspan" ) || 1 )
+ .appendTo( element );
+ });
+ } else if ( nodeName === "img" ) {
+ element.attr( "src", that.currentItem.attr( "src" ) );
+ }
+
+ if ( !className ) {
+ element.css( "visibility", "hidden" );
+ }
+
+ return element;
+ },
+ update: function(container, p) {
+
+ // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
+ // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
+ if(className && !o.forcePlaceholderSize) {
+ return;
+ }
+
+ //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
+ if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
+ if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
+ }
+ };
+ }
+
+ //Create the placeholder
+ that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
+
+ //Append it after the actual current item
+ that.currentItem.after(that.placeholder);
+
+ //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
+ o.placeholder.update(that, that.placeholder);
+
+ },
+
+ _contactContainers: function(event) {
+ var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis,
+ innermostContainer = null,
+ innermostIndex = null;
+
+ // get innermost container that intersects with item
+ for (i = this.containers.length - 1; i >= 0; i--) {
+
+ // never consider a container that's located within the item itself
+ if($.contains(this.currentItem[0], this.containers[i].element[0])) {
+ continue;
+ }
+
+ if(this._intersectsWith(this.containers[i].containerCache)) {
+
+ // if we've already found a container and it's more "inner" than this, then continue
+ if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
+ continue;
+ }
+
+ innermostContainer = this.containers[i];
+ innermostIndex = i;
+
+ } else {
+ // container doesn't intersect. trigger "out" event if necessary
+ if(this.containers[i].containerCache.over) {
+ this.containers[i]._trigger("out", event, this._uiHash(this));
+ this.containers[i].containerCache.over = 0;
+ }
+ }
+
+ }
+
+ // if no intersecting containers found, return
+ if(!innermostContainer) {
+ return;
+ }
+
+ // move the item into the container if it's not there already
+ if(this.containers.length === 1) {
+ if (!this.containers[innermostIndex].containerCache.over) {
+ this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
+ this.containers[innermostIndex].containerCache.over = 1;
+ }
+ } else {
+
+ //When entering a new container, we will find the item with the least distance and append our item near it
+ dist = 10000;
+ itemWithLeastDistance = null;
+ floating = innermostContainer.floating || this._isFloating(this.currentItem);
+ posProperty = floating ? "left" : "top";
+ sizeProperty = floating ? "width" : "height";
+ axis = floating ? "clientX" : "clientY";
+
+ for (j = this.items.length - 1; j >= 0; j--) {
+ if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
+ continue;
+ }
+ if(this.items[j].item[0] === this.currentItem[0]) {
+ continue;
+ }
+
+ cur = this.items[j].item.offset()[posProperty];
+ nearBottom = false;
+ if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
+ nearBottom = true;
+ }
+
+ if ( Math.abs( event[ axis ] - cur ) < dist ) {
+ dist = Math.abs( event[ axis ] - cur );
+ itemWithLeastDistance = this.items[ j ];
+ this.direction = nearBottom ? "up": "down";
+ }
+ }
+
+ //Check if dropOnEmpty is enabled
+ if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
+ return;
+ }
+
+ if(this.currentContainer === this.containers[innermostIndex]) {
+ if ( !this.currentContainer.containerCache.over ) {
+ this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
+ this.currentContainer.containerCache.over = 1;
+ }
+ return;
+ }
+
+ itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
+ this._trigger("change", event, this._uiHash());
+ this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
+ this.currentContainer = this.containers[innermostIndex];
+
+ //Update the placeholder
+ this.options.placeholder.update(this.currentContainer, this.placeholder);
+
+ this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
+ this.containers[innermostIndex].containerCache.over = 1;
+ }
+
+
+ },
+
+ _createHelper: function(event) {
+
+ var o = this.options,
+ helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
+
+ //Add the helper to the DOM if that didn't happen already
+ if(!helper.parents("body").length) {
+ $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
+ }
+
+ if(helper[0] === this.currentItem[0]) {
+ this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
+ }
+
+ if(!helper[0].style.width || o.forceHelperSize) {
+ helper.width(this.currentItem.width());
+ }
+ if(!helper[0].style.height || o.forceHelperSize) {
+ helper.height(this.currentItem.height());
+ }
+
+ return helper;
+
+ },
+
+ _adjustOffsetFromHelper: function(obj) {
+ if (typeof obj === "string") {
+ obj = obj.split(" ");
+ }
+ if ($.isArray(obj)) {
+ obj = {left: +obj[0], top: +obj[1] || 0};
+ }
+ if ("left" in obj) {
+ this.offset.click.left = obj.left + this.margins.left;
+ }
+ if ("right" in obj) {
+ this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
+ }
+ if ("top" in obj) {
+ this.offset.click.top = obj.top + this.margins.top;
+ }
+ if ("bottom" in obj) {
+ this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
+ }
+ },
+
+ _getParentOffset: function() {
+
+
+ //Get the offsetParent and cache its position
+ this.offsetParent = this.helper.offsetParent();
+ var po = this.offsetParent.offset();
+
+ // This is a special case where we need to modify a offset calculated on start, since the following happened:
+ // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
+ // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
+ // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
+ if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
+ po.left += this.scrollParent.scrollLeft();
+ po.top += this.scrollParent.scrollTop();
+ }
+
+ // This needs to be actually done for all browsers, since pageX/pageY includes this information
+ // with an ugly IE fix
+ if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
+ po = { top: 0, left: 0 };
+ }
+
+ return {
+ top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
+ left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
+ };
+
+ },
+
+ _getRelativeOffset: function() {
+
+ if(this.cssPosition === "relative") {
+ var p = this.currentItem.position();
+ return {
+ top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
+ left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
+ };
+ } else {
+ return { top: 0, left: 0 };
+ }
+
+ },
+
+ _cacheMargins: function() {
+ this.margins = {
+ left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
+ top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
+ };
+ },
+
+ _cacheHelperProportions: function() {
+ this.helperProportions = {
+ width: this.helper.outerWidth(),
+ height: this.helper.outerHeight()
+ };
+ },
+
+ _setContainment: function() {
+
+ var ce, co, over,
+ o = this.options;
+ if(o.containment === "parent") {
+ o.containment = this.helper[0].parentNode;
+ }
+ if(o.containment === "document" || o.containment === "window") {
+ this.containment = [
+ 0 - this.offset.relative.left - this.offset.parent.left,
+ 0 - this.offset.relative.top - this.offset.parent.top,
+ $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
+ ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
+ ];
+ }
+
+ if(!(/^(document|window|parent)$/).test(o.containment)) {
+ ce = $(o.containment)[0];
+ co = $(o.containment).offset();
+ over = ($(ce).css("overflow") !== "hidden");
+
+ this.containment = [
+ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
+ co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
+ co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
+ co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
+ ];
+ }
+
+ },
+
+ _convertPositionTo: function(d, pos) {
+
+ if(!pos) {
+ pos = this.position;
+ }
+ var mod = d === "absolute" ? 1 : -1,
+ scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
+ scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+ return {
+ top: (
+ pos.top + // The absolute mouse position
+ this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
+ ),
+ left: (
+ pos.left + // The absolute mouse position
+ this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
+ )
+ };
+
+ },
+
+ _generatePosition: function(event) {
+
+ var top, left,
+ o = this.options,
+ pageX = event.pageX,
+ pageY = event.pageY,
+ scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+ // This is another very weird special case that only happens for relative elements:
+ // 1. If the css position is relative
+ // 2. and the scroll parent is the document or similar to the offset parent
+ // we have to refresh the relative offset during the scroll so there are no jumps
+ if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
+ this.offset.relative = this._getRelativeOffset();
+ }
+
+ /*
+ * - Position constraining -
+ * Constrain the position to a mix of grid, containment.
+ */
+
+ if(this.originalPosition) { //If we are not dragging yet, we won't check for options
+
+ if(this.containment) {
+ if(event.pageX - this.offset.click.left < this.containment[0]) {
+ pageX = this.containment[0] + this.offset.click.left;
+ }
+ if(event.pageY - this.offset.click.top < this.containment[1]) {
+ pageY = this.containment[1] + this.offset.click.top;
+ }
+ if(event.pageX - this.offset.click.left > this.containment[2]) {
+ pageX = this.containment[2] + this.offset.click.left;
+ }
+ if(event.pageY - this.offset.click.top > this.containment[3]) {
+ pageY = this.containment[3] + this.offset.click.top;
+ }
+ }
+
+ if(o.grid) {
+ top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
+ pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
+
+ left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
+ pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
+ }
+
+ }
+
+ return {
+ top: (
+ pageY - // The absolute mouse position
+ this.offset.click.top - // Click offset (relative to the element)
+ this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
+ ),
+ left: (
+ pageX - // The absolute mouse position
+ this.offset.click.left - // Click offset (relative to the element)
+ this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
+ )
+ };
+
+ },
+
+ _rearrange: function(event, i, a, hardRefresh) {
+
+ a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
+
+ //Various things done here to improve the performance:
+ // 1. we create a setTimeout, that calls refreshPositions
+ // 2. on the instance, we have a counter variable, that get's higher after every append
+ // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
+ // 4. this lets only the last addition to the timeout stack through
+ this.counter = this.counter ? ++this.counter : 1;
+ var counter = this.counter;
+
+ this._delay(function() {
+ if(counter === this.counter) {
+ this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
+ }
+ });
+
+ },
+
+ _clear: function(event, noPropagation) {
+
+ this.reverting = false;
+ // We delay all events that have to be triggered to after the point where the placeholder has been removed and
+ // everything else normalized again
+ var i,
+ delayedTriggers = [];
+
+ // We first have to update the dom position of the actual currentItem
+ // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
+ if(!this._noFinalSort && this.currentItem.parent().length) {
+ this.placeholder.before(this.currentItem);
+ }
+ this._noFinalSort = null;
+
+ if(this.helper[0] === this.currentItem[0]) {
+ for(i in this._storedCSS) {
+ if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
+ this._storedCSS[i] = "";
+ }
+ }
+ this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
+ } else {
+ this.currentItem.show();
+ }
+
+ if(this.fromOutside && !noPropagation) {
+ delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
+ }
+ if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
+ delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
+ }
+
+ // Check if the items Container has Changed and trigger appropriate
+ // events.
+ if (this !== this.currentContainer) {
+ if(!noPropagation) {
+ delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
+ delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
+ delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
+ }
+ }
+
+
+ //Post events to containers
+ function delayEvent( type, instance, container ) {
+ return function( event ) {
+ container._trigger( type, event, instance._uiHash( instance ) );
+ };
+ }
+ for (i = this.containers.length - 1; i >= 0; i--){
+ if (!noPropagation) {
+ delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
+ }
+ if(this.containers[i].containerCache.over) {
+ delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
+ this.containers[i].containerCache.over = 0;
+ }
+ }
+
+ //Do what was originally in plugins
+ if ( this.storedCursor ) {
+ this.document.find( "body" ).css( "cursor", this.storedCursor );
+ this.storedStylesheet.remove();
+ }
+ if(this._storedOpacity) {
+ this.helper.css("opacity", this._storedOpacity);
+ }
+ if(this._storedZIndex) {
+ this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
+ }
+
+ this.dragging = false;
+
+ if(!noPropagation) {
+ this._trigger("beforeStop", event, this._uiHash());
+ }
+
+ //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
+ this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
+
+ if ( !this.cancelHelperRemoval ) {
+ if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
+ this.helper.remove();
+ }
+ this.helper = null;
+ }
+
+ if(!noPropagation) {
+ for (i=0; i < delayedTriggers.length; i++) {
+ delayedTriggers[i].call(this, event);
+ } //Trigger all delayed events
+ this._trigger("stop", event, this._uiHash());
+ }
+
+ this.fromOutside = false;
+ return !this.cancelHelperRemoval;
+
+ },
+
+ _trigger: function() {
+ if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
+ this.cancel();
+ }
+ },
+
+ _uiHash: function(_inst) {
+ var inst = _inst || this;
+ return {
+ helper: inst.helper,
+ placeholder: inst.placeholder || $([]),
+ position: inst.position,
+ originalPosition: inst.originalPosition,
+ offset: inst.positionAbs,
+ item: inst.currentItem,
+ sender: _inst ? _inst.element : null
+ };
+ }
+
+});
+
+
+/*!
+ * jQuery UI Spinner 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/spinner/
+ */
+
+
+function spinner_modifier( fn ) {
+ return function() {
+ var previous = this.element.val();
+ fn.apply( this, arguments );
+ this._refresh();
+ if ( previous !== this.element.val() ) {
+ this._trigger( "change" );
+ }
+ };
+}
+
+var spinner = $.widget( "ui.spinner", {
+ version: "1.11.2",
+ defaultElement: "<input>",
+ widgetEventPrefix: "spin",
+ options: {
+ culture: null,
+ icons: {
+ down: "ui-icon-triangle-1-s",
+ up: "ui-icon-triangle-1-n"
+ },
+ incremental: true,
+ max: null,
+ min: null,
+ numberFormat: null,
+ page: 10,
+ step: 1,
+
+ change: null,
+ spin: null,
+ start: null,
+ stop: null
+ },
+
+ _create: function() {
+ // handle string values that need to be parsed
+ this._setOption( "max", this.options.max );
+ this._setOption( "min", this.options.min );
+ this._setOption( "step", this.options.step );
+
+ // Only format if there is a value, prevents the field from being marked
+ // as invalid in Firefox, see #9573.
+ if ( this.value() !== "" ) {
+ // Format the value, but don't constrain.
+ this._value( this.element.val(), true );
+ }
+
+ this._draw();
+ this._on( this._events );
+ this._refresh();
+
+ // turning off autocomplete prevents the browser from remembering the
+ // value when navigating through history, so we re-enable autocomplete
+ // if the page is unloaded before the widget is destroyed. #7790
+ this._on( this.window, {
+ beforeunload: function() {
+ this.element.removeAttr( "autocomplete" );
+ }
+ });
+ },
+
+ _getCreateOptions: function() {
+ var options = {},
+ element = this.element;
+
+ $.each( [ "min", "max", "step" ], function( i, option ) {
+ var value = element.attr( option );
+ if ( value !== undefined && value.length ) {
+ options[ option ] = value;
+ }
+ });
+
+ return options;
+ },
+
+ _events: {
+ keydown: function( event ) {
+ if ( this._start( event ) && this._keydown( event ) ) {
+ event.preventDefault();
+ }
+ },
+ keyup: "_stop",
+ focus: function() {
+ this.previous = this.element.val();
+ },
+ blur: function( event ) {
+ if ( this.cancelBlur ) {
+ delete this.cancelBlur;
+ return;
+ }
+
+ this._stop();
+ this._refresh();
+ if ( this.previous !== this.element.val() ) {
+ this._trigger( "change", event );
+ }
+ },
+ mousewheel: function( event, delta ) {
+ if ( !delta ) {
+ return;
+ }
+ if ( !this.spinning && !this._start( event ) ) {
+ return false;
+ }
+
+ this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
+ clearTimeout( this.mousewheelTimer );
+ this.mousewheelTimer = this._delay(function() {
+ if ( this.spinning ) {
+ this._stop( event );
+ }
+ }, 100 );
+ event.preventDefault();
+ },
+ "mousedown .ui-spinner-button": function( event ) {
+ var previous;
+
+ // We never want the buttons to have focus; whenever the user is
+ // interacting with the spinner, the focus should be on the input.
+ // If the input is focused then this.previous is properly set from
+ // when the input first received focus. If the input is not focused
+ // then we need to set this.previous based on the value before spinning.
+ previous = this.element[0] === this.document[0].activeElement ?
+ this.previous : this.element.val();
+ function checkFocus() {
+ var isActive = this.element[0] === this.document[0].activeElement;
+ if ( !isActive ) {
+ this.element.focus();
+ this.previous = previous;
+ // support: IE
+ // IE sets focus asynchronously, so we need to check if focus
+ // moved off of the input because the user clicked on the button.
+ this._delay(function() {
+ this.previous = previous;
+ });
+ }
+ }
+
+ // ensure focus is on (or stays on) the text field
+ event.preventDefault();
+ checkFocus.call( this );
+
+ // support: IE
+ // IE doesn't prevent moving focus even with event.preventDefault()
+ // so we set a flag to know when we should ignore the blur event
+ // and check (again) if focus moved off of the input.
+ this.cancelBlur = true;
+ this._delay(function() {
+ delete this.cancelBlur;
+ checkFocus.call( this );
+ });
+
+ if ( this._start( event ) === false ) {
+ return;
+ }
+
+ this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
+ },
+ "mouseup .ui-spinner-button": "_stop",
+ "mouseenter .ui-spinner-button": function( event ) {
+ // button will add ui-state-active if mouse was down while mouseleave and kept down
+ if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
+ return;
+ }
+
+ if ( this._start( event ) === false ) {
+ return false;
+ }
+ this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
+ },
+ // TODO: do we really want to consider this a stop?
+ // shouldn't we just stop the repeater and wait until mouseup before
+ // we trigger the stop event?
+ "mouseleave .ui-spinner-button": "_stop"
+ },
+
+ _draw: function() {
+ var uiSpinner = this.uiSpinner = this.element
+ .addClass( "ui-spinner-input" )
+ .attr( "autocomplete", "off" )
+ .wrap( this._uiSpinnerHtml() )
+ .parent()
+ // add buttons
+ .append( this._buttonHtml() );
+
+ this.element.attr( "role", "spinbutton" );
+
+ // button bindings
+ this.buttons = uiSpinner.find( ".ui-spinner-button" )
+ .attr( "tabIndex", -1 )
+ .button()
+ .removeClass( "ui-corner-all" );
+
+ // IE 6 doesn't understand height: 50% for the buttons
+ // unless the wrapper has an explicit height
+ if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
+ uiSpinner.height() > 0 ) {
+ uiSpinner.height( uiSpinner.height() );
+ }
+
+ // disable spinner if element was already disabled
+ if ( this.options.disabled ) {
+ this.disable();
+ }
+ },
+
+ _keydown: function( event ) {
+ var options = this.options,
+ keyCode = $.ui.keyCode;
+
+ switch ( event.keyCode ) {
+ case keyCode.UP:
+ this._repeat( null, 1, event );
+ return true;
+ case keyCode.DOWN:
+ this._repeat( null, -1, event );
+ return true;
+ case keyCode.PAGE_UP:
+ this._repeat( null, options.page, event );
+ return true;
+ case keyCode.PAGE_DOWN:
+ this._repeat( null, -options.page, event );
+ return true;
+ }
+
+ return false;
+ },
+
+ _uiSpinnerHtml: function() {
+ return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
+ },
+
+ _buttonHtml: function() {
+ return "" +
+ "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
+ "<span class='ui-icon " + this.options.icons.up + "'>▲</span>" +
+ "</a>" +
+ "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
+ "<span class='ui-icon " + this.options.icons.down + "'>▼</span>" +
+ "</a>";
+ },
+
+ _start: function( event ) {
+ if ( !this.spinning && this._trigger( "start", event ) === false ) {
+ return false;
+ }
+
+ if ( !this.counter ) {
+ this.counter = 1;
+ }
+ this.spinning = true;
+ return true;
+ },
+
+ _repeat: function( i, steps, event ) {
+ i = i || 500;
+
+ clearTimeout( this.timer );
+ this.timer = this._delay(function() {
+ this._repeat( 40, steps, event );
+ }, i );
+
+ this._spin( steps * this.options.step, event );
+ },
+
+ _spin: function( step, event ) {
+ var value = this.value() || 0;
+
+ if ( !this.counter ) {
+ this.counter = 1;
+ }
+
+ value = this._adjustValue( value + step * this._increment( this.counter ) );
+
+ if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
+ this._value( value );
+ this.counter++;
+ }
+ },
+
+ _increment: function( i ) {
+ var incremental = this.options.incremental;
+
+ if ( incremental ) {
+ return $.isFunction( incremental ) ?
+ incremental( i ) :
+ Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 );
+ }
+
+ return 1;
+ },
+
+ _precision: function() {
+ var precision = this._precisionOf( this.options.step );
+ if ( this.options.min !== null ) {
+ precision = Math.max( precision, this._precisionOf( this.options.min ) );
+ }
+ return precision;
+ },
+
+ _precisionOf: function( num ) {
+ var str = num.toString(),
+ decimal = str.indexOf( "." );
+ return decimal === -1 ? 0 : str.length - decimal - 1;
+ },
+
+ _adjustValue: function( value ) {
+ var base, aboveMin,
+ options = this.options;
+
+ // make sure we're at a valid step
+ // - find out where we are relative to the base (min or 0)
+ base = options.min !== null ? options.min : 0;
+ aboveMin = value - base;
+ // - round to the nearest step
+ aboveMin = Math.round(aboveMin / options.step) * options.step;
+ // - rounding is based on 0, so adjust back to our base
+ value = base + aboveMin;
+
+ // fix precision from bad JS floating point math
+ value = parseFloat( value.toFixed( this._precision() ) );
+
+ // clamp the value
+ if ( options.max !== null && value > options.max) {
+ return options.max;
+ }
+ if ( options.min !== null && value < options.min ) {
+ return options.min;
+ }
+
+ return value;
+ },
+
+ _stop: function( event ) {
+ if ( !this.spinning ) {
+ return;
+ }
+
+ clearTimeout( this.timer );
+ clearTimeout( this.mousewheelTimer );
+ this.counter = 0;
+ this.spinning = false;
+ this._trigger( "stop", event );
+ },
+
+ _setOption: function( key, value ) {
+ if ( key === "culture" || key === "numberFormat" ) {
+ var prevValue = this._parse( this.element.val() );
+ this.options[ key ] = value;
+ this.element.val( this._format( prevValue ) );
+ return;
+ }
+
+ if ( key === "max" || key === "min" || key === "step" ) {
+ if ( typeof value === "string" ) {
+ value = this._parse( value );
+ }
+ }
+ if ( key === "icons" ) {
+ this.buttons.first().find( ".ui-icon" )
+ .removeClass( this.options.icons.up )
+ .addClass( value.up );
+ this.buttons.last().find( ".ui-icon" )
+ .removeClass( this.options.icons.down )
+ .addClass( value.down );
+ }
+
+ this._super( key, value );
+
+ if ( key === "disabled" ) {
+ this.widget().toggleClass( "ui-state-disabled", !!value );
+ this.element.prop( "disabled", !!value );
+ this.buttons.button( value ? "disable" : "enable" );
+ }
+ },
+
+ _setOptions: spinner_modifier(function( options ) {
+ this._super( options );
+ }),
+
+ _parse: function( val ) {
+ if ( typeof val === "string" && val !== "" ) {
+ val = window.Globalize && this.options.numberFormat ?
+ Globalize.parseFloat( val, 10, this.options.culture ) : +val;
+ }
+ return val === "" || isNaN( val ) ? null : val;
+ },
+
+ _format: function( value ) {
+ if ( value === "" ) {
+ return "";
+ }
+ return window.Globalize && this.options.numberFormat ?
+ Globalize.format( value, this.options.numberFormat, this.options.culture ) :
+ value;
+ },
+
+ _refresh: function() {
+ this.element.attr({
+ "aria-valuemin": this.options.min,
+ "aria-valuemax": this.options.max,
+ // TODO: what should we do with values that can't be parsed?
+ "aria-valuenow": this._parse( this.element.val() )
+ });
+ },
+
+ isValid: function() {
+ var value = this.value();
+
+ // null is invalid
+ if ( value === null ) {
+ return false;
+ }
+
+ // if value gets adjusted, it's invalid
+ return value === this._adjustValue( value );
+ },
+
+ // update the value without triggering change
+ _value: function( value, allowAny ) {
+ var parsed;
+ if ( value !== "" ) {
+ parsed = this._parse( value );
+ if ( parsed !== null ) {
+ if ( !allowAny ) {
+ parsed = this._adjustValue( parsed );
+ }
+ value = this._format( parsed );
+ }
+ }
+ this.element.val( value );
+ this._refresh();
+ },
+
+ _destroy: function() {
+ this.element
+ .removeClass( "ui-spinner-input" )
+ .prop( "disabled", false )
+ .removeAttr( "autocomplete" )
+ .removeAttr( "role" )
+ .removeAttr( "aria-valuemin" )
+ .removeAttr( "aria-valuemax" )
+ .removeAttr( "aria-valuenow" );
+ this.uiSpinner.replaceWith( this.element );
+ },
+
+ stepUp: spinner_modifier(function( steps ) {
+ this._stepUp( steps );
+ }),
+ _stepUp: function( steps ) {
+ if ( this._start() ) {
+ this._spin( (steps || 1) * this.options.step );
+ this._stop();
+ }
+ },
+
+ stepDown: spinner_modifier(function( steps ) {
+ this._stepDown( steps );
+ }),
+ _stepDown: function( steps ) {
+ if ( this._start() ) {
+ this._spin( (steps || 1) * -this.options.step );
+ this._stop();
+ }
+ },
+
+ pageUp: spinner_modifier(function( pages ) {
+ this._stepUp( (pages || 1) * this.options.page );
+ }),
+
+ pageDown: spinner_modifier(function( pages ) {
+ this._stepDown( (pages || 1) * this.options.page );
+ }),
+
+ value: function( newVal ) {
+ if ( !arguments.length ) {
+ return this._parse( this.element.val() );
+ }
+ spinner_modifier( this._value ).call( this, newVal );
+ },
+
+ widget: function() {
+ return this.uiSpinner;
+ }
+});
+
+
+/*!
+ * jQuery UI Tabs 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/tabs/
+ */
+
+
+var tabs = $.widget( "ui.tabs", {
+ version: "1.11.2",
+ delay: 300,
+ options: {
+ active: null,
+ collapsible: false,
+ event: "click",
+ heightStyle: "content",
+ hide: null,
+ show: null,
+
+ // callbacks
+ activate: null,
+ beforeActivate: null,
+ beforeLoad: null,
+ load: null
+ },
+
+ _isLocal: (function() {
+ var rhash = /#.*$/;
+
+ return function( anchor ) {
+ var anchorUrl, locationUrl;
+
+ // support: IE7
+ // IE7 doesn't normalize the href property when set via script (#9317)
+ anchor = anchor.cloneNode( false );
+
+ anchorUrl = anchor.href.replace( rhash, "" );
+ locationUrl = location.href.replace( rhash, "" );
+
+ // decoding may throw an error if the URL isn't UTF-8 (#9518)
+ try {
+ anchorUrl = decodeURIComponent( anchorUrl );
+ } catch ( error ) {}
+ try {
+ locationUrl = decodeURIComponent( locationUrl );
+ } catch ( error ) {}
+
+ return anchor.hash.length > 1 && anchorUrl === locationUrl;
+ };
+ })(),
+
+ _create: function() {
+ var that = this,
+ options = this.options;
+
+ this.running = false;
+
+ this.element
+ .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
+ .toggleClass( "ui-tabs-collapsible", options.collapsible );
+
+ this._processTabs();
+ options.active = this._initialActive();
+
+ // Take disabling tabs via class attribute from HTML
+ // into account and update option properly.
+ if ( $.isArray( options.disabled ) ) {
+ options.disabled = $.unique( options.disabled.concat(
+ $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
+ return that.tabs.index( li );
+ })
+ ) ).sort();
+ }
+
+ // check for length avoids error when initializing empty list
+ if ( this.options.active !== false && this.anchors.length ) {
+ this.active = this._findActive( options.active );
+ } else {
+ this.active = $();
+ }
+
+ this._refresh();
+
+ if ( this.active.length ) {
+ this.load( options.active );
+ }
+ },
+
+ _initialActive: function() {
+ var active = this.options.active,
+ collapsible = this.options.collapsible,
+ locationHash = location.hash.substring( 1 );
+
+ if ( active === null ) {
+ // check the fragment identifier in the URL
+ if ( locationHash ) {
+ this.tabs.each(function( i, tab ) {
+ if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
+ active = i;
+ return false;
+ }
+ });
+ }
+
+ // check for a tab marked active via a class
+ if ( active === null ) {
+ active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
+ }
+
+ // no active tab, set to false
+ if ( active === null || active === -1 ) {
+ active = this.tabs.length ? 0 : false;
+ }
+ }
+
+ // handle numbers: negative, out of range
+ if ( active !== false ) {
+ active = this.tabs.index( this.tabs.eq( active ) );
+ if ( active === -1 ) {
+ active = collapsible ? false : 0;
+ }
+ }
+
+ // don't allow collapsible: false and active: false
+ if ( !collapsible && active === false && this.anchors.length ) {
+ active = 0;
+ }
+
+ return active;
+ },
+
+ _getCreateEventData: function() {
+ return {
+ tab: this.active,
+ panel: !this.active.length ? $() : this._getPanelForTab( this.active )
+ };
+ },
+
+ _tabKeydown: function( event ) {
+ var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
+ selectedIndex = this.tabs.index( focusedTab ),
+ goingForward = true;
+
+ if ( this._handlePageNav( event ) ) {
+ return;
+ }
+
+ switch ( event.keyCode ) {
+ case $.ui.keyCode.RIGHT:
+ case $.ui.keyCode.DOWN:
+ selectedIndex++;
+ break;
+ case $.ui.keyCode.UP:
+ case $.ui.keyCode.LEFT:
+ goingForward = false;
+ selectedIndex--;
+ break;
+ case $.ui.keyCode.END:
+ selectedIndex = this.anchors.length - 1;
+ break;
+ case $.ui.keyCode.HOME:
+ selectedIndex = 0;
+ break;
+ case $.ui.keyCode.SPACE:
+ // Activate only, no collapsing
+ event.preventDefault();
+ clearTimeout( this.activating );
+ this._activate( selectedIndex );
+ return;
+ case $.ui.keyCode.ENTER:
+ // Toggle (cancel delayed activation, allow collapsing)
+ event.preventDefault();
+ clearTimeout( this.activating );
+ // Determine if we should collapse or activate
+ this._activate( selectedIndex === this.options.active ? false : selectedIndex );
+ return;
+ default:
+ return;
+ }
+
+ // Focus the appropriate tab, based on which key was pressed
+ event.preventDefault();
+ clearTimeout( this.activating );
+ selectedIndex = this._focusNextTab( selectedIndex, goingForward );
+
+ // Navigating with control key will prevent automatic activation
+ if ( !event.ctrlKey ) {
+ // Update aria-selected immediately so that AT think the tab is already selected.
+ // Otherwise AT may confuse the user by stating that they need to activate the tab,
+ // but the tab will already be activated by the time the announcement finishes.
+ focusedTab.attr( "aria-selected", "false" );
+ this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );
+
+ this.activating = this._delay(function() {
+ this.option( "active", selectedIndex );
+ }, this.delay );
+ }
+ },
+
+ _panelKeydown: function( event ) {
+ if ( this._handlePageNav( event ) ) {
+ return;
+ }
+
+ // Ctrl+up moves focus to the current tab
+ if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
+ event.preventDefault();
+ this.active.focus();
+ }
+ },
+
+ // Alt+page up/down moves focus to the previous/next tab (and activates)
+ _handlePageNav: function( event ) {
+ if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
+ this._activate( this._focusNextTab( this.options.active - 1, false ) );
+ return true;
+ }
+ if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
+ this._activate( this._focusNextTab( this.options.active + 1, true ) );
+ return true;
+ }
+ },
+
+ _findNextTab: function( index, goingForward ) {
+ var lastTabIndex = this.tabs.length - 1;
+
+ function constrain() {
+ if ( index > lastTabIndex ) {
+ index = 0;
+ }
+ if ( index < 0 ) {
+ index = lastTabIndex;
+ }
+ return index;
+ }
+
+ while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
+ index = goingForward ? index + 1 : index - 1;
+ }
+
+ return index;
+ },
+
+ _focusNextTab: function( index, goingForward ) {
+ index = this._findNextTab( index, goingForward );
+ this.tabs.eq( index ).focus();
+ return index;
+ },
+
+ _setOption: function( key, value ) {
+ if ( key === "active" ) {
+ // _activate() will handle invalid values and update this.options
+ this._activate( value );
+ return;
+ }
+
+ if ( key === "disabled" ) {
+ // don't use the widget factory's disabled handling
+ this._setupDisabled( value );
+ return;
+ }
+
+ this._super( key, value);
+
+ if ( key === "collapsible" ) {
+ this.element.toggleClass( "ui-tabs-collapsible", value );
+ // Setting collapsible: false while collapsed; open first panel
+ if ( !value && this.options.active === false ) {
+ this._activate( 0 );
+ }
+ }
+
+ if ( key === "event" ) {
+ this._setupEvents( value );
+ }
+
+ if ( key === "heightStyle" ) {
+ this._setupHeightStyle( value );
+ }
+ },
+
+ _sanitizeSelector: function( hash ) {
+ return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
+ },
+
+ refresh: function() {
+ var options = this.options,
+ lis = this.tablist.children( ":has(a[href])" );
+
+ // get disabled tabs from class attribute from HTML
+ // this will get converted to a boolean if needed in _refresh()
+ options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
+ return lis.index( tab );
+ });
+
+ this._processTabs();
+
+ // was collapsed or no tabs
+ if ( options.active === false || !this.anchors.length ) {
+ options.active = false;
+ this.active = $();
+ // was active, but active tab is gone
+ } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
+ // all remaining tabs are disabled
+ if ( this.tabs.length === options.disabled.length ) {
+ options.active = false;
+ this.active = $();
+ // activate previous tab
+ } else {
+ this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
+ }
+ // was active, active tab still exists
+ } else {
+ // make sure active index is correct
+ options.active = this.tabs.index( this.active );
+ }
+
+ this._refresh();
+ },
+
+ _refresh: function() {
+ this._setupDisabled( this.options.disabled );
+ this._setupEvents( this.options.event );
+ this._setupHeightStyle( this.options.heightStyle );
+
+ this.tabs.not( this.active ).attr({
+ "aria-selected": "false",
+ "aria-expanded": "false",
+ tabIndex: -1
+ });
+ this.panels.not( this._getPanelForTab( this.active ) )
+ .hide()
+ .attr({
+ "aria-hidden": "true"
+ });
+
+ // Make sure one tab is in the tab order
+ if ( !this.active.length ) {
+ this.tabs.eq( 0 ).attr( "tabIndex", 0 );
+ } else {
+ this.active
+ .addClass( "ui-tabs-active ui-state-active" )
+ .attr({
+ "aria-selected": "true",
+ "aria-expanded": "true",
+ tabIndex: 0
+ });
+ this._getPanelForTab( this.active )
+ .show()
+ .attr({
+ "aria-hidden": "false"
+ });
+ }
+ },
+
+ _processTabs: function() {
+ var that = this,
+ prevTabs = this.tabs,
+ prevAnchors = this.anchors,
+ prevPanels = this.panels;
+
+ this.tablist = this._getList()
+ .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
+ .attr( "role", "tablist" )
+
+ // Prevent users from focusing disabled tabs via click
+ .delegate( "> li", "mousedown" + this.eventNamespace, function( event ) {
+ if ( $( this ).is( ".ui-state-disabled" ) ) {
+ event.preventDefault();
+ }
+ })
+
+ // support: IE <9
+ // Preventing the default action in mousedown doesn't prevent IE
+ // from focusing the element, so if the anchor gets focused, blur.
+ // We don't have to worry about focusing the previously focused
+ // element since clicking on a non-focusable element should focus
+ // the body anyway.
+ .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
+ if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
+ this.blur();
+ }
+ });
+
+ this.tabs = this.tablist.find( "> li:has(a[href])" )
+ .addClass( "ui-state-default ui-corner-top" )
+ .attr({
+ role: "tab",
+ tabIndex: -1
+ });
+
+ this.anchors = this.tabs.map(function() {
+ return $( "a", this )[ 0 ];
+ })
+ .addClass( "ui-tabs-anchor" )
+ .attr({
+ role: "presentation",
+ tabIndex: -1
+ });
+
+ this.panels = $();
+
+ this.anchors.each(function( i, anchor ) {
+ var selector, panel, panelId,
+ anchorId = $( anchor ).uniqueId().attr( "id" ),
+ tab = $( anchor ).closest( "li" ),
+ originalAriaControls = tab.attr( "aria-controls" );
+
+ // inline tab
+ if ( that._isLocal( anchor ) ) {
+ selector = anchor.hash;
+ panelId = selector.substring( 1 );
+ panel = that.element.find( that._sanitizeSelector( selector ) );
+ // remote tab
+ } else {
+ // If the tab doesn't already have aria-controls,
+ // generate an id by using a throw-away element
+ panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id;
+ selector = "#" + panelId;
+ panel = that.element.find( selector );
+ if ( !panel.length ) {
+ panel = that._createPanel( panelId );
+ panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
+ }
+ panel.attr( "aria-live", "polite" );
+ }
+
+ if ( panel.length) {
+ that.panels = that.panels.add( panel );
+ }
+ if ( originalAriaControls ) {
+ tab.data( "ui-tabs-aria-controls", originalAriaControls );
+ }
+ tab.attr({
+ "aria-controls": panelId,
+ "aria-labelledby": anchorId
+ });
+ panel.attr( "aria-labelledby", anchorId );
+ });
+
+ this.panels
+ .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
+ .attr( "role", "tabpanel" );
+
+ // Avoid memory leaks (#10056)
+ if ( prevTabs ) {
+ this._off( prevTabs.not( this.tabs ) );
+ this._off( prevAnchors.not( this.anchors ) );
+ this._off( prevPanels.not( this.panels ) );
+ }
+ },
+
+ // allow overriding how to find the list for rare usage scenarios (#7715)
+ _getList: function() {
+ return this.tablist || this.element.find( "ol,ul" ).eq( 0 );
+ },
+
+ _createPanel: function( id ) {
+ return $( "<div>" )
+ .attr( "id", id )
+ .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
+ .data( "ui-tabs-destroy", true );
+ },
+
+ _setupDisabled: function( disabled ) {
+ if ( $.isArray( disabled ) ) {
+ if ( !disabled.length ) {
+ disabled = false;
+ } else if ( disabled.length === this.anchors.length ) {
+ disabled = true;
+ }
+ }
+
+ // disable tabs
+ for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
+ if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
+ $( li )
+ .addClass( "ui-state-disabled" )
+ .attr( "aria-disabled", "true" );
+ } else {
+ $( li )
+ .removeClass( "ui-state-disabled" )
+ .removeAttr( "aria-disabled" );
+ }
+ }
+
+ this.options.disabled = disabled;
+ },
+
+ _setupEvents: function( event ) {
+ var events = {};
+ if ( event ) {
+ $.each( event.split(" "), function( index, eventName ) {
+ events[ eventName ] = "_eventHandler";
+ });
+ }
+
+ this._off( this.anchors.add( this.tabs ).add( this.panels ) );
+ // Always prevent the default action, even when disabled
+ this._on( true, this.anchors, {
+ click: function( event ) {
+ event.preventDefault();
+ }
+ });
+ this._on( this.anchors, events );
+ this._on( this.tabs, { keydown: "_tabKeydown" } );
+ this._on( this.panels, { keydown: "_panelKeydown" } );
+
+ this._focusable( this.tabs );
+ this._hoverable( this.tabs );
+ },
+
+ _setupHeightStyle: function( heightStyle ) {
+ var maxHeight,
+ parent = this.element.parent();
+
+ if ( heightStyle === "fill" ) {
+ maxHeight = parent.height();
+ maxHeight -= this.element.outerHeight() - this.element.height();
+
+ this.element.siblings( ":visible" ).each(function() {
+ var elem = $( this ),
+ position = elem.css( "position" );
+
+ if ( position === "absolute" || position === "fixed" ) {
+ return;
+ }
+ maxHeight -= elem.outerHeight( true );
+ });
+
+ this.element.children().not( this.panels ).each(function() {
+ maxHeight -= $( this ).outerHeight( true );
+ });
+
+ this.panels.each(function() {
+ $( this ).height( Math.max( 0, maxHeight -
+ $( this ).innerHeight() + $( this ).height() ) );
+ })
+ .css( "overflow", "auto" );
+ } else if ( heightStyle === "auto" ) {
+ maxHeight = 0;
+ this.panels.each(function() {
+ maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
+ }).height( maxHeight );
+ }
+ },
+
+ _eventHandler: function( event ) {
+ var options = this.options,
+ active = this.active,
+ anchor = $( event.currentTarget ),
+ tab = anchor.closest( "li" ),
+ clickedIsActive = tab[ 0 ] === active[ 0 ],
+ collapsing = clickedIsActive && options.collapsible,
+ toShow = collapsing ? $() : this._getPanelForTab( tab ),
+ toHide = !active.length ? $() : this._getPanelForTab( active ),
+ eventData = {
+ oldTab: active,
+ oldPanel: toHide,
+ newTab: collapsing ? $() : tab,
+ newPanel: toShow
+ };
+
+ event.preventDefault();
+
+ if ( tab.hasClass( "ui-state-disabled" ) ||
+ // tab is already loading
+ tab.hasClass( "ui-tabs-loading" ) ||
+ // can't switch durning an animation
+ this.running ||
+ // click on active header, but not collapsible
+ ( clickedIsActive && !options.collapsible ) ||
+ // allow canceling activation
+ ( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
+ return;
+ }
+
+ options.active = collapsing ? false : this.tabs.index( tab );
+
+ this.active = clickedIsActive ? $() : tab;
+ if ( this.xhr ) {
+ this.xhr.abort();
+ }
+
+ if ( !toHide.length && !toShow.length ) {
+ $.error( "jQuery UI Tabs: Mismatching fragment identifier." );
+ }
+
+ if ( toShow.length ) {
+ this.load( this.tabs.index( tab ), event );
+ }
+ this._toggle( event, eventData );
+ },
+
+ // handles show/hide for selecting tabs
+ _toggle: function( event, eventData ) {
+ var that = this,
+ toShow = eventData.newPanel,
+ toHide = eventData.oldPanel;
+
+ this.running = true;
+
+ function complete() {
+ that.running = false;
+ that._trigger( "activate", event, eventData );
+ }
+
+ function show() {
+ eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
+
+ if ( toShow.length && that.options.show ) {
+ that._show( toShow, that.options.show, complete );
+ } else {
+ toShow.show();
+ complete();
+ }
+ }
+
+ // start out by hiding, then showing, then completing
+ if ( toHide.length && this.options.hide ) {
+ this._hide( toHide, this.options.hide, function() {
+ eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
+ show();
+ });
+ } else {
+ eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
+ toHide.hide();
+ show();
+ }
+
+ toHide.attr( "aria-hidden", "true" );
+ eventData.oldTab.attr({
+ "aria-selected": "false",
+ "aria-expanded": "false"
+ });
+ // If we're switching tabs, remove the old tab from the tab order.
+ // If we're opening from collapsed state, remove the previous tab from the tab order.
+ // If we're collapsing, then keep the collapsing tab in the tab order.
+ if ( toShow.length && toHide.length ) {
+ eventData.oldTab.attr( "tabIndex", -1 );
+ } else if ( toShow.length ) {
+ this.tabs.filter(function() {
+ return $( this ).attr( "tabIndex" ) === 0;
+ })
+ .attr( "tabIndex", -1 );
+ }
+
+ toShow.attr( "aria-hidden", "false" );
+ eventData.newTab.attr({
+ "aria-selected": "true",
+ "aria-expanded": "true",
+ tabIndex: 0
+ });
+ },
+
+ _activate: function( index ) {
+ var anchor,
+ active = this._findActive( index );
+
+ // trying to activate the already active panel
+ if ( active[ 0 ] === this.active[ 0 ] ) {
+ return;
+ }
+
+ // trying to collapse, simulate a click on the current active header
+ if ( !active.length ) {
+ active = this.active;
+ }
+
+ anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
+ this._eventHandler({
+ target: anchor,
+ currentTarget: anchor,
+ preventDefault: $.noop
+ });
+ },
+
+ _findActive: function( index ) {
+ return index === false ? $() : this.tabs.eq( index );
+ },
+
+ _getIndex: function( index ) {
+ // meta-function to give users option to provide a href string instead of a numerical index.
+ if ( typeof index === "string" ) {
+ index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
+ }
+
+ return index;
+ },
+
+ _destroy: function() {
+ if ( this.xhr ) {
+ this.xhr.abort();
+ }
+
+ this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );
+
+ this.tablist
+ .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
+ .removeAttr( "role" );
+
+ this.anchors
+ .removeClass( "ui-tabs-anchor" )
+ .removeAttr( "role" )
+ .removeAttr( "tabIndex" )
+ .removeUniqueId();
+
+ this.tablist.unbind( this.eventNamespace );
+
+ this.tabs.add( this.panels ).each(function() {
+ if ( $.data( this, "ui-tabs-destroy" ) ) {
+ $( this ).remove();
+ } else {
+ $( this )
+ .removeClass( "ui-state-default ui-state-active ui-state-disabled " +
+ "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
+ .removeAttr( "tabIndex" )
+ .removeAttr( "aria-live" )
+ .removeAttr( "aria-busy" )
+ .removeAttr( "aria-selected" )
+ .removeAttr( "aria-labelledby" )
+ .removeAttr( "aria-hidden" )
+ .removeAttr( "aria-expanded" )
+ .removeAttr( "role" );
+ }
+ });
+
+ this.tabs.each(function() {
+ var li = $( this ),
+ prev = li.data( "ui-tabs-aria-controls" );
+ if ( prev ) {
+ li
+ .attr( "aria-controls", prev )
+ .removeData( "ui-tabs-aria-controls" );
+ } else {
+ li.removeAttr( "aria-controls" );
+ }
+ });
+
+ this.panels.show();
+
+ if ( this.options.heightStyle !== "content" ) {
+ this.panels.css( "height", "" );
+ }
+ },
+
+ enable: function( index ) {
+ var disabled = this.options.disabled;
+ if ( disabled === false ) {
+ return;
+ }
+
+ if ( index === undefined ) {
+ disabled = false;
+ } else {
+ index = this._getIndex( index );
+ if ( $.isArray( disabled ) ) {
+ disabled = $.map( disabled, function( num ) {
+ return num !== index ? num : null;
+ });
+ } else {
+ disabled = $.map( this.tabs, function( li, num ) {
+ return num !== index ? num : null;
+ });
+ }
+ }
+ this._setupDisabled( disabled );
+ },
+
+ disable: function( index ) {
+ var disabled = this.options.disabled;
+ if ( disabled === true ) {
+ return;
+ }
+
+ if ( index === undefined ) {
+ disabled = true;
+ } else {
+ index = this._getIndex( index );
+ if ( $.inArray( index, disabled ) !== -1 ) {
+ return;
+ }
+ if ( $.isArray( disabled ) ) {
+ disabled = $.merge( [ index ], disabled ).sort();
+ } else {
+ disabled = [ index ];
+ }
+ }
+ this._setupDisabled( disabled );
+ },
+
+ load: function( index, event ) {
+ index = this._getIndex( index );
+ var that = this,
+ tab = this.tabs.eq( index ),
+ anchor = tab.find( ".ui-tabs-anchor" ),
+ panel = this._getPanelForTab( tab ),
+ eventData = {
+ tab: tab,
+ panel: panel
+ };
+
+ // not remote
+ if ( this._isLocal( anchor[ 0 ] ) ) {
+ return;
+ }
+
+ this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );
+
+ // support: jQuery <1.8
+ // jQuery <1.8 returns false if the request is canceled in beforeSend,
+ // but as of 1.8, $.ajax() always returns a jqXHR object.
+ if ( this.xhr && this.xhr.statusText !== "canceled" ) {
+ tab.addClass( "ui-tabs-loading" );
+ panel.attr( "aria-busy", "true" );
+
+ this.xhr
+ .success(function( response ) {
+ // support: jQuery <1.8
+ // http://bugs.jquery.com/ticket/11778
+ setTimeout(function() {
+ panel.html( response );
+ that._trigger( "load", event, eventData );
+ }, 1 );
+ })
+ .complete(function( jqXHR, status ) {
+ // support: jQuery <1.8
+ // http://bugs.jquery.com/ticket/11778
+ setTimeout(function() {
+ if ( status === "abort" ) {
+ that.panels.stop( false, true );
+ }
+
+ tab.removeClass( "ui-tabs-loading" );
+ panel.removeAttr( "aria-busy" );
+
+ if ( jqXHR === that.xhr ) {
+ delete that.xhr;
+ }
+ }, 1 );
+ });
+ }
+ },
+
+ _ajaxSettings: function( anchor, event, eventData ) {
+ var that = this;
+ return {
+ url: anchor.attr( "href" ),
+ beforeSend: function( jqXHR, settings ) {
+ return that._trigger( "beforeLoad", event,
+ $.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) );
+ }
+ };
+ },
+
+ _getPanelForTab: function( tab ) {
+ var id = $( tab ).attr( "aria-controls" );
+ return this.element.find( this._sanitizeSelector( "#" + id ) );
+ }
+});
+
+
+/*!
+ * jQuery UI Tooltip 1.11.2
+ * http://jqueryui.com
+ *
+ * Copyright 2014 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/tooltip/
+ */
+
+
+var tooltip = $.widget( "ui.tooltip", {
+ version: "1.11.2",
+ options: {
+ content: function() {
+ // support: IE<9, Opera in jQuery <1.7
+ // .text() can't accept undefined, so coerce to a string
+ var title = $( this ).attr( "title" ) || "";
+ // Escape title, since we're going from an attribute to raw HTML
+ return $( "<a>" ).text( title ).html();
+ },
+ hide: true,
+ // Disabled elements have inconsistent behavior across browsers (#8661)
+ items: "[title]:not([disabled])",
+ position: {
+ my: "left top+15",
+ at: "left bottom",
+ collision: "flipfit flip"
+ },
+ show: true,
+ tooltipClass: null,
+ track: false,
+
+ // callbacks
+ close: null,
+ open: null
+ },
+
+ _addDescribedBy: function( elem, id ) {
+ var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
+ describedby.push( id );
+ elem
+ .data( "ui-tooltip-id", id )
+ .attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
+ },
+
+ _removeDescribedBy: function( elem ) {
+ var id = elem.data( "ui-tooltip-id" ),
+ describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
+ index = $.inArray( id, describedby );
+
+ if ( index !== -1 ) {
+ describedby.splice( index, 1 );
+ }
+
+ elem.removeData( "ui-tooltip-id" );
+ describedby = $.trim( describedby.join( " " ) );
+ if ( describedby ) {
+ elem.attr( "aria-describedby", describedby );
+ } else {
+ elem.removeAttr( "aria-describedby" );
+ }
+ },
+
+ _create: function() {
+ this._on({
+ mouseover: "open",
+ focusin: "open"
+ });
+
+ // IDs of generated tooltips, needed for destroy
+ this.tooltips = {};
+
+ // IDs of parent tooltips where we removed the title attribute
+ this.parents = {};
+
+ if ( this.options.disabled ) {
+ this._disable();
+ }
+
+ // Append the aria-live region so tooltips announce correctly
+ this.liveRegion = $( "<div>" )
+ .attr({
+ role: "log",
+ "aria-live": "assertive",
+ "aria-relevant": "additions"
+ })
+ .addClass( "ui-helper-hidden-accessible" )
+ .appendTo( this.document[ 0 ].body );
+ },
+
+ _setOption: function( key, value ) {
+ var that = this;
+
+ if ( key === "disabled" ) {
+ this[ value ? "_disable" : "_enable" ]();
+ this.options[ key ] = value;
+ // disable element style changes
+ return;
+ }
+
+ this._super( key, value );
+
+ if ( key === "content" ) {
+ $.each( this.tooltips, function( id, tooltipData ) {
+ that._updateContent( tooltipData.element );
+ });
+ }
+ },
+
+ _disable: function() {
+ var that = this;
+
+ // close open tooltips
+ $.each( this.tooltips, function( id, tooltipData ) {
+ var event = $.Event( "blur" );
+ event.target = event.currentTarget = tooltipData.element[ 0 ];
+ that.close( event, true );
+ });
+
+ // remove title attributes to prevent native tooltips
+ this.element.find( this.options.items ).addBack().each(function() {
+ var element = $( this );
+ if ( element.is( "[title]" ) ) {
+ element
+ .data( "ui-tooltip-title", element.attr( "title" ) )
+ .removeAttr( "title" );
+ }
+ });
+ },
+
+ _enable: function() {
+ // restore title attributes
+ this.element.find( this.options.items ).addBack().each(function() {
+ var element = $( this );
+ if ( element.data( "ui-tooltip-title" ) ) {
+ element.attr( "title", element.data( "ui-tooltip-title" ) );
+ }
+ });
+ },
+
+ open: function( event ) {
+ var that = this,
+ target = $( event ? event.target : this.element )
+ // we need closest here due to mouseover bubbling,
+ // but always pointing at the same event target
+ .closest( this.options.items );
+
+ // No element to show a tooltip for or the tooltip is already open
+ if ( !target.length || target.data( "ui-tooltip-id" ) ) {
+ return;
+ }
+
+ if ( target.attr( "title" ) ) {
+ target.data( "ui-tooltip-title", target.attr( "title" ) );
+ }
+
+ target.data( "ui-tooltip-open", true );
+
+ // kill parent tooltips, custom or native, for hover
+ if ( event && event.type === "mouseover" ) {
+ target.parents().each(function() {
+ var parent = $( this ),
+ blurEvent;
+ if ( parent.data( "ui-tooltip-open" ) ) {
+ blurEvent = $.Event( "blur" );
+ blurEvent.target = blurEvent.currentTarget = this;
+ that.close( blurEvent, true );
+ }
+ if ( parent.attr( "title" ) ) {
+ parent.uniqueId();
+ that.parents[ this.id ] = {
+ element: this,
+ title: parent.attr( "title" )
+ };
+ parent.attr( "title", "" );
+ }
+ });
+ }
+
+ this._updateContent( target, event );
+ },
+
+ _updateContent: function( target, event ) {
+ var content,
+ contentOption = this.options.content,
+ that = this,
+ eventType = event ? event.type : null;
+
+ if ( typeof contentOption === "string" ) {
+ return this._open( event, target, contentOption );
+ }
+
+ content = contentOption.call( target[0], function( response ) {
+ // ignore async response if tooltip was closed already
+ if ( !target.data( "ui-tooltip-open" ) ) {
+ return;
+ }
+ // IE may instantly serve a cached response for ajax requests
+ // delay this call to _open so the other call to _open runs first
+ that._delay(function() {
+ // jQuery creates a special event for focusin when it doesn't
+ // exist natively. To improve performance, the native event
+ // object is reused and the type is changed. Therefore, we can't
+ // rely on the type being correct after the event finished
+ // bubbling, so we set it back to the previous value. (#8740)
+ if ( event ) {
+ event.type = eventType;
+ }
+ this._open( event, target, response );
+ });
+ });
+ if ( content ) {
+ this._open( event, target, content );
+ }
+ },
+
+ _open: function( event, target, content ) {
+ var tooltipData, tooltip, events, delayedShow, a11yContent,
+ positionOption = $.extend( {}, this.options.position );
+
+ if ( !content ) {
+ return;
+ }
+
+ // Content can be updated multiple times. If the tooltip already
+ // exists, then just update the content and bail.
+ tooltipData = this._find( target );
+ if ( tooltipData ) {
+ tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
+ return;
+ }
+
+ // if we have a title, clear it to prevent the native tooltip
+ // we have to check first to avoid defining a title if none exists
+ // (we don't want to cause an element to start matching [title])
+ //
+ // We use removeAttr only for key events, to allow IE to export the correct
+ // accessible attributes. For mouse events, set to empty string to avoid
+ // native tooltip showing up (happens only when removing inside mouseover).
+ if ( target.is( "[title]" ) ) {
+ if ( event && event.type === "mouseover" ) {
+ target.attr( "title", "" );
+ } else {
+ target.removeAttr( "title" );
+ }
+ }
+
+ tooltipData = this._tooltip( target );
+ tooltip = tooltipData.tooltip;
+ this._addDescribedBy( target, tooltip.attr( "id" ) );
+ tooltip.find( ".ui-tooltip-content" ).html( content );
+
+ // Support: Voiceover on OS X, JAWS on IE <= 9
+ // JAWS announces deletions even when aria-relevant="additions"
+ // Voiceover will sometimes re-read the entire log region's contents from the beginning
+ this.liveRegion.children().hide();
+ if ( content.clone ) {
+ a11yContent = content.clone();
+ a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
+ } else {
+ a11yContent = content;
+ }
+ $( "<div>" ).html( a11yContent ).appendTo( this.liveRegion );
+
+ function position( event ) {
+ positionOption.of = event;
+ if ( tooltip.is( ":hidden" ) ) {
+ return;
+ }
+ tooltip.position( positionOption );
+ }
+ if ( this.options.track && event && /^mouse/.test( event.type ) ) {
+ this._on( this.document, {
+ mousemove: position
+ });
+ // trigger once to override element-relative positioning
+ position( event );
+ } else {
+ tooltip.position( $.extend({
+ of: target
+ }, this.options.position ) );
+ }
+
+ tooltip.hide();
+
+ this._show( tooltip, this.options.show );
+ // Handle tracking tooltips that are shown with a delay (#8644). As soon
+ // as the tooltip is visible, position the tooltip using the most recent
+ // event.
+ if ( this.options.show && this.options.show.delay ) {
+ delayedShow = this.delayedShow = setInterval(function() {
+ if ( tooltip.is( ":visible" ) ) {
+ position( positionOption.of );
+ clearInterval( delayedShow );
+ }
+ }, $.fx.interval );
+ }
+
+ this._trigger( "open", event, { tooltip: tooltip } );
+
+ events = {
+ keyup: function( event ) {
+ if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
+ var fakeEvent = $.Event(event);
+ fakeEvent.currentTarget = target[0];
+ this.close( fakeEvent, true );
+ }
+ }
+ };
+
+ // Only bind remove handler for delegated targets. Non-delegated
+ // tooltips will handle this in destroy.
+ if ( target[ 0 ] !== this.element[ 0 ] ) {
+ events.remove = function() {
+ this._removeTooltip( tooltip );
+ };
+ }
+
+ if ( !event || event.type === "mouseover" ) {
+ events.mouseleave = "close";
+ }
+ if ( !event || event.type === "focusin" ) {
+ events.focusout = "close";
+ }
+ this._on( true, target, events );
+ },
+
+ close: function( event ) {
+ var tooltip,
+ that = this,
+ target = $( event ? event.currentTarget : this.element ),
+ tooltipData = this._find( target );
+
+ // The tooltip may already be closed
+ if ( !tooltipData ) {
+ return;
+ }
+
+ tooltip = tooltipData.tooltip;
+
+ // disabling closes the tooltip, so we need to track when we're closing
+ // to avoid an infinite loop in case the tooltip becomes disabled on close
+ if ( tooltipData.closing ) {
+ return;
+ }
+
+ // Clear the interval for delayed tracking tooltips
+ clearInterval( this.delayedShow );
+
+ // only set title if we had one before (see comment in _open())
+ // If the title attribute has changed since open(), don't restore
+ if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
+ target.attr( "title", target.data( "ui-tooltip-title" ) );
+ }
+
+ this._removeDescribedBy( target );
+
+ tooltipData.hiding = true;
+ tooltip.stop( true );
+ this._hide( tooltip, this.options.hide, function() {
+ that._removeTooltip( $( this ) );
+ });
+
+ target.removeData( "ui-tooltip-open" );
+ this._off( target, "mouseleave focusout keyup" );
+
+ // Remove 'remove' binding only on delegated targets
+ if ( target[ 0 ] !== this.element[ 0 ] ) {
+ this._off( target, "remove" );
+ }
+ this._off( this.document, "mousemove" );
+
+ if ( event && event.type === "mouseleave" ) {
+ $.each( this.parents, function( id, parent ) {
+ $( parent.element ).attr( "title", parent.title );
+ delete that.parents[ id ];
+ });
+ }
+
+ tooltipData.closing = true;
+ this._trigger( "close", event, { tooltip: tooltip } );
+ if ( !tooltipData.hiding ) {
+ tooltipData.closing = false;
+ }
+ },
+
+ _tooltip: function( element ) {
+ var tooltip = $( "<div>" )
+ .attr( "role", "tooltip" )
+ .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
+ ( this.options.tooltipClass || "" ) ),
+ id = tooltip.uniqueId().attr( "id" );
+
+ $( "<div>" )
+ .addClass( "ui-tooltip-content" )
+ .appendTo( tooltip );
+
+ tooltip.appendTo( this.document[0].body );
+
+ return this.tooltips[ id ] = {
+ element: element,
+ tooltip: tooltip
+ };
+ },
+
+ _find: function( target ) {
+ var id = target.data( "ui-tooltip-id" );
+ return id ? this.tooltips[ id ] : null;
+ },
+
+ _removeTooltip: function( tooltip ) {
+ tooltip.remove();
+ delete this.tooltips[ tooltip.attr( "id" ) ];
+ },
+
+ _destroy: function() {
+ var that = this;
+
+ // close open tooltips
+ $.each( this.tooltips, function( id, tooltipData ) {
+ // Delegate to close method to handle common cleanup
+ var event = $.Event( "blur" ),
+ element = tooltipData.element;
+ event.target = event.currentTarget = element[ 0 ];
+ that.close( event, true );
+
+ // Remove immediately; destroying an open tooltip doesn't use the
+ // hide animation
+ $( "#" + id ).remove();
+
+ // Restore the title
+ if ( element.data( "ui-tooltip-title" ) ) {
+ // If the title attribute has changed since open(), don't restore
+ if ( !element.attr( "title" ) ) {
+ element.attr( "title", element.data( "ui-tooltip-title" ) );
+ }
+ element.removeData( "ui-tooltip-title" );
+ }
+ });
+ this.liveRegion.remove();
+ }
+});
+
+
+
+}));
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/jquery/jquery.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,9205 @@
+/*!
+ * jQuery JavaScript Library v2.1.3
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-12-18T15:11Z
+ */
+
+(function( global, factory ) {
+
+ if ( typeof module === "object" && typeof module.exports === "object" ) {
+ // For CommonJS and CommonJS-like environments where a proper `window`
+ // is present, execute the factory and get jQuery.
+ // For environments that do not have a `window` with a `document`
+ // (such as Node.js), expose a factory as module.exports.
+ // This accentuates the need for the creation of a real `window`.
+ // e.g. var jQuery = require("jquery")(window);
+ // See ticket #14549 for more info.
+ module.exports = global.document ?
+ factory( global, true ) :
+ function( w ) {
+ if ( !w.document ) {
+ throw new Error( "jQuery requires a window with a document" );
+ }
+ return factory( w );
+ };
+ } else {
+ factory( global );
+ }
+
+// Pass this if window is not defined yet
+}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
+
+// Support: Firefox 18+
+// Can't be in strict mode, several libs including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+//
+
+var arr = [];
+
+var slice = arr.slice;
+
+var concat = arr.concat;
+
+var push = arr.push;
+
+var indexOf = arr.indexOf;
+
+var class2type = {};
+
+var toString = class2type.toString;
+
+var hasOwn = class2type.hasOwnProperty;
+
+var support = {};
+
+
+
+var
+ // Use the correct document accordingly with window argument (sandbox)
+ document = window.document,
+
+ version = "2.1.3",
+
+ // Define a local copy of jQuery
+ jQuery = function( selector, context ) {
+ // The jQuery object is actually just the init constructor 'enhanced'
+ // Need init if jQuery is called (just allow error to be thrown if not included)
+ return new jQuery.fn.init( selector, context );
+ },
+
+ // Support: Android<4.1
+ // Make sure we trim BOM and NBSP
+ rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
+
+ // Matches dashed string for camelizing
+ rmsPrefix = /^-ms-/,
+ rdashAlpha = /-([\da-z])/gi,
+
+ // Used by jQuery.camelCase as callback to replace()
+ fcamelCase = function( all, letter ) {
+ return letter.toUpperCase();
+ };
+
+jQuery.fn = jQuery.prototype = {
+ // The current version of jQuery being used
+ jquery: version,
+
+ constructor: jQuery,
+
+ // Start with an empty selector
+ selector: "",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ toArray: function() {
+ return slice.call( this );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num != null ?
+
+ // Return just the one element from the set
+ ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
+
+ // Return all the elements in a clean array
+ slice.call( this );
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems ) {
+
+ // Build a new jQuery matched element set
+ var ret = jQuery.merge( this.constructor(), elems );
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+ ret.context = this.context;
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (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 );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ) );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ eq: function( i ) {
+ var len = this.length,
+ j = +i + ( i < 0 ? len : 0 );
+ return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
+ },
+
+ end: function() {
+ return this.prevObject || this.constructor(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: arr.sort,
+ splice: arr.splice
+};
+
+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;
+
+ // Skip the boolean and the target
+ target = arguments[ i ] || {};
+ i++;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+ target = {};
+ }
+
+ // Extend jQuery itself if only one argument is passed
+ if ( i === length ) {
+ target = this;
+ i--;
+ }
+
+ for ( ; i < length; i++ ) {
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null ) {
+ // Extend the base object
+ for ( name in options ) {
+ src = target[ name ];
+ copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging plain objects or arrays
+ if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+ if ( copyIsArray ) {
+ copyIsArray = false;
+ clone = src && jQuery.isArray(src) ? src : [];
+
+ } else {
+ clone = src && jQuery.isPlainObject(src) ? src : {};
+ }
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ // Unique for each copy of jQuery on the page
+ expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
+
+ // Assume jQuery is ready without the ready module
+ isReady: true,
+
+ error: function( msg ) {
+ throw new Error( msg );
+ },
+
+ noop: function() {},
+
+ isFunction: function( obj ) {
+ return jQuery.type(obj) === "function";
+ },
+
+ isArray: Array.isArray,
+
+ isWindow: function( obj ) {
+ return obj != null && obj === obj.window;
+ },
+
+ isNumeric: function( obj ) {
+ // parseFloat NaNs numeric-cast false positives (null|true|false|"")
+ // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
+ // subtraction forces infinities to NaN
+ // adding 1 corrects loss of precision from parseFloat (#15100)
+ return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
+ },
+
+ 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;
+ }
+
+ if ( obj.constructor &&
+ !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
+ 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;
+ },
+
+ type: function( obj ) {
+ if ( obj == null ) {
+ return obj + "";
+ }
+ // Support: Android<4.0, iOS<6 (functionish RegExp)
+ return typeof obj === "object" || typeof obj === "function" ?
+ class2type[ toString.call(obj) ] || "object" :
+ typeof obj;
+ },
+
+ // 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
+ // Support: IE9-11+
+ // 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;
+ },
+
+ // Support: Android<4.1
+ trim: function( text ) {
+ return text == null ?
+ "" :
+ ( text + "" ).replace( rtrim, "" );
+ },
+
+ // results is for internal usage only
+ makeArray: function( arr, results ) {
+ var ret = results || [];
+
+ if ( arr != null ) {
+ if ( isArraylike( Object(arr) ) ) {
+ jQuery.merge( ret,
+ typeof arr === "string" ?
+ [ arr ] : arr
+ );
+ } else {
+ push.call( ret, arr );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, arr, i ) {
+ return arr == null ? -1 : indexOf.call( arr, elem, i );
+ },
+
+ merge: function( first, second ) {
+ var len = +second.length,
+ j = 0,
+ i = first.length;
+
+ for ( ; j < len; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, invert ) {
+ var callbackInverse,
+ matches = [],
+ i = 0,
+ length = elems.length,
+ callbackExpect = !invert;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( ; i < length; i++ ) {
+ callbackInverse = !callback( elems[ i ], i );
+ if ( callbackInverse !== callbackExpect ) {
+ matches.push( elems[ i ] );
+ }
+ }
+
+ return matches;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var value,
+ i = 0,
+ length = elems.length,
+ isArray = isArraylike( elems ),
+ ret = [];
+
+ // Go through the array, translating each of the items to their new values
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+
+ // Go through every key on the object,
+ } else {
+ for ( i in elems ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+ }
+
+ // Flatten any nested arrays
+ return concat.apply( [], ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ // Bind a function to a context, optionally partially applying any
+ // arguments.
+ proxy: function( fn, context ) {
+ var 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 = slice.call( arguments, 2 );
+ proxy = function() {
+ return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
+ };
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || jQuery.guid++;
+
+ return proxy;
+ },
+
+ now: Date.now,
+
+ // jQuery.support is not used in Core but other projects attach their
+ // properties to it so it needs to exist.
+ support: support
+});
+
+// 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 ( type === "function" || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ if ( obj.nodeType === 1 && length ) {
+ return true;
+ }
+
+ return type === "array" || length === 0 ||
+ typeof length === "number" && length > 0 && ( length - 1 ) in obj;
+}
+var Sizzle =
+/*!
+ * Sizzle CSS Selector Engine v2.2.0-pre
+ * http://sizzlejs.com/
+ *
+ * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-12-16
+ */
+(function( window ) {
+
+var i,
+ support,
+ Expr,
+ getText,
+ isXML,
+ tokenize,
+ compile,
+ select,
+ outermostContext,
+ sortInput,
+ hasDuplicate,
+
+ // Local document vars
+ setDocument,
+ document,
+ docElem,
+ documentIsHTML,
+ rbuggyQSA,
+ rbuggyMatches,
+ matches,
+ contains,
+
+ // Instance-specific data
+ expando = "sizzle" + 1 * new Date(),
+ preferredDoc = window.document,
+ dirruns = 0,
+ done = 0,
+ classCache = createCache(),
+ tokenCache = createCache(),
+ compilerCache = createCache(),
+ sortOrder = function( a, b ) {
+ if ( a === b ) {
+ hasDuplicate = true;
+ }
+ return 0;
+ },
+
+ // General-purpose constants
+ MAX_NEGATIVE = 1 << 31,
+
+ // Instance methods
+ hasOwn = ({}).hasOwnProperty,
+ arr = [],
+ pop = arr.pop,
+ push_native = arr.push,
+ push = arr.push,
+ slice = arr.slice,
+ // Use a stripped-down indexOf as it's faster than native
+ // http://jsperf.com/thor-indexof-vs-for/5
+ indexOf = function( list, elem ) {
+ var i = 0,
+ len = list.length;
+ for ( ; i < len; i++ ) {
+ if ( list[i] === elem ) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
+
+ // Regular expressions
+
+ // 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#" ),
+
+ // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
+ attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
+ // Operator (capture 2)
+ "*([*^$|!~]?=)" + whitespace +
+ // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
+ "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
+ "*\\]",
+
+ pseudos = ":(" + characterEncoding + ")(?:\\((" +
+ // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
+ // 1. quoted (capture 3; capture 4 or capture 5)
+ "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
+ // 2. simple (capture 6)
+ "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
+ // 3. anything else (capture 2)
+ ".*" +
+ ")\\)|)",
+
+ // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
+ rwhitespace = new RegExp( whitespace + "+", "g" ),
+ rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
+
+ rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
+ rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
+
+ rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
+
+ rpseudo = new RegExp( pseudos ),
+ ridentifier = new RegExp( "^" + identifier + "$" ),
+
+ matchExpr = {
+ "ID": new RegExp( "^#(" + 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" )
+ },
+
+ rinputs = /^(?:input|select|textarea|button)$/i,
+ rheader = /^h\d$/i,
+
+ rnative = /^[^{]+\{\s*\[native \w/,
+
+ // Easily-parseable/retrievable ID or TAG or CLASS selectors
+ rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
+
+ rsibling = /[+~]/,
+ rescape = /'|\\/g,
+
+ // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
+ runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
+ funescape = function( _, escaped, escapedWhitespace ) {
+ var high = "0x" + escaped - 0x10000;
+ // NaN means non-codepoint
+ // Support: Firefox<24
+ // Workaround erroneous numeric interpretation of +"0x"
+ return high !== high || escapedWhitespace ?
+ escaped :
+ high < 0 ?
+ // BMP codepoint
+ String.fromCharCode( high + 0x10000 ) :
+ // Supplemental Plane codepoint (surrogate pair)
+ String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
+ },
+
+ // Used for iframes
+ // See setDocument()
+ // Removing the function wrapper causes a "Permission Denied"
+ // error in IE
+ unloadHandler = function() {
+ setDocument();
+ };
+
+// Optimize for push.apply( _, NodeList )
+try {
+ push.apply(
+ (arr = slice.call( preferredDoc.childNodes )),
+ preferredDoc.childNodes
+ );
+ // Support: Android<4.0
+ // Detect silently failing push.apply
+ arr[ preferredDoc.childNodes.length ].nodeType;
+} catch ( e ) {
+ push = { apply: arr.length ?
+
+ // Leverage slice if possible
+ function( target, els ) {
+ push_native.apply( target, slice.call(els) );
+ } :
+
+ // Support: IE<9
+ // Otherwise append directly
+ function( target, els ) {
+ var j = target.length,
+ i = 0;
+ // Can't trust NodeList.length
+ while ( (target[j++] = els[i++]) ) {}
+ target.length = j - 1;
+ }
+ };
+}
+
+function Sizzle( selector, context, results, seed ) {
+ var 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 || [];
+ nodeType = context.nodeType;
+
+ if ( typeof selector !== "string" || !selector ||
+ nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
+
+ return results;
+ }
+
+ if ( !seed && documentIsHTML ) {
+
+ // Try to shortcut find operations when possible (e.g., not under DocumentFragment)
+ if ( nodeType !== 11 && (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 (jQuery #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 ) {
+ push.apply( results, context.getElementsByClassName( m ) );
+ return results;
+ }
+ }
+
+ // QSA path
+ if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
+ nid = old = expando;
+ newContext = context;
+ newSelector = nodeType !== 1 && 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 ) && testContext( 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]);
+ }
+ }
+ });
+ });
+}
+
+/**
+ * Checks a node for validity as a Sizzle context
+ * @param {Element|Object=} context
+ * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
+ */
+function testContext( context ) {
+ return context && typeof context.getElementsByTagName !== "undefined" && context;
+}
+
+// Expose support vars for convenience
+support = Sizzle.support = {};
+
+/**
+ * Detects XML nodes
+ * @param {Element|Object} elem An element or a document
+ * @returns {Boolean} True iff elem is a non-HTML XML node
+ */
+isXML = Sizzle.isXML = function( elem ) {
+ // documentElement is verified for cases where it doesn't yet exist
+ // (such as loading iframes in IE - #4833)
+ var documentElement = elem && (elem.ownerDocument || elem).documentElement;
+ return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+/**
+ * Sets document-related variables once based on the current document
+ * @param {Element|Object} [doc] An element or document object to use to set the document
+ * @returns {Object} Returns the current document
+ */
+setDocument = Sizzle.setDocument = function( node ) {
+ var hasCompare, parent,
+ doc = node ? node.ownerDocument || node : preferredDoc;
+
+ // 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;
+ parent = doc.defaultView;
+
+ // 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 !== parent.top ) {
+ // IE11 does not have attachEvent, so all must suffer
+ if ( parent.addEventListener ) {
+ parent.addEventListener( "unload", unloadHandler, false );
+ } else if ( parent.attachEvent ) {
+ parent.attachEvent( "onunload", unloadHandler );
+ }
+ }
+
+ /* Support tests
+ ---------------------------------------------------------------------- */
+ documentIsHTML = !isXML( doc );
+
+ /* 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;
+ });
+
+ // Support: IE<9
+ support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
+
+ // Support: IE<10
+ // Check if getElementById returns elements by name
+ // The broken getElementById methods don't pick up programatically-set names,
+ // so use a roundabout getElementsByName test
+ support.getById = assert(function( div ) {
+ docElem.appendChild( div ).id = expando;
+ return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
+ });
+
+ // ID find and filter
+ if ( support.getById ) {
+ Expr.find["ID"] = function( id, context ) {
+ if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
+ var m = context.getElementById( id );
+ // 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 !== "undefined" && elem.getAttributeNode("id");
+ return node && node.value === attrId;
+ };
+ };
+ }
+
+ // Tag
+ Expr.find["TAG"] = support.getElementsByTagName ?
+ function( tag, context ) {
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ return context.getElementsByTagName( tag );
+
+ // DocumentFragment nodes don't have gEBTN
+ } else if ( support.qsa ) {
+ return context.querySelectorAll( tag );
+ }
+ } :
+
+ function( tag, context ) {
+ var elem,
+ tmp = [],
+ i = 0,
+ // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
+ results = context.getElementsByTagName( tag );
+
+ // Filter out possible comments
+ if ( tag === "*" ) {
+ while ( (elem = results[i++]) ) {
+ if ( elem.nodeType === 1 ) {
+ tmp.push( elem );
+ }
+ }
+
+ return tmp;
+ }
+ return results;
+ };
+
+ // Class
+ Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
+ if ( 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
+ docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
+ "<select id='" + expando + "-\f]' msallowcapture=''>" +
+ "<option selected=''></option></select>";
+
+ // Support: IE8, Opera 11-12.16
+ // Nothing should be selected when empty strings follow ^= or $= or *=
+ // The test attribute must be unknown in Opera but "safe" for WinRT
+ // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
+ if ( div.querySelectorAll("[msallowcapture^='']").length ) {
+ rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
+ }
+
+ // Support: IE8
+ // Boolean attributes and "value" are not treated correctly
+ if ( !div.querySelectorAll("[selected]").length ) {
+ rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
+ }
+
+ // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
+ rbuggyQSA.push("~=");
+ }
+
+ // Webkit/Opera - :checked should return selected option elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ // IE8 throws error here and will not see later tests
+ if ( !div.querySelectorAll(":checked").length ) {
+ rbuggyQSA.push(":checked");
+ }
+
+ // Support: Safari 8+, iOS 8+
+ // https://bugs.webkit.org/show_bug.cgi?id=136851
+ // In-page `selector#id sibing-combinator selector` fails
+ if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
+ rbuggyQSA.push(".#.+[+~]");
+ }
+ });
+
+ assert(function( div ) {
+ // Support: Windows 8 Native Apps
+ // The type and name attributes are restricted during .innerHTML assignment
+ var input = doc.createElement("input");
+ input.setAttribute( "type", "hidden" );
+ div.appendChild( input ).setAttribute( "name", "D" );
+
+ // Support: IE8
+ // Enforce case-sensitivity of name attribute
+ if ( div.querySelectorAll("[name=d]").length ) {
+ rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
+ }
+
+ // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
+ // IE8 throws error here and will not see later tests
+ if ( !div.querySelectorAll(":enabled").length ) {
+ rbuggyQSA.push( ":enabled", ":disabled" );
+ }
+
+ // Opera 10-11 does not throw on post-comma invalid pseudos
+ div.querySelectorAll("*,:x");
+ rbuggyQSA.push(",.*:");
+ });
+ }
+
+ if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
+ docElem.webkitMatchesSelector ||
+ docElem.mozMatchesSelector ||
+ docElem.oMatchesSelector ||
+ docElem.msMatchesSelector) )) ) {
+
+ assert(function( div ) {
+ // Check to see if it's possible to do matchesSelector
+ // on a disconnected node (IE 9)
+ support.disconnectedMatch = matches.call( div, "div" );
+
+ // This should fail with an exception
+ // Gecko does not error, returns false instead
+ matches.call( div, "[s!='']:x" );
+ rbuggyMatches.push( "!=", pseudos );
+ });
+ }
+
+ rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
+ rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
+
+ /* Contains
+ ---------------------------------------------------------------------- */
+ hasCompare = rnative.test( docElem.compareDocumentPosition );
+
+ // Element contains another
+ // Purposefully does not implement inclusive descendent
+ // As in, an element does not contain itself
+ contains = hasCompare || rnative.test( docElem.contains ) ?
+ function( a, b ) {
+ var adown = a.nodeType === 9 ? a.documentElement : a,
+ bup = b && b.parentNode;
+ return a === bup || !!( bup && bup.nodeType === 1 && (
+ adown.contains ?
+ adown.contains( bup ) :
+ a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
+ ));
+ } :
+ function( a, b ) {
+ if ( b ) {
+ while ( (b = b.parentNode) ) {
+ if ( b === a ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+
+ /* Sorting
+ ---------------------------------------------------------------------- */
+
+ // Document order sorting
+ sortOrder = hasCompare ?
+ function( a, b ) {
+
+ // Flag for duplicate removal
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ // Sort on method existence if only one input has compareDocumentPosition
+ var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
+ if ( compare ) {
+ return compare;
+ }
+
+ // Calculate position if both inputs belong to the same document
+ compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
+ a.compareDocumentPosition( b ) :
+
+ // Otherwise we know they are disconnected
+ 1;
+
+ // Disconnected nodes
+ if ( compare & 1 ||
+ (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
+
+ // Choose the first element that is related to our preferred document
+ if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
+ return -1;
+ }
+ if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
+ return 1;
+ }
+
+ // Maintain original order
+ return sortInput ?
+ ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
+ 0;
+ }
+
+ return compare & 4 ? -1 : 1;
+ } :
+ function( a, b ) {
+ // Exit early if the nodes are identical
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ var cur,
+ i = 0,
+ aup = a.parentNode,
+ bup = b.parentNode,
+ ap = [ a ],
+ bp = [ b ];
+
+ // Parentless nodes are either documents or disconnected
+ if ( !aup || !bup ) {
+ return a === doc ? -1 :
+ b === doc ? 1 :
+ aup ? -1 :
+ bup ? 1 :
+ sortInput ?
+ ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
+ 0;
+
+ // If the nodes are siblings, we can do a quick check
+ } else if ( aup === bup ) {
+ return siblingCheck( a, b );
+ }
+
+ // Otherwise we need full lists of their ancestors for comparison
+ cur = a;
+ while ( (cur = cur.parentNode) ) {
+ ap.unshift( cur );
+ }
+ cur = b;
+ while ( (cur = cur.parentNode) ) {
+ bp.unshift( cur );
+ }
+
+ // Walk down the tree looking for a discrepancy
+ while ( ap[i] === bp[i] ) {
+ i++;
+ }
+
+ return i ?
+ // Do a sibling check if the nodes have a common ancestor
+ siblingCheck( ap[i], bp[i] ) :
+
+ // Otherwise nodes in our document sort first
+ ap[i] === preferredDoc ? -1 :
+ bp[i] === preferredDoc ? 1 :
+ 0;
+ };
+
+ return 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 ?
+ val :
+ support.attributes || !documentIsHTML ?
+ elem.getAttribute( name ) :
+ (val = elem.getAttributeNode(name)) && val.specified ?
+ val.value :
+ null;
+};
+
+Sizzle.error = function( msg ) {
+ throw new Error( "Syntax error, unrecognized expression: " + msg );
+};
+
+/**
+ * Document sorting and removing duplicates
+ * @param {ArrayLike} results
+ */
+Sizzle.uniqueSort = function( results ) {
+ var elem,
+ duplicates = [],
+ j = 0,
+ i = 0;
+
+ // Unless we *know* we can detect duplicates, assume their presence
+ hasDuplicate = !support.detectDuplicates;
+ sortInput = !support.sortStable && results.slice( 0 );
+ results.sort( sortOrder );
+
+ if ( hasDuplicate ) {
+ while ( (elem = results[i++]) ) {
+ if ( elem === results[ i ] ) {
+ j = duplicates.push( i );
+ }
+ }
+ while ( j-- ) {
+ results.splice( duplicates[ j ], 1 );
+ }
+ }
+
+ // Clear input after sorting to release objects
+ // See https://github.com/jquery/sizzle/pull/225
+ sortInput = null;
+
+ return results;
+};
+
+/**
+ * Utility function for retrieving the text value of an array of DOM nodes
+ * @param {Array|Element} elem
+ */
+getText = Sizzle.getText = function( elem ) {
+ var node,
+ ret = "",
+ i = 0,
+ nodeType = elem.nodeType;
+
+ if ( !nodeType ) {
+ // If no nodeType, this is expected to be an array
+ while ( (node = elem[i++]) ) {
+ // Do not traverse comment nodes
+ ret += getText( node );
+ }
+ } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
+ // Use textContent for elements
+ // innerText usage removed for consistency of new lines (jQuery #11153)
+ if ( typeof elem.textContent === "string" ) {
+ return elem.textContent;
+ } else {
+ // Traverse its children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ ret += getText( elem );
+ }
+ }
+ } else if ( nodeType === 3 || nodeType === 4 ) {
+ return elem.nodeValue;
+ }
+ // Do not include comment or processing instruction nodes
+
+ return ret;
+};
+
+Expr = Sizzle.selectors = {
+
+ // Can be adjusted by the user
+ cacheLength: 50,
+
+ createPseudo: markFunction,
+
+ match: matchExpr,
+
+ attrHandle: {},
+
+ find: {},
+
+ relative: {
+ ">": { dir: "parentNode", first: true },
+ " ": { dir: "parentNode" },
+ "+": { dir: "previousSibling", first: true },
+ "~": { dir: "previousSibling" }
+ },
+
+ preFilter: {
+ "ATTR": function( match ) {
+ match[1] = match[1].replace( runescape, funescape );
+
+ // Move the given value to match[3] whether quoted or unquoted
+ match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
+
+ if ( match[2] === "~=" ) {
+ match[3] = " " + match[3] + " ";
+ }
+
+ return match.slice( 0, 4 );
+ },
+
+ "CHILD": function( match ) {
+ /* matches from matchExpr["CHILD"]
+ 1 type (only|nth|...)
+ 2 what (child|of-type)
+ 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
+ 4 xn-component of xn+y argument ([+-]?\d*n|)
+ 5 sign of xn-component
+ 6 x of xn-component
+ 7 sign of y-component
+ 8 y of y-component
+ */
+ match[1] = match[1].toLowerCase();
+
+ if ( match[1].slice( 0, 3 ) === "nth" ) {
+ // nth-* requires argument
+ if ( !match[3] ) {
+ Sizzle.error( match[0] );
+ }
+
+ // numeric x and y parameters for Expr.filter.CHILD
+ // remember that false/true cast respectively to 0/1
+ match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
+ match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
+
+ // other types prohibit arguments
+ } else if ( match[3] ) {
+ Sizzle.error( match[0] );
+ }
+
+ return match;
+ },
+
+ "PSEUDO": function( match ) {
+ var excess,
+ unquoted = !match[6] && match[2];
+
+ if ( matchExpr["CHILD"].test( match[0] ) ) {
+ return null;
+ }
+
+ // Accept quoted arguments as-is
+ if ( match[3] ) {
+ match[2] = match[4] || match[5] || "";
+
+ // Strip excess characters from unquoted arguments
+ } else if ( unquoted && rpseudo.test( unquoted ) &&
+ // Get excess from tokenize (recursively)
+ (excess = tokenize( unquoted, true )) &&
+ // advance to the next closing parenthesis
+ (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
+
+ // excess is a negative index
+ match[0] = match[0].slice( 0, excess );
+ match[2] = unquoted.slice( 0, excess );
+ }
+
+ // Return only captures needed by the pseudo filter method (type and argument)
+ return match.slice( 0, 3 );
+ }
+ },
+
+ filter: {
+
+ "TAG": function( nodeNameSelector ) {
+ var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
+ return nodeNameSelector === "*" ?
+ function() { return true; } :
+ function( elem ) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
+ };
+ },
+
+ "CLASS": function( className ) {
+ var pattern = classCache[ className + " " ];
+
+ return pattern ||
+ (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
+ classCache( className, function( elem ) {
+ return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
+ });
+ },
+
+ "ATTR": function( name, operator, check ) {
+ return function( elem ) {
+ var result = Sizzle.attr( elem, name );
+
+ if ( result == null ) {
+ return operator === "!=";
+ }
+ if ( !operator ) {
+ return true;
+ }
+
+ result += "";
+
+ return operator === "=" ? result === check :
+ operator === "!=" ? result !== check :
+ operator === "^=" ? check && result.indexOf( check ) === 0 :
+ operator === "*=" ? check && result.indexOf( check ) > -1 :
+ operator === "$=" ? check && result.slice( -check.length ) === check :
+ operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
+ operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
+ false;
+ };
+ },
+
+ "CHILD": function( type, what, argument, first, last ) {
+ var simple = type.slice( 0, 3 ) !== "nth",
+ forward = type.slice( -4 ) !== "last",
+ ofType = what === "of-type";
+
+ return first === 1 && last === 0 ?
+
+ // Shortcut for :nth-*(n)
+ function( elem ) {
+ return !!elem.parentNode;
+ } :
+
+ function( elem, context, xml ) {
+ var cache, 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( seed, matched[i] );
+ seed[ idx ] = !( matches[ idx ] = matched[i] );
+ }
+ }) :
+ function( elem ) {
+ return fn( elem, 0, args );
+ };
+ }
+
+ return fn;
+ }
+ },
+
+ pseudos: {
+ // Potentially complex pseudos
+ "not": markFunction(function( selector ) {
+ // Trim the selector passed to compile
+ // to avoid treating leading and trailing
+ // spaces as combinators
+ var input = [],
+ results = [],
+ matcher = compile( selector.replace( rtrim, "$1" ) );
+
+ return matcher[ expando ] ?
+ markFunction(function( seed, matches, context, xml ) {
+ var elem,
+ unmatched = matcher( seed, null, xml, [] ),
+ i = seed.length;
+
+ // Match elements unmatched by `matcher`
+ while ( i-- ) {
+ if ( (elem = unmatched[i]) ) {
+ seed[i] = !(matches[i] = elem);
+ }
+ }
+ }) :
+ function( elem, context, xml ) {
+ input[0] = elem;
+ matcher( input, null, xml, results );
+ // Don't keep the element (issue #299)
+ input[0] = null;
+ return !results.pop();
+ };
+ }),
+
+ "has": markFunction(function( selector ) {
+ return function( elem ) {
+ return Sizzle( selector, elem ).length > 0;
+ };
+ }),
+
+ "contains": markFunction(function( text ) {
+ text = text.replace( runescape, funescape );
+ return function( elem ) {
+ return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
+ };
+ }),
+
+ // "Whether an element is represented by a :lang() selector
+ // is based solely on the element's language value
+ // being equal to the identifier C,
+ // or beginning with the identifier C immediately followed by "-".
+ // The matching of C against the element's language value is performed case-insensitively.
+ // The identifier C does not have to be a valid language name."
+ // http://www.w3.org/TR/selectors/#lang-pseudo
+ "lang": markFunction( function( lang ) {
+ // lang value must be a valid identifier
+ if ( !ridentifier.test(lang || "") ) {
+ Sizzle.error( "unsupported lang: " + lang );
+ }
+ lang = lang.replace( runescape, funescape ).toLowerCase();
+ return function( elem ) {
+ var elemLang;
+ do {
+ if ( (elemLang = documentIsHTML ?
+ elem.lang :
+ elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
+
+ elemLang = elemLang.toLowerCase();
+ return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
+ }
+ } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
+ return false;
+ };
+ }),
+
+ // Miscellaneous
+ "target": function( elem ) {
+ var hash = window.location && window.location.hash;
+ return hash && hash.slice( 1 ) === elem.id;
+ },
+
+ "root": function( elem ) {
+ return elem === docElem;
+ },
+
+ "focus": function( elem ) {
+ return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
+ },
+
+ // Boolean properties
+ "enabled": function( elem ) {
+ return elem.disabled === false;
+ },
+
+ "disabled": function( elem ) {
+ return elem.disabled === true;
+ },
+
+ "checked": function( elem ) {
+ // In CSS3, :checked should return both checked and selected elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ var nodeName = elem.nodeName.toLowerCase();
+ return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
+ },
+
+ "selected": function( elem ) {
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ if ( elem.parentNode ) {
+ elem.parentNode.selectedIndex;
+ }
+
+ return elem.selected === true;
+ },
+
+ // Contents
+ "empty": function( elem ) {
+ // http://www.w3.org/TR/selectors/#empty-pseudo
+ // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
+ // but not by others (comment: 8; processing instruction: 7; etc.)
+ // nodeType < 6 works because attributes (2) do not appear as children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ if ( elem.nodeType < 6 ) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ "parent": function( elem ) {
+ return !Expr.pseudos["empty"]( elem );
+ },
+
+ // Element/input types
+ "header": function( elem ) {
+ return rheader.test( elem.nodeName );
+ },
+
+ "input": function( elem ) {
+ return rinputs.test( elem.nodeName );
+ },
+
+ "button": function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && elem.type === "button" || name === "button";
+ },
+
+ "text": function( elem ) {
+ var attr;
+ return elem.nodeName.toLowerCase() === "input" &&
+ elem.type === "text" &&
+
+ // Support: IE<8
+ // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
+ ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
+ },
+
+ // Position-in-collection
+ "first": createPositionalPseudo(function() {
+ return [ 0 ];
+ }),
+
+ "last": createPositionalPseudo(function( matchIndexes, length ) {
+ return [ length - 1 ];
+ }),
+
+ "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
+ return [ argument < 0 ? argument + length : argument ];
+ }),
+
+ "even": createPositionalPseudo(function( matchIndexes, length ) {
+ var i = 0;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ }),
+
+ "odd": createPositionalPseudo(function( matchIndexes, length ) {
+ var i = 1;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ }),
+
+ "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
+ var i = argument < 0 ? argument + length : argument;
+ for ( ; --i >= 0; ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ }),
+
+ "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
+ var i = argument < 0 ? argument + length : argument;
+ for ( ; ++i < length; ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ })
+ }
+};
+
+Expr.pseudos["nth"] = Expr.pseudos["eq"];
+
+// Add button/input type pseudos
+for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
+ Expr.pseudos[ i ] = createInputPseudo( i );
+}
+for ( i in { submit: true, reset: true } ) {
+ Expr.pseudos[ i ] = createButtonPseudo( i );
+}
+
+// Easy API for creating new setFilters
+function setFilters() {}
+setFilters.prototype = Expr.filters = Expr.pseudos;
+Expr.setFilters = new setFilters();
+
+tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
+ var matched, match, tokens, type,
+ soFar, groups, preFilters,
+ cached = tokenCache[ selector + " " ];
+
+ if ( cached ) {
+ return parseOnly ? 0 : cached.slice( 0 );
+ }
+
+ soFar = selector;
+ groups = [];
+ preFilters = Expr.preFilter;
+
+ while ( soFar ) {
+
+ // Comma and first run
+ if ( !matched || (match = rcomma.exec( soFar )) ) {
+ if ( match ) {
+ // Don't consume trailing commas as valid
+ soFar = soFar.slice( match[0].length ) || soFar;
+ }
+ groups.push( (tokens = []) );
+ }
+
+ matched = false;
+
+ // Combinators
+ if ( (match = rcombinators.exec( soFar )) ) {
+ matched = match.shift();
+ tokens.push({
+ value: matched,
+ // Cast descendant combinators to space
+ type: match[0].replace( rtrim, " " )
+ });
+ soFar = soFar.slice( matched.length );
+ }
+
+ // Filters
+ for ( type in Expr.filter ) {
+ if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
+ (match = preFilters[ type ]( match ))) ) {
+ matched = match.shift();
+ tokens.push({
+ value: matched,
+ type: type,
+ matches: match
+ });
+ soFar = soFar.slice( matched.length );
+ }
+ }
+
+ if ( !matched ) {
+ break;
+ }
+ }
+
+ // Return the length of the invalid excess
+ // if we're just parsing
+ // Otherwise, throw an error or return tokens
+ return parseOnly ?
+ soFar.length :
+ soFar ?
+ Sizzle.error( selector ) :
+ // Cache the tokens
+ tokenCache( selector, groups ).slice( 0 );
+};
+
+function toSelector( tokens ) {
+ var i = 0,
+ len = tokens.length,
+ selector = "";
+ for ( ; i < len; i++ ) {
+ selector += tokens[i].value;
+ }
+ return selector;
+}
+
+function addCombinator( matcher, combinator, base ) {
+ var dir = combinator.dir,
+ checkNonElements = base && dir === "parentNode",
+ doneName = done++;
+
+ return combinator.first ?
+ // Check against closest ancestor/preceding element
+ function( elem, context, xml ) {
+ while ( (elem = elem[ dir ]) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ return matcher( elem, context, xml );
+ }
+ }
+ } :
+
+ // Check against all ancestor/preceding elements
+ function( elem, context, xml ) {
+ var oldCache, outerCache,
+ newCache = [ 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 ( (oldCache = outerCache[ dir ]) &&
+ oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
+
+ // Assign to newCache so results back-propagate to previous elements
+ return (newCache[ 2 ] = oldCache[ 2 ]);
+ } else {
+ // Reuse newcache so results back-propagate to previous elements
+ outerCache[ dir ] = newCache;
+
+ // A match means we're done; a fail means we have to keep checking
+ if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+function elementMatcher( matchers ) {
+ return matchers.length > 1 ?
+ function( elem, context, xml ) {
+ var i = matchers.length;
+ while ( i-- ) {
+ if ( !matchers[i]( elem, context, xml ) ) {
+ return false;
+ }
+ }
+ return true;
+ } :
+ matchers[0];
+}
+
+function multipleContexts( selector, contexts, results ) {
+ var i = 0,
+ len = contexts.length;
+ for ( ; i < len; i++ ) {
+ Sizzle( selector, contexts[i], results );
+ }
+ return results;
+}
+
+function condense( unmatched, map, filter, context, xml ) {
+ var elem,
+ newUnmatched = [],
+ i = 0,
+ len = unmatched.length,
+ mapped = map != null;
+
+ for ( ; i < len; i++ ) {
+ if ( (elem = unmatched[i]) ) {
+ if ( !filter || filter( elem, context, xml ) ) {
+ newUnmatched.push( elem );
+ if ( mapped ) {
+ map.push( i );
+ }
+ }
+ }
+ }
+
+ return newUnmatched;
+}
+
+function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
+ if ( postFilter && !postFilter[ expando ] ) {
+ postFilter = setMatcher( postFilter );
+ }
+ if ( postFinder && !postFinder[ expando ] ) {
+ postFinder = setMatcher( postFinder, postSelector );
+ }
+ return markFunction(function( seed, results, context, xml ) {
+ var temp, i, elem,
+ preMap = [],
+ postMap = [],
+ preexisting = results.length,
+
+ // Get initial elements from seed or context
+ elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
+
+ // Prefilter to get matcher input, preserving a map for seed-results synchronization
+ matcherIn = preFilter && ( seed || !selector ) ?
+ condense( elems, preMap, preFilter, context, xml ) :
+ elems,
+
+ matcherOut = matcher ?
+ // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
+ postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
+
+ // ...intermediate processing is necessary
+ [] :
+
+ // ...otherwise use results directly
+ results :
+ matcherIn;
+
+ // Find primary matches
+ if ( matcher ) {
+ matcher( matcherIn, matcherOut, context, xml );
+ }
+
+ // Apply postFilter
+ if ( postFilter ) {
+ temp = condense( matcherOut, postMap );
+ postFilter( temp, [], context, xml );
+
+ // Un-match failing elements by moving them back to matcherIn
+ i = temp.length;
+ while ( i-- ) {
+ if ( (elem = temp[i]) ) {
+ matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
+ }
+ }
+ }
+
+ if ( seed ) {
+ if ( postFinder || preFilter ) {
+ if ( postFinder ) {
+ // Get the final matcherOut by condensing this intermediate into postFinder contexts
+ temp = [];
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( (elem = matcherOut[i]) ) {
+ // Restore matcherIn since elem is not yet a final match
+ temp.push( (matcherIn[i] = elem) );
+ }
+ }
+ postFinder( null, (matcherOut = []), temp, xml );
+ }
+
+ // Move matched elements from seed to results to keep them synchronized
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( (elem = matcherOut[i]) &&
+ (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
+
+ seed[temp] = !(results[temp] = elem);
+ }
+ }
+ }
+
+ // Add elements to results, through postFinder if defined
+ } else {
+ matcherOut = condense(
+ matcherOut === results ?
+ matcherOut.splice( preexisting, matcherOut.length ) :
+ matcherOut
+ );
+ if ( postFinder ) {
+ postFinder( null, results, matcherOut, xml );
+ } else {
+ push.apply( results, matcherOut );
+ }
+ }
+ });
+}
+
+function matcherFromTokens( tokens ) {
+ var checkContext, matcher, j,
+ len = tokens.length,
+ leadingRelative = Expr.relative[ tokens[0].type ],
+ implicitRelative = leadingRelative || Expr.relative[" "],
+ i = leadingRelative ? 1 : 0,
+
+ // The foundational matcher ensures that elements are reachable from top-level context(s)
+ matchContext = addCombinator( function( elem ) {
+ return elem === checkContext;
+ }, implicitRelative, true ),
+ matchAnyContext = addCombinator( function( elem ) {
+ return indexOf( checkContext, elem ) > -1;
+ }, implicitRelative, true ),
+ matchers = [ function( elem, context, xml ) {
+ var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
+ (checkContext = context).nodeType ?
+ matchContext( elem, context, xml ) :
+ matchAnyContext( elem, context, xml ) );
+ // Avoid hanging onto element (issue #299)
+ checkContext = null;
+ return ret;
+ } ];
+
+ for ( ; i < len; i++ ) {
+ if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
+ matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
+ } else {
+ matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
+
+ // Return special upon seeing a positional matcher
+ if ( matcher[ expando ] ) {
+ // Find the next relative operator (if any) for proper handling
+ j = ++i;
+ for ( ; j < len; j++ ) {
+ if ( Expr.relative[ tokens[j].type ] ) {
+ break;
+ }
+ }
+ return setMatcher(
+ i > 1 && elementMatcher( matchers ),
+ i > 1 && toSelector(
+ // If the preceding token was a descendant combinator, insert an implicit any-element `*`
+ tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
+ ).replace( rtrim, "$1" ),
+ matcher,
+ i < j && matcherFromTokens( tokens.slice( i, j ) ),
+ j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
+ j < len && toSelector( tokens )
+ );
+ }
+ matchers.push( matcher );
+ }
+ }
+
+ return elementMatcher( matchers );
+}
+
+function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
+ var bySet = setMatchers.length > 0,
+ byElement = elementMatchers.length > 0,
+ superMatcher = function( seed, context, xml, results, outermost ) {
+ var elem, j, matcher,
+ matchedCount = 0,
+ i = "0",
+ unmatched = seed && [],
+ setMatched = [],
+ contextBackup = outermostContext,
+ // We must always have either seed elements or outermost context
+ elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
+ // Use integer dirruns iff this is the outermost matcher
+ dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
+ len = elems.length;
+
+ if ( outermost ) {
+ outermostContext = context !== document && context;
+ }
+
+ // Add elements passing elementMatchers directly to results
+ // Keep `i` a string if there are no elements so `matchedCount` will be "00" below
+ // Support: IE<9, Safari
+ // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
+ for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
+ if ( byElement && elem ) {
+ j = 0;
+ while ( (matcher = elementMatchers[j++]) ) {
+ if ( matcher( elem, context, xml ) ) {
+ results.push( elem );
+ break;
+ }
+ }
+ if ( outermost ) {
+ dirruns = dirrunsUnique;
+ }
+ }
+
+ // Track unmatched elements for set filters
+ if ( bySet ) {
+ // They will have gone through all possible matchers
+ if ( (elem = !matcher && elem) ) {
+ matchedCount--;
+ }
+
+ // Lengthen the array for every element, matched or not
+ if ( seed ) {
+ unmatched.push( elem );
+ }
+ }
+ }
+
+ // 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, match /* Internal Use Only */ ) {
+ var i,
+ setMatchers = [],
+ elementMatchers = [],
+ cached = compilerCache[ selector + " " ];
+
+ if ( !cached ) {
+ // Generate a function of recursive functions that can be used to check each element
+ if ( !match ) {
+ match = tokenize( selector );
+ }
+ i = match.length;
+ while ( i-- ) {
+ cached = matcherFromTokens( match[i] );
+ if ( cached[ expando ] ) {
+ setMatchers.push( cached );
+ } else {
+ elementMatchers.push( cached );
+ }
+ }
+
+ // Cache the compiled function
+ cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
+
+ // Save selector and tokenization
+ cached.selector = selector;
+ }
+ return cached;
+};
+
+/**
+ * A low-level selection function that works with Sizzle's compiled
+ * selector functions
+ * @param {String|Function} selector A selector or a pre-compiled
+ * selector function built with Sizzle.compile
+ * @param {Element} context
+ * @param {Array} [results]
+ * @param {Array} [seed] A set of elements to match against
+ */
+select = Sizzle.select = function( selector, context, results, seed ) {
+ var i, tokens, token, type, find,
+ compiled = typeof selector === "function" && selector,
+ match = !seed && tokenize( (selector = compiled.selector || selector) );
+
+ results = results || [];
+
+ // Try to minimize operations if there is no seed and 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;
+
+ // Precompiled matchers will still verify ancestry, so step up a level
+ } else if ( compiled ) {
+ context = context.parentNode;
+ }
+
+ selector = selector.slice( tokens.shift().value.length );
+ }
+
+ // Fetch a seed set for right-to-left matching
+ i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
+ while ( i-- ) {
+ token = tokens[i];
+
+ // Abort if we hit a combinator
+ if ( Expr.relative[ (type = token.type) ] ) {
+ break;
+ }
+ if ( (find = Expr.find[ type ]) ) {
+ // Search, expanding context for leading sibling combinators
+ if ( (seed = find(
+ token.matches[0].replace( runescape, funescape ),
+ rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
+ )) ) {
+
+ // If seed is empty or no tokens remain, we can return early
+ tokens.splice( i, 1 );
+ selector = seed.length && toSelector( tokens );
+ if ( !selector ) {
+ push.apply( results, seed );
+ return results;
+ }
+
+ break;
+ }
+ }
+ }
+ }
+
+ // Compile and execute a filtering function if one is not provided
+ // Provide `match` to avoid retokenization if we modified the selector above
+ ( compiled || compile( selector, match ) )(
+ seed,
+ context,
+ !documentIsHTML,
+ results,
+ rsibling.test( selector ) && testContext( context.parentNode ) || context
+ );
+ return results;
+};
+
+// One-time assignments
+
+// Sort stability
+support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
+
+// Support: Chrome 14-35+
+// Always assume duplicates if they aren't passed to the comparison function
+support.detectDuplicates = !!hasDuplicate;
+
+// Initialize against the default document
+setDocument();
+
+// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
+// Detached nodes confoundingly follow *each other*
+support.sortDetached = assert(function( div1 ) {
+ // Should return 1, but returns 4 (following)
+ return div1.compareDocumentPosition( document.createElement("div") ) & 1;
+});
+
+// Support: IE<8
+// Prevent attribute/property "interpolation"
+// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+if ( !assert(function( div ) {
+ div.innerHTML = "<a href='#'></a>";
+ return div.firstChild.getAttribute("href") === "#" ;
+}) ) {
+ addHandle( "type|href|height|width", function( elem, name, isXML ) {
+ if ( !isXML ) {
+ return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
+ }
+ });
+}
+
+// Support: IE<9
+// Use defaultValue in place of getAttribute("value")
+if ( !support.attributes || !assert(function( div ) {
+ div.innerHTML = "<input/>";
+ div.firstChild.setAttribute( "value", "" );
+ return div.firstChild.getAttribute( "value" ) === "";
+}) ) {
+ addHandle( "value", function( elem, name, isXML ) {
+ if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
+ return elem.defaultValue;
+ }
+ });
+}
+
+// Support: IE<9
+// Use getAttributeNode to fetch booleans when getAttribute lies
+if ( !assert(function( div ) {
+ return div.getAttribute("disabled") == null;
+}) ) {
+ addHandle( booleans, function( elem, name, isXML ) {
+ var val;
+ if ( !isXML ) {
+ return elem[ name ] === true ? name.toLowerCase() :
+ (val = elem.getAttributeNode( name )) && val.specified ?
+ val.value :
+ null;
+ }
+ });
+}
+
+return Sizzle;
+
+})( window );
+
+
+
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.pseudos;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+
+var rneedsContext = jQuery.expr.match.needsContext;
+
+var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
+
+
+
+var risSimple = /^.[^:#\[\.,]*$/;
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, not ) {
+ if ( jQuery.isFunction( qualifier ) ) {
+ return jQuery.grep( elements, function( elem, i ) {
+ /* jshint -W018 */
+ return !!qualifier.call( elem, i, elem ) !== not;
+ });
+
+ }
+
+ if ( qualifier.nodeType ) {
+ return jQuery.grep( elements, function( elem ) {
+ return ( elem === qualifier ) !== not;
+ });
+
+ }
+
+ if ( typeof qualifier === "string" ) {
+ if ( risSimple.test( qualifier ) ) {
+ return jQuery.filter( qualifier, elements, not );
+ }
+
+ qualifier = jQuery.filter( qualifier, elements );
+ }
+
+ return jQuery.grep( elements, function( elem ) {
+ return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
+ });
+}
+
+jQuery.filter = function( expr, elems, not ) {
+ var elem = elems[ 0 ];
+
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return elems.length === 1 && elem.nodeType === 1 ?
+ jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
+ jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
+ return elem.nodeType === 1;
+ }));
+};
+
+jQuery.fn.extend({
+ find: function( selector ) {
+ var i,
+ len = this.length,
+ ret = [],
+ self = this;
+
+ if ( typeof selector !== "string" ) {
+ return this.pushStack( jQuery( selector ).filter(function() {
+ for ( i = 0; i < len; i++ ) {
+ if ( jQuery.contains( self[ i ], this ) ) {
+ return true;
+ }
+ }
+ }) );
+ }
+
+ for ( i = 0; i < len; i++ ) {
+ jQuery.find( selector, self[ i ], ret );
+ }
+
+ // Needed because $( selector, context ) becomes $( context ).find( selector )
+ ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
+ ret.selector = this.selector ? this.selector + " " + selector : selector;
+ return ret;
+ },
+ filter: function( selector ) {
+ return this.pushStack( winnow(this, selector || [], false) );
+ },
+ not: function( selector ) {
+ return this.pushStack( winnow(this, selector || [], true) );
+ },
+ is: function( selector ) {
+ return !!winnow(
+ this,
+
+ // If this is a positional/relative selector, check membership in the returned set
+ // so $("p:first").is("p:last") won't return true for a doc with two "p".
+ typeof selector === "string" && rneedsContext.test( selector ) ?
+ jQuery( selector ) :
+ selector || [],
+ false
+ ).length;
+ }
+});
+
+
+// Initialize a jQuery object
+
+
+// A central reference to the root jQuery(document)
+var rootjQuery,
+
+ // A simple way to check for HTML strings
+ // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+ // Strict HTML recognition (#11290: must start with <)
+ rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
+
+ init = jQuery.fn.init = function( selector, context ) {
+ var match, elem;
+
+ // HANDLE: $(""), $(null), $(undefined), $(false)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ if ( selector[0] === "<" && selector[ 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;
+
+ // Option to run scripts is true for back-compat
+ // Intentionally let the error be thrown if parseHTML is not present
+ jQuery.merge( this, jQuery.parseHTML(
+ match[1],
+ context && context.nodeType ? context.ownerDocument || context : document,
+ true
+ ) );
+
+ // HANDLE: $(html, props)
+ if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
+ for ( match in context ) {
+ // Properties of context are called as methods if possible
+ if ( jQuery.isFunction( this[ match ] ) ) {
+ this[ match ]( context[ match ] );
+
+ // ...and otherwise set as attributes
+ } else {
+ this.attr( match, context[ match ] );
+ }
+ }
+ }
+
+ return this;
+
+ // HANDLE: $(#id)
+ } else {
+ elem = document.getElementById( match[2] );
+
+ // Support: Blackberry 4.6
+ // gEBID returns nodes 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 typeof rootjQuery.ready !== "undefined" ?
+ rootjQuery.ready( selector ) :
+ // Execute immediately if ready is not present
+ selector( jQuery );
+ }
+
+ if ( selector.selector !== undefined ) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.makeArray( selector, this );
+ };
+
+// Give the init function the jQuery prototype for later instantiation
+init.prototype = jQuery.fn;
+
+// Initialize central reference
+rootjQuery = jQuery( document );
+
+
+var rparentsprev = /^(?:parents|prev(?:Until|All))/,
+ // Methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+jQuery.extend({
+ 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;
+ }
+});
+
+jQuery.fn.extend({
+ 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;
+ }
+ }
+ });
+ },
+
+ closest: function( selectors, context ) {
+ var cur,
+ i = 0,
+ l = this.length,
+ matched = [],
+ pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
+ jQuery( selectors, context || this.context ) :
+ 0;
+
+ for ( ; i < l; i++ ) {
+ for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
+ // Always skip document fragments
+ if ( cur.nodeType < 11 && (pos ?
+ pos.index(cur) > -1 :
+
+ // Don't pass non-elements to Sizzle
+ cur.nodeType === 1 &&
+ jQuery.find.matchesSelector(cur, selectors)) ) {
+
+ matched.push( cur );
+ break;
+ }
+ }
+ }
+
+ return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
+ },
+
+ // Determine the position of an element within the set
+ 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 indexOf.call( jQuery( elem ), this[ 0 ] );
+ }
+
+ // Locate the position of the desired element
+ return indexOf.call( this,
+
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[ 0 ] : elem
+ );
+ },
+
+ add: function( selector, context ) {
+ return this.pushStack(
+ jQuery.unique(
+ jQuery.merge( this.get(), jQuery( selector, context ) )
+ )
+ );
+ },
+
+ addBack: function( selector ) {
+ return this.add( selector == null ?
+ this.prevObject : this.prevObject.filter(selector)
+ );
+ }
+});
+
+function sibling( cur, dir ) {
+ 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 );
+ };
+});
+var rnotwhite = (/\S+/g);
+
+
+
+// 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( 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 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[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
+ }
+ });
+ });
+ fns = null;
+ }).promise();
+ },
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj ) {
+ return obj != null ? jQuery.extend( obj, promise ) : promise;
+ }
+ },
+ deferred = {};
+
+ // Keep pipe for back-compat
+ promise.pipe = promise.then;
+
+ // Add list-specific methods
+ jQuery.each( tuples, function( i, tuple ) {
+ var list = tuple[ 2 ],
+ stateString = tuple[ 3 ];
+
+ // promise[ done | fail | progress ] = list.add
+ promise[ tuple[1] ] = list.add;
+
+ // Handle state
+ if ( stateString ) {
+ list.add(function() {
+ // state = [ resolved | rejected ]
+ state = stateString;
+
+ // [ reject_list | resolve_list ].disable; progress_list.lock
+ }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
+ }
+
+ // deferred[ resolve | reject | notify ]
+ deferred[ tuple[0] ] = function() {
+ deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
+ return this;
+ };
+ deferred[ tuple[0] + "With" ] = list.fireWith;
+ });
+
+ // Make the deferred a promise
+ promise.promise( deferred );
+
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+
+ // All done!
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( subordinate /* , ..., subordinateN */ ) {
+ var i = 0,
+ resolveValues = slice.call( arguments ),
+ length = resolveValues.length,
+
+ // the count of uncompleted subordinates
+ remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
+
+ // the master Deferred. If resolveValues consist of only a single Deferred, just use that.
+ deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
+
+ // Update function for both resolve and progress values
+ updateFunc = function( i, contexts, values ) {
+ return function( value ) {
+ contexts[ i ] = this;
+ values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
+ if ( values === progressValues ) {
+ deferred.notifyWith( contexts, values );
+ } else if ( !( --remaining ) ) {
+ deferred.resolveWith( contexts, values );
+ }
+ };
+ },
+
+ progressValues, progressContexts, resolveContexts;
+
+ // Add listeners to Deferred subordinates; treat others as resolved
+ if ( length > 1 ) {
+ progressValues = new Array( length );
+ progressContexts = new Array( length );
+ resolveContexts = new Array( length );
+ for ( ; i < length; i++ ) {
+ if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
+ resolveValues[ i ].promise()
+ .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();
+ }
+});
+
+
+// The deferred used on DOM ready
+var readyList;
+
+jQuery.fn.ready = function( fn ) {
+ // Add the callback
+ jQuery.ready.promise().done( fn );
+
+ return this;
+};
+
+jQuery.extend({
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // A counter to track how many items to wait for before
+ // the ready event fires. See #6781
+ readyWait: 1,
+
+ // Hold (or release) the ready event
+ holdReady: function( hold ) {
+ if ( hold ) {
+ jQuery.readyWait++;
+ } else {
+ jQuery.ready( true );
+ }
+ },
+
+ // Handle when the DOM is ready
+ ready: function( wait ) {
+
+ // Abort if there are pending holds or we're already ready
+ if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
+ return;
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If a normal DOM Ready event fired, decrement, and wait if need be
+ if ( wait !== true && --jQuery.readyWait > 0 ) {
+ return;
+ }
+
+ // If there are functions bound, to execute
+ readyList.resolveWith( document, [ jQuery ] );
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.triggerHandler ) {
+ jQuery( document ).triggerHandler( "ready" );
+ jQuery( document ).off( "ready" );
+ }
+ }
+});
+
+/**
+ * The ready event handler and self cleanup method
+ */
+function completed() {
+ document.removeEventListener( "DOMContentLoaded", completed, false );
+ window.removeEventListener( "load", completed, false );
+ jQuery.ready();
+}
+
+jQuery.ready.promise = function( obj ) {
+ if ( !readyList ) {
+
+ readyList = jQuery.Deferred();
+
+ // Catch cases where $(document).ready() is called after the browser event has already occurred.
+ // 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 );
+};
+
+// Kick off the DOM ready check even if the user does not
+jQuery.ready.promise();
+
+
+
+
+// Multifunctional method to get and set values of a collection
+// The value/s can optionally be executed if it's a function
+var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
+ var i = 0,
+ len = 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 < len; i++ ) {
+ fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
+ }
+ }
+ }
+
+ return chainable ?
+ elems :
+
+ // Gets
+ bulk ?
+ fn.call( elems ) :
+ len ? fn( elems[0], key ) : emptyGet;
+};
+
+
+/**
+ * Determines whether an object can have data
+ */
+jQuery.acceptData = function( owner ) {
+ // Accepts only:
+ // - Node
+ // - Node.ELEMENT_NODE
+ // - Node.DOCUMENT_NODE
+ // - Object
+ // - Any
+ /* jshint -W018 */
+ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
+};
+
+
+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 + Data.uid++;
+}
+
+Data.uid = 1;
+Data.accepts = jQuery.acceptData;
+
+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( 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 ] ];
+ }
+ }
+};
+var data_priv = new Data();
+
+var data_user = new Data();
+
+
+
+// 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 rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
+ rmultiDash = /([A-Z])/g;
+
+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 ) ? jQuery.parseJSON( 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({
+ 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 i, name, data,
+ elem = this[ 0 ],
+ attrs = elem && elem.attributes;
+
+ // Gets all values
+ if ( key === undefined ) {
+ if ( this.length ) {
+ data = data_user.get( elem );
+
+ if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
+ i = attrs.length;
+ while ( i-- ) {
+
+ // Support: IE11+
+ // The attrs elements can be null (#14894)
+ if ( attrs[ i ] ) {
+ name = attrs[ i ].name;
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = jQuery.camelCase( name.slice(5) );
+ dataAttr( elem, name, data[ name ] );
+ }
+ }
+ }
+ 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 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 );
+ });
+ }
+});
+
+
+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 public - generate a queueHooks object, or return 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 );
+ });
+ },
+ 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 pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
+
+var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
+
+var isHidden = function( elem, el ) {
+ // isHidden might be called from jQuery#filter function;
+ // in that case, element will be second argument
+ elem = el || elem;
+ return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
+ };
+
+var rcheckableType = (/^(?:checkbox|radio)$/i);
+
+
+
+(function() {
+ var fragment = document.createDocumentFragment(),
+ div = fragment.appendChild( document.createElement( "div" ) ),
+ input = document.createElement( "input" );
+
+ // Support: Safari<=5.1
+ // Check state lost if the name is set (#11217)
+ // Support: Windows Web Apps (WWA)
+ // `name` and `type` must use .setAttribute for WWA (#14901)
+ input.setAttribute( "type", "radio" );
+ input.setAttribute( "checked", "checked" );
+ input.setAttribute( "name", "t" );
+
+ div.appendChild( input );
+
+ // Support: Safari<=5.1, Android<4.2
+ // Older WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+ // Support: IE<=11+
+ // Make sure textarea (and checkbox) defaultValue is properly cloned
+ div.innerHTML = "<textarea>x</textarea>";
+ support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
+})();
+var strundefined = typeof undefined;
+
+
+
+support.focusinBubbles = "onfocusin" in window;
+
+
+var
+ rkeyEvent = /^key/,
+ rmouseEvent = /^(?:mouse|pointer|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 !== strundefined && jQuery.event.triggered !== e.type ?
+ jQuery.event.dispatch.apply( elem, arguments ) : undefined;
+ };
+ }
+
+ // Handle multiple events separated by a space
+ types = ( types || "" ).match( rnotwhite ) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec( types[t] ) || [];
+ type = origType = tmp[1];
+ namespaces = ( tmp[2] || "" ).split( "." ).sort();
+
+ // There *must* be a type, no attaching namespace-only handlers
+ if ( !type ) {
+ continue;
+ }
+
+ // If event changes its type, use the special event handlers for the changed type
+ special = jQuery.event.special[ type ] || {};
+
+ // If selector defined, determine special event api type, otherwise given type
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+
+ // Update special based on newly reset type
+ special = jQuery.event.special[ type ] || {};
+
+ // handleObj is passed to all event handlers
+ handleObj = jQuery.extend({
+ type: type,
+ origType: origType,
+ data: data,
+ handler: handler,
+ guid: handler.guid,
+ selector: selector,
+ needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
+ namespace: namespaces.join(".")
+ }, handleObjIn );
+
+ // Init the event handler queue if we're the first
+ if ( !(handlers = events[ type ]) ) {
+ handlers = events[ type ] = [];
+ handlers.delegateCount = 0;
+
+ // Only use addEventListener 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;
+ }
+
+ },
+
+ // 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( 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 = hasOwn.call( event, "type" ) ? event.type : event,
+ namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
+
+ cur = tmp = elem = elem || document;
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // focus/blur morphs to focusin/out; ensure we're not firing them right now
+ if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
+ return;
+ }
+
+ if ( type.indexOf(".") >= 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 && handle.apply && jQuery.acceptData( cur ) ) {
+ event.result = handle.apply( cur, data );
+ if ( event.result === false ) {
+ event.preventDefault();
+ }
+ }
+ }
+ event.type = type;
+
+ // If nobody prevented the default action, do it now
+ if ( !onlyHandlers && !event.isDefaultPrevented() ) {
+
+ if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
+ 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 = 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 ) {
+ 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.defaultPrevented === undefined &&
+ // Support: Android<4.0
+ src.returnValue === false ?
+ returnTrue :
+ returnFalse;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // Put explicitly provided properties onto the event object
+ if ( props ) {
+ jQuery.extend( this, props );
+ }
+
+ // Create a timestamp if incoming event doesn't have one
+ this.timeStamp = src && src.timeStamp || jQuery.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+};
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ 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() {
+ var e = this.originalEvent;
+
+ this.isImmediatePropagationStopped = returnTrue;
+
+ if ( e && e.stopImmediatePropagation ) {
+ e.stopImmediatePropagation();
+ }
+
+ this.stopPropagation();
+ }
+};
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+// Support: Chrome 15+
+jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout",
+ pointerenter: "pointerover",
+ pointerleave: "pointerout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ delegateType: fix,
+ bindType: fix,
+
+ handle: function( event ) {
+ var ret,
+ target = this,
+ related = event.relatedTarget,
+ handleObj = event.handleObj;
+
+ // For 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;
+ }
+ };
+});
+
+// Support: Firefox, Chrome, Safari
+// Create "bubbling" focus and blur events
+if ( !support.focusinBubbles ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+ // Attach a single capturing handler on the document while someone wants focusin/focusout
+ var handler = function( event ) {
+ jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
+ };
+
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ var doc = this.ownerDocument || this,
+ attaches = data_priv.access( doc, fix );
+
+ if ( !attaches ) {
+ doc.addEventListener( orig, handler, true );
+ }
+ data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
+ },
+ teardown: function() {
+ var doc = this.ownerDocument || this,
+ attaches = data_priv.access( doc, fix ) - 1;
+
+ if ( !attaches ) {
+ doc.removeEventListener( orig, handler, true );
+ data_priv.remove( doc, fix );
+
+ } else {
+ data_priv.access( doc, fix, attaches );
+ }
+ }
+ };
+ });
+}
+
+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
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
+ rtagName = /<([\w:]+)/,
+ rhtml = /<|&#?\w+;/,
+ rnoInnerhtml = /<(?:script|style|link)/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: IE9
+ 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: IE9
+wrapMap.optgroup = wrapMap.option;
+
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+// Support: 1.x compatibility
+// Manipulating tables requires a tbody
+function manipulationTarget( elem, content ) {
+ return jQuery.nodeName( elem, "table" ) &&
+ jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
+
+ elem.getElementsByTagName("tbody")[0] ||
+ elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
+ elem;
+}
+
+// Replace/restore the type attribute of script elements for safe DOM manipulation
+function disableScript( elem ) {
+ elem.type = (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 i = 0,
+ l = elems.length;
+
+ 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;
+}
+
+// Fix IE bugs, see support tests
+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" && 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.extend({
+ clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+ var i, l, srcElements, destElements,
+ clone = elem.cloneNode( true ),
+ inPage = jQuery.contains( elem.ownerDocument, elem );
+
+ // Fix IE cloning issues
+ if ( !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,
+ fragment = context.createDocumentFragment(),
+ nodes = [],
+ i = 0,
+ l = elems.length;
+
+ for ( ; i < l; i++ ) {
+ elem = elems[ i ];
+
+ if ( elem || elem === 0 ) {
+
+ // Add nodes directly
+ if ( jQuery.type( elem ) === "object" ) {
+ // Support: QtWebKit, PhantomJS
+ // push.apply(_, arraylike) throws on ancient WebKit
+ 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, PhantomJS
+ // push.apply(_, arraylike) throws on ancient WebKit
+ jQuery.merge( nodes, tmp.childNodes );
+
+ // Remember the top-level container
+ tmp = fragment.firstChild;
+
+ // Ensure the created nodes are orphaned (#12392)
+ 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, type, key,
+ special = jQuery.event.special,
+ i = 0;
+
+ for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
+ if ( jQuery.acceptData( elem ) ) {
+ key = elem[ data_priv.expando ];
+
+ if ( key && (data = data_priv.cache[ key ]) ) {
+ if ( data.events ) {
+ for ( type in data.events ) {
+ if ( special[ type ] ) {
+ jQuery.event.remove( elem, type );
+
+ // This is a shortcut to avoid jQuery.event.remove's overhead
+ } else {
+ jQuery.removeEvent( elem, type, data.handle );
+ }
+ }
+ }
+ 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 ] ];
+ }
+ }
+});
+
+jQuery.fn.extend({
+ text: function( value ) {
+ return access( this, function( value ) {
+ return value === undefined ?
+ jQuery.text( this ) :
+ this.empty().each(function() {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ this.textContent = 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 );
+ }
+ });
+ },
+
+ remove: function( selector, keepData /* Internal Use Only */ ) {
+ 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 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 arg = arguments[ 0 ];
+
+ // Make the changes, replacing each context element with the new content
+ this.domManip( arguments, function( elem ) {
+ arg = this.parentNode;
+
+ jQuery.cleanData( getAll( this ) );
+
+ if ( arg ) {
+ arg.replaceChild( elem, this );
+ }
+ });
+
+ // Force removal if there was no new content (e.g., from empty arguments)
+ return arg && (arg.length || arg.nodeType) ? this : this.remove();
+ },
+
+ detach: function( selector ) {
+ return this.remove( selector, true );
+ },
+
+ domManip: function( args, callback ) {
+
+ // Flatten any nested arrays
+ args = 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" &&
+ !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 );
+ });
+ }
+
+ if ( l ) {
+ fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, 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 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 ) {
+ // Optional AJAX dependency, but won't run scripts if not present
+ if ( jQuery._evalUrl ) {
+ 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 push.apply(_, arraylike) throws
+ push.apply( ret, elems.get() );
+ }
+
+ return this.pushStack( ret );
+ };
+});
+
+
+var iframe,
+ elemdisplay = {};
+
+/**
+ * Retrieve the actual display of a element
+ * @param {String} name nodeName of the element
+ * @param {Object} doc Document object
+ */
+// Called only from within defaultDisplay
+function actualDisplay( name, doc ) {
+ var style,
+ elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
+
+ // getDefaultComputedStyle might be reliably used only on attached element
+ display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
+
+ // Use of this method is a temporary fix (more like optimization) until something better comes along,
+ // since it was removed from specification and supported only in FF
+ style.display : jQuery.css( elem[ 0 ], "display" );
+
+ // We don't have any data stored on the element,
+ // so use "detach" method as fast way to get rid of the element
+ elem.detach();
+
+ return display;
+}
+
+/**
+ * Try to determine the default display value of an element
+ * @param {String} nodeName
+ */
+function defaultDisplay( nodeName ) {
+ var doc = document,
+ display = elemdisplay[ nodeName ];
+
+ if ( !display ) {
+ display = actualDisplay( nodeName, doc );
+
+ // If the simple way fails, read from inside an iframe
+ if ( display === "none" || !display ) {
+
+ // Use the already-created iframe if possible
+ iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
+
+ // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
+ doc = iframe[ 0 ].contentDocument;
+
+ // Support: IE
+ doc.write();
+ doc.close();
+
+ display = actualDisplay( nodeName, doc );
+ iframe.detach();
+ }
+
+ // Store the correct default display
+ elemdisplay[ nodeName ] = display;
+ }
+
+ return display;
+}
+var rmargin = (/^margin/);
+
+var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
+
+var getStyles = function( elem ) {
+ // Support: IE<=11+, Firefox<=30+ (#15098, #14150)
+ // IE throws on elements created in popups
+ // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
+ if ( elem.ownerDocument.defaultView.opener ) {
+ return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
+ }
+
+ return window.getComputedStyle( elem, null );
+ };
+
+
+
+function curCSS( elem, name, computed ) {
+ var width, minWidth, maxWidth, ret,
+ style = elem.style;
+
+ computed = computed || getStyles( elem );
+
+ // Support: IE9
+ // getPropertyValue is only needed for .css('filter') (#12537)
+ if ( computed ) {
+ ret = computed.getPropertyValue( name ) || computed[ name ];
+ }
+
+ if ( computed ) {
+
+ if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
+ ret = jQuery.style( elem, name );
+ }
+
+ // Support: iOS < 6
+ // A tribute to the "awesome hack by Dean Edwards"
+ // iOS < 6 (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 !== undefined ?
+ // Support: IE
+ // IE returns zIndex value as an integer.
+ ret + "" :
+ ret;
+}
+
+
+function addGetHookIf( conditionFn, hookFn ) {
+ // Define the hook, we'll check on the first run if it's really needed.
+ return {
+ get: function() {
+ if ( conditionFn() ) {
+ // Hook not needed (or it's not possible to use it due
+ // to missing dependency), remove it.
+ delete this.get;
+ return;
+ }
+
+ // Hook needed; redefine it so that the support test is not executed again.
+ return (this.get = hookFn).apply( this, arguments );
+ }
+ };
+}
+
+
+(function() {
+ var pixelPositionVal, boxSizingReliableVal,
+ docElem = document.documentElement,
+ container = document.createElement( "div" ),
+ div = document.createElement( "div" );
+
+ if ( !div.style ) {
+ return;
+ }
+
+ // Support: IE9-11+
+ // Style of cloned element affects source element cloned (#8908)
+ div.style.backgroundClip = "content-box";
+ div.cloneNode( true ).style.backgroundClip = "";
+ support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+ container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
+ "position:absolute";
+ container.appendChild( div );
+
+ // Executing both pixelPosition & boxSizingReliable tests require only one layout
+ // so they're executed at the same time to save the second computation.
+ function computePixelPositionAndBoxSizingReliable() {
+ div.style.cssText =
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
+ "box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
+ "border:1px;padding:1px;width:4px;position:absolute";
+ div.innerHTML = "";
+ docElem.appendChild( container );
+
+ var divStyle = window.getComputedStyle( div, null );
+ pixelPositionVal = divStyle.top !== "1%";
+ boxSizingReliableVal = divStyle.width === "4px";
+
+ docElem.removeChild( container );
+ }
+
+ // Support: node.js jsdom
+ // Don't assume that getComputedStyle is a property of the global object
+ if ( window.getComputedStyle ) {
+ jQuery.extend( support, {
+ pixelPosition: function() {
+
+ // This test is executed only once but we still do memoizing
+ // since we can use the boxSizingReliable pre-computing.
+ // No need to check if the test was already performed, though.
+ computePixelPositionAndBoxSizingReliable();
+ return pixelPositionVal;
+ },
+ boxSizingReliable: function() {
+ if ( boxSizingReliableVal == null ) {
+ computePixelPositionAndBoxSizingReliable();
+ }
+ return boxSizingReliableVal;
+ },
+ reliableMarginRight: function() {
+
+ // 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
+ // This support function is only executed once so no memoizing is needed.
+ var ret,
+ marginDiv = div.appendChild( document.createElement( "div" ) );
+
+ // Reset CSS: box-sizing; display; margin; border; padding
+ marginDiv.style.cssText = div.style.cssText =
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
+ "box-sizing:content-box;display:block;margin:0;border:0;padding:0";
+ marginDiv.style.marginRight = marginDiv.style.width = "0";
+ div.style.width = "1px";
+ docElem.appendChild( container );
+
+ ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
+
+ docElem.removeChild( container );
+ div.removeChild( marginDiv );
+
+ return ret;
+ }
+ });
+ }
+})();
+
+
+// A method for quickly swapping in/out CSS properties to get correct calculations.
+jQuery.swap = function( elem, options, callback, args ) {
+ var ret, name,
+ old = {};
+
+ // Remember the old values, and insert the new ones
+ for ( name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ ret = callback.apply( elem, args || [] );
+
+ // Revert the old values
+ for ( name in options ) {
+ elem.style[ name ] = old[ name ];
+ }
+
+ return ret;
+};
+
+
+var
+ // Swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
+ // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
+ rdisplayswap = /^(none|table(?!-c[ea]).+)/,
+ rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
+ rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
+
+ cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+ cssNormalTransform = {
+ letterSpacing: "0",
+ fontWeight: "400"
+ },
+
+ 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[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 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.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;
+ }
+
+ // Check for style in case a browser which returns unreliable values
+ // for getComputedStyle silently falls back to the reliable elem.style
+ valueIsBorderBox = isBorderBox &&
+ ( support.boxSizingReliable() || val === elem.style[ name ] );
+
+ // Normalize "", auto, and prepare for extra
+ val = parseFloat( val ) || 0;
+ }
+
+ // Use the active box-sizing model to add/subtract irrelevant styles
+ return ( val +
+ augmentWidthOrHeight(
+ elem,
+ name,
+ extra || ( isBorderBox ? "border" : "content" ),
+ valueIsBorderBox,
+ styles
+ )
+ ) + "px";
+}
+
+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", defaultDisplay(elem.nodeName) );
+ }
+ } else {
+ hidden = isHidden( elem );
+
+ if ( 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.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,
+ "flexGrow": true,
+ "flexShrink": true,
+ "fontWeight": true,
+ "lineHeight": true,
+ "opacity": true,
+ "order": true,
+ "orphans": true,
+ "widows": true,
+ "zIndex": true,
+ "zoom": true
+ },
+
+ // Add in properties whose names you wish to fix before
+ // setting or getting the value
+ cssProps: {
+ "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, then unprefixed version
+ hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+ // Check if we're setting a value
+ if ( value !== undefined ) {
+ type = typeof value;
+
+ // Convert "+=" or "-=" to relative numbers (#7345)
+ if ( type === "string" && (ret = rrelNum.exec( value )) ) {
+ value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
+ // Fixes bug #9237
+ type = "number";
+ }
+
+ // Make sure that null and NaN values aren't set (#7116)
+ if ( value == null || value !== value ) {
+ return;
+ }
+
+ // If a number, add 'px' to the (except for certain CSS properties)
+ if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+ value += "px";
+ }
+
+ // Support: IE9-11+
+ // background-* props affect original clone's values
+ if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
+ style[ name ] = "inherit";
+ }
+
+ // If a hook was provided, use that value, otherwise just set the specified value
+ if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
+ 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 ) );
+
+ // Try prefixed name followed by the unprefixed name
+ 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 ];
+ }
+
+ // Make numeric 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;
+ }
+});
+
+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
+ // but it must have a current display style that would benefit
+ return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
+ 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.css( elem, "boxSizing", false, styles ) === "border-box",
+ styles
+ ) : 0
+ );
+ }
+ };
+});
+
+// Support: Android 2.3
+jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
+ function( elem, computed ) {
+ if ( computed ) {
+ return jQuery.swap( elem, { "display": "inline-block" },
+ curCSS, [ elem, "marginRight" ] );
+ }
+ }
+);
+
+// These hooks are used by animate to expand properties
+jQuery.each({
+ margin: "",
+ padding: "",
+ border: "Width"
+}, function( prefix, suffix ) {
+ jQuery.cssHooks[ prefix + suffix ] = {
+ expand: function( value ) {
+ var i = 0,
+ expanded = {},
+
+ // Assumes a single number if not a string
+ parts = typeof value === "string" ? value.split(" ") : [ value ];
+
+ for ( ; i < 4; i++ ) {
+ expanded[ prefix + cssExpand[ i ] + suffix ] =
+ parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
+ }
+
+ return expanded;
+ }
+ };
+
+ if ( !rmargin.test( prefix ) ) {
+ jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
+ }
+});
+
+jQuery.fn.extend({
+ css: function( name, value ) {
+ return access( this, function( elem, name, value ) {
+ var styles, len,
+ map = {},
+ i = 0;
+
+ if ( jQuery.isArray( name ) ) {
+ styles = getStyles( elem );
+ len = name.length;
+
+ for ( ; i < len; i++ ) {
+ map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
+ }
+
+ return map;
+ }
+
+ return value !== undefined ?
+ jQuery.style( elem, name, value ) :
+ jQuery.css( elem, name );
+ }, name, value, arguments.length > 1 );
+ },
+ show: function() {
+ return showHide( this, true );
+ },
+ hide: function() {
+ return showHide( this );
+ },
+ toggle: function( state ) {
+ if ( typeof state === "boolean" ) {
+ return state ? this.show() : this.hide();
+ }
+
+ return this.each(function() {
+ if ( isHidden( this ) ) {
+ jQuery( this ).show();
+ } else {
+ jQuery( this ).hide();
+ }
+ });
+ }
+});
+
+
+function Tween( elem, options, prop, end, easing ) {
+ return new Tween.prototype.init( elem, options, prop, end, easing );
+}
+jQuery.Tween = Tween;
+
+Tween.prototype = {
+ constructor: Tween,
+ init: function( elem, options, prop, end, easing, unit ) {
+ this.elem = elem;
+ this.prop = prop;
+ this.easing = easing || "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.
+ // 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 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.easing = {
+ linear: function( p ) {
+ return p;
+ },
+ swing: function( p ) {
+ return 0.5 - Math.cos( p * Math.PI ) / 2;
+ }
+};
+
+jQuery.fx = Tween.prototype.init;
+
+// Back Compat <1.8 extension point
+jQuery.fx.step = {};
+
+
+
+
+var
+ fxNow, timerId,
+ rfxtypes = /^(?:toggle|show|hide)$/,
+ rfxnum = new RegExp( "^(?:([+-])=|)(" + 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 string for doubling 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(),
+ // break 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() );
+}
+
+// Generate parameters to create a standard animation
+function genFx( type, includeWidth ) {
+ var which,
+ i = 0,
+ attrs = { height: type };
+
+ // If we include width, step value is 1 to do all cssExpand values,
+ // otherwise step value is 2 to skip over Left and Right
+ includeWidth = includeWidth ? 1 : 0;
+ for ( ; i < 4 ; i += 2 - includeWidth ) {
+ which = cssExpand[ i ];
+ attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
+ }
+
+ if ( includeWidth ) {
+ attrs.opacity = attrs.width = type;
+ }
+
+ return attrs;
+}
+
+function createTween( value, prop, animation ) {
+ var tween,
+ collection = ( 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 defaultPrefilter( elem, props, opts ) {
+ /* jshint validthis: true */
+ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
+ anim = this,
+ orig = {},
+ style = elem.style,
+ hidden = elem.nodeType && isHidden( elem ),
+ dataShow = 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() {
+ // Ensure the complete handler is 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
+ display = jQuery.css( elem, "display" );
+
+ // Test default display if display is currently "none"
+ checkDisplay = display === "none" ?
+ data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
+
+ if ( checkDisplay === "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 );
+
+ // Any non-fx value stops us from restoring the original display value
+ } else {
+ display = undefined;
+ }
+ }
+
+ if ( !jQuery.isEmptyObject( orig ) ) {
+ if ( dataShow ) {
+ if ( "hidden" in dataShow ) {
+ hidden = dataShow.hidden;
+ }
+ } else {
+ dataShow = 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;
+ }
+ }
+ }
+
+ // If this is a noop like .hide().hide(), restore an overwritten display value
+ } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
+ style.display = display;
+ }
+}
+
+function propFilter( props, specialEasing ) {
+ var index, name, easing, value, hooks;
+
+ // camelCase, specialEasing and expand cssHook pass
+ for ( index in props ) {
+ name = jQuery.camelCase( index );
+ easing = specialEasing[ name ];
+ value = props[ index ];
+ if ( jQuery.isArray( value ) ) {
+ easing = value[ 1 ];
+ value = props[ index ] = value[ 0 ];
+ }
+
+ if ( index !== name ) {
+ props[ name ] = value;
+ delete props[ index ];
+ }
+
+ hooks = jQuery.cssHooks[ name ];
+ if ( hooks && "expand" in hooks ) {
+ value = hooks.expand( value );
+ delete props[ name ];
+
+ // Not quite $.extend, this won't overwrite existing keys.
+ // Reusing 'index' because we have the correct "name"
+ for ( index in value ) {
+ if ( !( index in props ) ) {
+ props[ index ] = value[ index ];
+ specialEasing[ index ] = easing;
+ }
+ }
+ } else {
+ specialEasing[ name ] = easing;
+ }
+ }
+}
+
+function Animation( elem, properties, options ) {
+ var result,
+ stopped,
+ index = 0,
+ length = 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 ),
+ // Support: Android 2.3
+ // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
+ temp = remaining / animation.duration || 0,
+ percent = 1 - temp,
+ index = 0,
+ length = animation.tweens.length;
+
+ for ( ; index < length ; index++ ) {
+ animation.tweens[ index ].run( percent );
+ }
+
+ deferred.notifyWith( elem, [ animation, percent, remaining ]);
+
+ if ( percent < 1 && length ) {
+ return remaining;
+ } else {
+ deferred.resolveWith( elem, [ animation ] );
+ return false;
+ }
+ },
+ animation = deferred.promise({
+ elem: elem,
+ props: jQuery.extend( {}, properties ),
+ opts: jQuery.extend( true, { specialEasing: {} }, 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 );
+}
+
+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 );
+ }
+ }
+});
+
+jQuery.speed = function( speed, easing, fn ) {
+ var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
+ };
+
+ opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+ opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
+
+ // Normalize opt.queue - true/undefined/null -> "fx"
+ if ( opt.queue == null || opt.queue === true ) {
+ opt.queue = "fx";
+ }
+
+ // Queueing
+ opt.old = opt.complete;
+
+ opt.complete = function() {
+ if ( jQuery.isFunction( opt.old ) ) {
+ opt.old.call( this );
+ }
+
+ if ( opt.queue ) {
+ jQuery.dequeue( this, opt.queue );
+ }
+ };
+
+ return opt;
+};
+
+jQuery.fn.extend({
+ fadeTo: function( speed, to, easing, callback ) {
+
+ // Show any hidden elements after setting opacity to 0
+ return this.filter( isHidden ).css( "opacity", 0 ).show()
+
+ // Animate to the value specified
+ .end().animate({ opacity: to }, speed, easing, callback );
+ },
+ animate: function( prop, speed, easing, callback ) {
+ var empty = jQuery.isEmptyObject( prop ),
+ optall = jQuery.speed( speed, easing, callback ),
+ doAnimation = function() {
+ // Operate on a copy of prop so per-property easing won't be lost
+ var anim = Animation( this, jQuery.extend( {}, prop ), optall );
+
+ // Empty animations, or finishing resolves immediately
+ if ( empty || 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;
+ });
+ }
+});
+
+jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
+ var cssFn = jQuery.fn[ name ];
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return speed == null || typeof speed === "boolean" ?
+ cssFn.apply( this, arguments ) :
+ this.animate( genFx( name, true ), speed, easing, callback );
+ };
+});
+
+// Generate shortcuts for custom animations
+jQuery.each({
+ slideDown: genFx("show"),
+ slideUp: genFx("hide"),
+ slideToggle: genFx("toggle"),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" },
+ fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return this.animate( props, speed, easing, callback );
+ };
+});
+
+jQuery.timers = [];
+jQuery.fx.tick = function() {
+ var timer,
+ i = 0,
+ timers = jQuery.timers;
+
+ fxNow = jQuery.now();
+
+ for ( ; i < timers.length; i++ ) {
+ timer = timers[ i ];
+ // Checks the timer has not already been removed
+ if ( !timer() && timers[ i ] === timer ) {
+ timers.splice( i--, 1 );
+ }
+ }
+
+ if ( !timers.length ) {
+ jQuery.fx.stop();
+ }
+ fxNow = undefined;
+};
+
+jQuery.fx.timer = function( timer ) {
+ jQuery.timers.push( timer );
+ if ( timer() ) {
+ jQuery.fx.start();
+ } else {
+ jQuery.timers.pop();
+ }
+};
+
+jQuery.fx.interval = 13;
+
+jQuery.fx.start = function() {
+ if ( !timerId ) {
+ timerId = 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
+};
+
+
+// Based off of the plugin by Clint Helfers, with permission.
+// http://blindsignals.com/index.php/2009/07/jquery-delay/
+jQuery.fn.delay = function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function( next, hooks ) {
+ var timeout = setTimeout( next, time );
+ hooks.stop = function() {
+ clearTimeout( timeout );
+ };
+ });
+};
+
+
+(function() {
+ var input = document.createElement( "input" ),
+ select = document.createElement( "select" ),
+ opt = select.appendChild( document.createElement( "option" ) );
+
+ input.type = "checkbox";
+
+ // Support: iOS<=5.1, Android<=4.2+
+ // Default value for a checkbox should be "on"
+ support.checkOn = input.value !== "";
+
+ // Support: IE<=11+
+ // Must access selectedIndex to make default options select
+ support.optSelected = opt.selected;
+
+ // Support: Android<=2.3
+ // Options inside disabled selects are incorrectly marked as disabled
+ select.disabled = true;
+ support.optDisabled = !opt.disabled;
+
+ // Support: IE<=11+
+ // An input loses its value after becoming a radio
+ input = document.createElement( "input" );
+ input.value = "t";
+ input.type = "radio";
+ support.radioValue = input.value === "t";
+})();
+
+
+var nodeHook, boolHook,
+ attrHandle = jQuery.expr.attrHandle;
+
+jQuery.fn.extend({
+ attr: function( name, value ) {
+ return access( this, jQuery.attr, name, value, arguments.length > 1 );
+ },
+
+ removeAttr: function( name ) {
+ return this.each(function() {
+ jQuery.removeAttr( this, name );
+ });
+ }
+});
+
+jQuery.extend({
+ attr: function( elem, name, value ) {
+ var 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 === 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( 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 ( !support.radioValue && value === "radio" &&
+ jQuery.nodeName( elem, "input" ) ) {
+ var val = elem.value;
+ elem.setAttribute( "type", value );
+ if ( val ) {
+ elem.value = val;
+ }
+ return value;
+ }
+ }
+ }
+ }
+});
+
+// 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 = attrHandle[ name ] || jQuery.find.attr;
+
+ attrHandle[ name ] = function( elem, name, isXML ) {
+ var ret, handle;
+ if ( !isXML ) {
+ // Avoid an infinite loop by temporarily removing this function from the getter
+ handle = attrHandle[ name ];
+ attrHandle[ name ] = ret;
+ ret = getter( elem, name, isXML ) != null ?
+ name.toLowerCase() :
+ null;
+ attrHandle[ name ] = handle;
+ }
+ return ret;
+ };
+});
+
+
+
+
+var rfocusable = /^(?:input|select|textarea|button)$/i;
+
+jQuery.fn.extend({
+ prop: function( name, value ) {
+ return access( this, jQuery.prop, name, value, arguments.length > 1 );
+ },
+
+ removeProp: function( name ) {
+ return this.each(function() {
+ delete this[ jQuery.propFix[ name ] || name ];
+ });
+ }
+});
+
+jQuery.extend({
+ 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;
+ }
+ }
+ }
+});
+
+if ( !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;
+});
+
+
+
+
+var rclass = /[\t\r\n\f]/g;
+
+jQuery.fn.extend({
+ addClass: function( value ) {
+ var classes, elem, cur, clazz, j, finalValue,
+ proceed = typeof value === "string" && value,
+ i = 0,
+ len = this.length;
+
+ 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( 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 + " ";
+ }
+ }
+
+ // only assign if different to avoid unneeded rendering.
+ finalValue = jQuery.trim( cur );
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ var classes, elem, cur, clazz, j, finalValue,
+ proceed = arguments.length === 0 || typeof value === "string" && value,
+ i = 0,
+ len = this.length;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).removeClass( value.call( this, j, this.className ) );
+ });
+ }
+ if ( proceed ) {
+ classes = ( value || "" ).match( 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 + " ", " " );
+ }
+ }
+
+ // Only assign if different to avoid unneeded rendering.
+ finalValue = value ? jQuery.trim( cur ) : "";
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value;
+
+ if ( typeof stateVal === "boolean" && type === "string" ) {
+ return stateVal ? this.addClass( value ) : this.removeClass( value );
+ }
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( i ) {
+ jQuery( this ).toggleClass( value.call(this, i, 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( 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 === 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;
+ }
+});
+
+
+
+
+var rreturn = /\r/g;
+
+jQuery.fn.extend({
+ val: function( value ) {
+ var hooks, ret, isFunction,
+ elem = this[0];
+
+ if ( !arguments.length ) {
+ if ( elem ) {
+ hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
+
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
+ return ret;
+ }
+
+ ret = elem.value;
+
+ return typeof ret === "string" ?
+ // Handle most common string cases
+ ret.replace(rreturn, "") :
+ // Handle cases where value is null/undef or number
+ ret == null ? "" : ret;
+ }
+
+ return;
+ }
+
+ isFunction = jQuery.isFunction( value );
+
+ return this.each(function( i ) {
+ var val;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call( this, i, jQuery( this ).val() );
+ } else {
+ val = value;
+ }
+
+ // Treat null/undefined as ""; convert numbers to string
+ if ( val == null ) {
+ val = "";
+
+ } else if ( typeof val === "number" ) {
+ val += "";
+
+ } else if ( jQuery.isArray( val ) ) {
+ val = jQuery.map( val, function( value ) {
+ return value == null ? "" : value + "";
+ });
+ }
+
+ hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
+
+ // If set returns undefined, fall back to normal setting
+ if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
+ this.value = val;
+ }
+ });
+ }
+});
+
+jQuery.extend({
+ valHooks: {
+ option: {
+ get: function( elem ) {
+ var val = jQuery.find.attr( elem, "value" );
+ return val != null ?
+ val :
+ // Support: IE10-11+
+ // option.text throws exceptions (#14686, #14858)
+ jQuery.trim( jQuery.text( elem ) );
+ }
+ },
+ 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
+ ( 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( option.value, values ) >= 0) ) {
+ optionSet = true;
+ }
+ }
+
+ // Force browsers to behave consistently when non-matching value is set
+ if ( !optionSet ) {
+ elem.selectedIndex = -1;
+ }
+ return values;
+ }
+ }
+ }
+});
+
+// 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 ( !support.checkOn ) {
+ jQuery.valHooks[ this ].get = function( elem ) {
+ return elem.getAttribute("value") === null ? "on" : elem.value;
+ };
+ }
+});
+
+
+
+
+// Return jQuery for attributes-only inclusion
+
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( data, fn ) {
+ return arguments.length > 0 ?
+ this.on( name, null, data, fn ) :
+ this.trigger( name );
+ };
+});
+
+jQuery.fn.extend({
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ },
+
+ 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 nonce = jQuery.now();
+
+var rquery = (/\?/);
+
+
+
+// Support: Android 2.3
+// Workaround failure to string-cast null input
+jQuery.parseJSON = function( data ) {
+ return JSON.parse( data + "" );
+};
+
+
+// Cross-browser xml parsing
+jQuery.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;
+};
+
+
+var
+ 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+)|)|)/,
+
+ /* Prefilters
+ * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+ * 2) These are called:
+ * - BEFORE asking for a transport
+ * - AFTER param serialization (s.data is a string if s.processData is true)
+ * 3) key is the dataType
+ * 4) the catchall symbol "*" can be used
+ * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+ */
+ prefilters = {},
+
+ /* Transports bindings
+ * 1) key is the dataType
+ * 2) the catchall symbol "*" can be used
+ * 3) selection will start with transport dataType and THEN go to "*" if needed
+ */
+ transports = {},
+
+ // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
+ allTypes = "*/".concat( "*" ),
+
+ // Document location
+ ajaxLocation = window.location.href,
+
+ // Segment location into parts
+ ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+ // dataTypeExpression is optional and defaults to "*"
+ return function( dataTypeExpression, func ) {
+
+ if ( typeof dataTypeExpression !== "string" ) {
+ func = dataTypeExpression;
+ dataTypeExpression = "*";
+ }
+
+ var dataType,
+ i = 0,
+ dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
+
+ if ( jQuery.isFunction( func ) ) {
+ // For each dataType in the dataTypeExpression
+ while ( (dataType = dataTypes[i++]) ) {
+ // Prepend if requested
+ if ( dataType[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;
+}
+
+/* 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 };
+}
+
+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( rnotwhite ) || [ "" ];
+
+ // A cross-domain request is in order when we have a protocol:host:port mismatch
+ if ( s.crossDomain == null ) {
+ parts = rurl.exec( s.url.toLowerCase() );
+ s.crossDomain = !!( parts &&
+ ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
+ ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
+ ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
+ );
+ }
+
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
+ }
+
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
+
+ // If request was aborted inside a prefilter, stop there
+ if ( state === 2 ) {
+ return jqXHR;
+ }
+
+ // We can fire global events as of now if asked to
+ // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
+ fireGlobals = jQuery.event && s.global;
+
+ // Watch for a new set of requests
+ if ( fireGlobals && jQuery.active++ === 0 ) {
+ jQuery.event.trigger("ajaxStart");
+ }
+
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
+
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
+
+ // Save the URL in case we're toying with the If-Modified-Since
+ // and/or If-None-Match header later on
+ cacheURL = s.url;
+
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
+
+ // If data is available, append data to url
+ if ( s.data ) {
+ cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
+ // #9682: remove data so that it's not used in an eventual retry
+ delete s.data;
+ }
+
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
+ s.url = rts.test( cacheURL ) ?
+
+ // If there is already a '_' parameter, set its value
+ cacheURL.replace( rts, "$1_=" + nonce++ ) :
+
+ // Otherwise add one to the end
+ cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
+ }
+ }
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
+ }
+ if ( jQuery.etag[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
+ }
+ }
+
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ jqXHR.setRequestHeader( "Content-Type", s.contentType );
+ }
+
+ // Set the Accepts header for the server, depending on the dataType
+ jqXHR.setRequestHeader(
+ "Accept",
+ s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+ s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+ s.accepts[ "*" ]
+ );
+
+ // Check for headers option
+ for ( i in s.headers ) {
+ jqXHR.setRequestHeader( i, s.headers[ i ] );
+ }
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
+ // Abort if not done already and return
+ return jqXHR.abort();
+ }
+
+ // Aborting is no longer a cancellation
+ strAbort = "abort";
+
+ // Install callbacks on deferreds
+ for ( i in { success: 1, error: 1, complete: 1 } ) {
+ jqXHR[ i ]( s[ i ] );
+ }
+
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
+
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ jqXHR.readyState = 1;
+
+ // Send global event
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
+ }
+ // 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 {
+ // Extract error from statusText and normalize 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
+ });
+ };
+});
+
+
+jQuery._evalUrl = function( url ) {
+ return jQuery.ajax({
+ url: url,
+ type: "GET",
+ dataType: "script",
+ async: false,
+ global: false,
+ "throws": true
+ });
+};
+
+
+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();
+ }
+});
+
+
+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 );
+};
+
+
+
+
+var r20 = /%20/g,
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+ rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+function buildParams( prefix, obj, traditional, add ) {
+ var name;
+
+ if ( jQuery.isArray( obj ) ) {
+ // Serialize array item.
+ jQuery.each( obj, function( i, v ) {
+ if ( traditional || rbracket.test( prefix ) ) {
+ // Treat each array item as a scalar.
+ add( prefix, v );
+
+ } else {
+ // Item is non-scalar (array or object), encode its numeric index.
+ buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
+ }
+ });
+
+ } else if ( !traditional && jQuery.type( obj ) === "object" ) {
+ // Serialize object item.
+ for ( name in obj ) {
+ buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
+ }
+
+ } else {
+ // Serialize scalar item.
+ add( prefix, obj );
+ }
+}
+
+// Serialize an array of form elements or a set of
+// key/values into a query string
+jQuery.param = function( a, traditional ) {
+ var prefix,
+ s = [],
+ add = function( key, value ) {
+ // If value is a function, invoke it and return its value
+ value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
+ s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
+ };
+
+ // Set traditional to true for jQuery <= 1.3.2 behavior.
+ if ( traditional === undefined ) {
+ traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
+ }
+
+ // If an array was passed in, assume that it is an array of form elements.
+ if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
+ // Serialize the form elements
+ jQuery.each( a, function() {
+ add( this.name, this.value );
+ });
+
+ } else {
+ // If traditional, encode the "old" way (the way 1.3.2 or older
+ // did it), otherwise encode params recursively.
+ for ( prefix in a ) {
+ buildParams( prefix, a[ prefix ], traditional, add );
+ }
+ }
+
+ // Return the resulting serialization
+ return s.join( "&" ).replace( r20, "+" );
+};
+
+jQuery.fn.extend({
+ serialize: function() {
+ return jQuery.param( this.serializeArray() );
+ },
+ serializeArray: function() {
+ return this.map(function() {
+ // Can add propHook for "elements" to filter or add form elements
+ var elements = jQuery.prop( this, "elements" );
+ return elements ? jQuery.makeArray( elements ) : this;
+ })
+ .filter(function() {
+ var type = this.type;
+
+ // Use .is( ":disabled" ) so that fieldset[disabled] works
+ return this.name && !jQuery( this ).is( ":disabled" ) &&
+ rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
+ ( this.checked || !rcheckableType.test( type ) );
+ })
+ .map(function( i, elem ) {
+ var val = jQuery( this ).val();
+
+ return val == null ?
+ null :
+ jQuery.isArray( val ) ?
+ jQuery.map( val, function( val ) {
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }) :
+ { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }).get();
+ }
+});
+
+
+jQuery.ajaxSettings.xhr = function() {
+ try {
+ return new XMLHttpRequest();
+ } catch( e ) {}
+};
+
+var xhrId = 0,
+ xhrCallbacks = {},
+ 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
+ },
+ xhrSupported = jQuery.ajaxSettings.xhr();
+
+// Support: IE9
+// Open requests must be manually aborted on unload (#5280)
+// See https://support.microsoft.com/kb/2856746 for more info
+if ( window.attachEvent ) {
+ window.attachEvent( "onunload", function() {
+ for ( var key in xhrCallbacks ) {
+ xhrCallbacks[ key ]();
+ }
+ });
+}
+
+support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+support.ajax = xhrSupported = !!xhrSupported;
+
+jQuery.ajaxTransport(function( options ) {
+ var callback;
+
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( support.cors || xhrSupported && !options.crossDomain ) {
+ return {
+ send: function( headers, complete ) {
+ var i,
+ xhr = options.xhr(),
+ id = ++xhrId;
+
+ 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; see #8605, #14207
+ xhr.status,
+ xhr.statusText
+ );
+ } else {
+ complete(
+ xhrSuccessStatus[ xhr.status ] || xhr.status,
+ xhr.statusText,
+ // Support: IE9
+ // Accessing binary-data responseText throws an exception
+ // (#11426)
+ 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 ] = callback("abort");
+
+ try {
+ // Do send the request (this may raise an exception)
+ xhr.send( options.hasContent && options.data || null );
+ } catch ( e ) {
+ // #14683: Only rethrow if this hasn't been notified as an error yet
+ if ( callback ) {
+ throw e;
+ }
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback();
+ }
+ }
+ };
+ }
+});
+
+
+
+
+// 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 + "_" + ( 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 += ( 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";
+ }
+});
+
+
+
+
+// data: string of html
+// context (optional): If specified, the fragment will be created in this context, defaults to document
+// keepScripts (optional): If true, will include scripts passed in the html string
+jQuery.parseHTML = function( data, context, keepScripts ) {
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+ if ( typeof context === "boolean" ) {
+ keepScripts = context;
+ context = false;
+ }
+ context = context || document;
+
+ var parsed = rsingleTag.exec( data ),
+ scripts = !keepScripts && [];
+
+ // Single tag
+ if ( parsed ) {
+ return [ context.createElement( parsed[1] ) ];
+ }
+
+ parsed = jQuery.buildFragment( [ data ], context, scripts );
+
+ if ( scripts && scripts.length ) {
+ jQuery( scripts ).remove();
+ }
+
+ return jQuery.merge( [], parsed.childNodes );
+};
+
+
+// Keep a copy of the old load method
+var _load = jQuery.fn.load;
+
+/**
+ * Load a url into a page
+ */
+jQuery.fn.load = function( url, params, callback ) {
+ if ( typeof url !== "string" && _load ) {
+ return _load.apply( this, arguments );
+ }
+
+ var selector, type, response,
+ self = this,
+ off = url.indexOf(" ");
+
+ if ( off >= 0 ) {
+ selector = jQuery.trim( 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.expr.filters.animated = function( elem ) {
+ return jQuery.grep(jQuery.timers, function( fn ) {
+ return elem === fn.elem;
+ }).length;
+};
+
+
+
+
+var docElem = window.document.documentElement;
+
+/**
+ * Gets a window from an element
+ */
+function getWindow( elem ) {
+ return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
+}
+
+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({
+ 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;
+ }
+
+ // Support: BlackBerry 5, iOS 3 (original iPhone)
+ // If we don't have gBCR, just use 0,0 rather than error
+ if ( typeof elem.getBoundingClientRect !== strundefined ) {
+ box = elem.getBoundingClientRect();
+ }
+ win = getWindow( doc );
+ return {
+ top: box.top + win.pageYOffset - docElem.clientTop,
+ left: box.left + win.pageXOffset - docElem.clientLeft
+ };
+ },
+
+ 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 its only offset parent
+ if ( jQuery.css( elem, "position" ) === "fixed" ) {
+ // Assume getBoundingClientRect is there 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 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 );
+ };
+});
+
+// Support: Safari<7+, Chrome<37+
+// Add the top/left cssHooks using jQuery.fn.position
+// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
+// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
+// getComputedStyle returns percent when specified for top/left/bottom/right;
+// rather than make the css module depend on the offset module, just check for it here
+jQuery.each( [ "top", "left" ], function( i, prop ) {
+ jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
+ function( elem, computed ) {
+ if ( computed ) {
+ computed = curCSS( elem, prop );
+ // If curCSS returns percentage, fallback to offset
+ return rnumnonpx.test( computed ) ?
+ jQuery( elem ).position()[ prop ] + "px" :
+ computed;
+ }
+ }
+ );
+});
+
+
+// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
+jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
+ jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
+ // Margin is only for outerHeight, outerWidth
+ jQuery.fn[ funcName ] = function( margin, value ) {
+ var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
+ extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
+
+ return access( this, function( elem, type, value ) {
+ var doc;
+
+ if ( jQuery.isWindow( elem ) ) {
+ // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
+ // isn't a whole lot we can do. See pull request at this URL for discussion:
+ // https://github.com/jquery/jquery/pull/764
+ return elem.document.documentElement[ "client" + name ];
+ }
+
+ // Get document width or height
+ if ( elem.nodeType === 9 ) {
+ doc = elem.documentElement;
+
+ // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
+ // whichever is greatest
+ 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 );
+ };
+ });
+});
+
+
+// The number of elements contained in the matched element set
+jQuery.fn.size = function() {
+ return this.length;
+};
+
+jQuery.fn.andSelf = jQuery.fn.addBack;
+
+
+
+
+// Register as a named AMD module, since jQuery can be concatenated with other
+// files that may use define, but not via a proper concatenation script that
+// understands anonymous AMD modules. A named AMD is safest and most robust
+// way to register. Lowercase jquery is used because AMD module names are
+// derived from file names, and jQuery is normally delivered in a lowercase
+// file name. Do this after creating the global so that if an AMD module wants
+// to call noConflict to hide this version of jQuery, it will work.
+
+// Note that for maximum portability, libraries that are not jQuery should
+// declare themselves as anonymous modules, and avoid setting a global if an
+// AMD loader is present. jQuery is a special case. For more information, see
+// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
+
+if ( typeof define === "function" && define.amd ) {
+ define( "jquery", [], function() {
+ return jQuery;
+ });
+}
+
+
+
+
+var
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+
+ // Map over the $ in case of overwrite
+ _$ = window.$;
+
+jQuery.noConflict = function( deep ) {
+ if ( window.$ === jQuery ) {
+ window.$ = _$;
+ }
+
+ if ( deep && window.jQuery === jQuery ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+};
+
+// Expose jQuery and $ identifiers, even in AMD
+// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
+// and CommonJS for browser emulators (#13566)
+if ( typeof noGlobal === strundefined ) {
+ window.jQuery = window.$ = jQuery;
+}
+
+
+
+
+return jQuery;
+
+}));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/paper/paper-full.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,12881 @@
+/*!
+ * Paper.js v0.9.21 - The Swiss Army Knife of Vector Graphics Scripting.
+ * http://paperjs.org/
+ *
+ * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey
+ * http://scratchdisk.com/ & http://jonathanpuckey.com/
+ *
+ * Distributed under the MIT license. See LICENSE file for details.
+ *
+ * All rights reserved.
+ *
+ * Date: Sat Nov 22 09:01:01 2014 -0800
+ *
+ ***
+ *
+ * Straps.js - Class inheritance library with support for bean-style accessors
+ *
+ * Copyright (c) 2006 - 2013 Juerg Lehni
+ * http://scratchdisk.com/
+ *
+ * Distributed under the MIT license.
+ *
+ ***
+ *
+ * Acorn.js
+ * http://marijnhaverbeke.nl/acorn/
+ *
+ * Acorn is a tiny, fast JavaScript parser written in JavaScript,
+ * created by Marijn Haverbeke and released under an MIT license.
+ *
+ */
+
+var paper = new function(undefined) {
+
+var Base = new function() {
+ var hidden = /^(statics|enumerable|beans|preserve)$/,
+
+ forEach = [].forEach || function(iter, bind) {
+ for (var i = 0, l = this.length; i < l; i++)
+ iter.call(bind, this[i], i, this);
+ },
+
+ forIn = function(iter, bind) {
+ for (var i in this)
+ if (this.hasOwnProperty(i))
+ iter.call(bind, this[i], i, this);
+ },
+
+ create = Object.create || function(proto) {
+ return { __proto__: proto };
+ },
+
+ describe = Object.getOwnPropertyDescriptor || function(obj, name) {
+ var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);
+ return get
+ ? { get: get, set: obj.__lookupSetter__(name),
+ enumerable: true, configurable: true }
+ : obj.hasOwnProperty(name)
+ ? { value: obj[name], enumerable: true,
+ configurable: true, writable: true }
+ : null;
+ },
+
+ _define = Object.defineProperty || function(obj, name, desc) {
+ if ((desc.get || desc.set) && obj.__defineGetter__) {
+ if (desc.get)
+ obj.__defineGetter__(name, desc.get);
+ if (desc.set)
+ obj.__defineSetter__(name, desc.set);
+ } else {
+ obj[name] = desc.value;
+ }
+ return obj;
+ },
+
+ define = function(obj, name, desc) {
+ delete obj[name];
+ return _define(obj, name, desc);
+ };
+
+ function inject(dest, src, enumerable, beans, preserve) {
+ var beansNames = {};
+
+ function field(name, val) {
+ val = val || (val = describe(src, name))
+ && (val.get ? val : val.value);
+ if (typeof val === 'string' && val[0] === '#')
+ val = dest[val.substring(1)] || val;
+ var isFunc = typeof val === 'function',
+ res = val,
+ prev = preserve || isFunc
+ ? (val && val.get ? name in dest : dest[name])
+ : null,
+ bean;
+ if (!preserve || !prev) {
+ if (isFunc && prev)
+ val.base = prev;
+ if (isFunc && beans !== false
+ && (bean = name.match(/^([gs]et|is)(([A-Z])(.*))$/)))
+ beansNames[bean[3].toLowerCase() + bean[4]] = bean[2];
+ if (!res || isFunc || !res.get || typeof res.get !== 'function'
+ || !Base.isPlainObject(res))
+ res = { value: res, writable: true };
+ if ((describe(dest, name)
+ || { configurable: true }).configurable) {
+ res.configurable = true;
+ res.enumerable = enumerable;
+ }
+ define(dest, name, res);
+ }
+ }
+ if (src) {
+ for (var name in src) {
+ if (src.hasOwnProperty(name) && !hidden.test(name))
+ field(name);
+ }
+ for (var name in beansNames) {
+ var part = beansNames[name],
+ set = dest['set' + part],
+ get = dest['get' + part] || set && dest['is' + part];
+ if (get && (beans === true || get.length === 0))
+ field(name, { get: get, set: set });
+ }
+ }
+ return dest;
+ }
+
+ function each(obj, iter, bind) {
+ if (obj)
+ ('length' in obj && !obj.getLength
+ && typeof obj.length === 'number'
+ ? forEach
+ : forIn).call(obj, iter, bind = bind || obj);
+ return bind;
+ }
+
+ function set(obj, props, exclude) {
+ for (var key in props)
+ if (props.hasOwnProperty(key) && !(exclude && exclude[key]))
+ obj[key] = props[key];
+ return obj;
+ }
+
+ return inject(function Base() {
+ for (var i = 0, l = arguments.length; i < l; i++)
+ set(this, arguments[i]);
+ }, {
+ inject: function(src) {
+ if (src) {
+ var statics = src.statics === true ? src : src.statics,
+ beans = src.beans,
+ preserve = src.preserve;
+ if (statics !== src)
+ inject(this.prototype, src, src.enumerable, beans, preserve);
+ inject(this, statics, true, beans, preserve);
+ }
+ for (var i = 1, l = arguments.length; i < l; i++)
+ this.inject(arguments[i]);
+ return this;
+ },
+
+ extend: function() {
+ var base = this,
+ ctor;
+ for (var i = 0, l = arguments.length; i < l; i++)
+ if (ctor = arguments[i].initialize)
+ break;
+ ctor = ctor || function() {
+ base.apply(this, arguments);
+ };
+ ctor.prototype = create(this.prototype);
+ ctor.base = base;
+ define(ctor.prototype, 'constructor',
+ { value: ctor, writable: true, configurable: true });
+ inject(ctor, this, true);
+ return arguments.length ? this.inject.apply(ctor, arguments) : ctor;
+ }
+ }, true).inject({
+ inject: function() {
+ for (var i = 0, l = arguments.length; i < l; i++) {
+ var src = arguments[i];
+ if (src)
+ inject(this, src, src.enumerable, src.beans, src.preserve);
+ }
+ return this;
+ },
+
+ extend: function() {
+ var res = create(this);
+ return res.inject.apply(res, arguments);
+ },
+
+ each: function(iter, bind) {
+ return each(this, iter, bind);
+ },
+
+ set: function(props) {
+ return set(this, props);
+ },
+
+ clone: function() {
+ return new this.constructor(this);
+ },
+
+ statics: {
+ each: each,
+ create: create,
+ define: define,
+ describe: describe,
+ set: set,
+
+ clone: function(obj) {
+ return set(new obj.constructor(), obj);
+ },
+
+ isPlainObject: function(obj) {
+ var ctor = obj != null && obj.constructor;
+ return ctor && (ctor === Object || ctor === Base
+ || ctor.name === 'Object');
+ },
+
+ pick: function() {
+ for (var i = 0, l = arguments.length; i < l; i++)
+ if (arguments[i] !== undefined)
+ return arguments[i];
+ }
+ }
+ });
+};
+
+if (typeof module !== 'undefined')
+ module.exports = Base;
+
+if (!Array.isArray) {
+ Array.isArray = function(obj) {
+ return Object.prototype.toString.call(obj) === '[object Array]';
+ };
+}
+
+if (!document.head) {
+ document.head = document.getElementsByTagName('head')[0];
+}
+
+Base.inject({
+ toString: function() {
+ return this._id != null
+ ? (this._class || 'Object') + (this._name
+ ? " '" + this._name + "'"
+ : ' @' + this._id)
+ : '{ ' + Base.each(this, function(value, key) {
+ if (!/^_/.test(key)) {
+ var type = typeof value;
+ this.push(key + ': ' + (type === 'number'
+ ? Formatter.instance.number(value)
+ : type === 'string' ? "'" + value + "'" : value));
+ }
+ }, []).join(', ') + ' }';
+ },
+
+ exportJSON: function(options) {
+ return Base.exportJSON(this, options);
+ },
+
+ toJSON: function() {
+ return Base.serialize(this);
+ },
+
+ _set: function(props, exclude, dontCheck) {
+ if (props && (dontCheck || Base.isPlainObject(props))) {
+ var orig = props._filtering || props;
+ for (var key in orig) {
+ if (orig.hasOwnProperty(key) && !(exclude && exclude[key])) {
+ var value = props[key];
+ if (value !== undefined)
+ this[key] = value;
+ }
+ }
+ return true;
+ }
+ },
+
+ statics: {
+
+ exports: {
+ enumerable: true
+ },
+
+ extend: function extend() {
+ var res = extend.base.apply(this, arguments),
+ name = res.prototype._class;
+ if (name && !Base.exports[name])
+ Base.exports[name] = res;
+ return res;
+ },
+
+ equals: function(obj1, obj2) {
+ function checkKeys(o1, o2) {
+ for (var i in o1)
+ if (o1.hasOwnProperty(i) && !o2.hasOwnProperty(i))
+ return false;
+ return true;
+ }
+ if (obj1 === obj2)
+ return true;
+ if (obj1 && obj1.equals)
+ return obj1.equals(obj2);
+ if (obj2 && obj2.equals)
+ return obj2.equals(obj1);
+ if (Array.isArray(obj1) && Array.isArray(obj2)) {
+ if (obj1.length !== obj2.length)
+ return false;
+ for (var i = 0, l = obj1.length; i < l; i++) {
+ if (!Base.equals(obj1[i], obj2[i]))
+ return false;
+ }
+ return true;
+ }
+ if (obj1 && typeof obj1 === 'object'
+ && obj2 && typeof obj2 === 'object') {
+ if (!checkKeys(obj1, obj2) || !checkKeys(obj2, obj1))
+ return false;
+ for (var i in obj1) {
+ if (obj1.hasOwnProperty(i)
+ && !Base.equals(obj1[i], obj2[i]))
+ return false;
+ }
+ return true;
+ }
+ return false;
+ },
+
+ read: function(list, start, options, length) {
+ if (this === Base) {
+ var value = this.peek(list, start);
+ list.__index++;
+ return value;
+ }
+ var proto = this.prototype,
+ readIndex = proto._readIndex,
+ index = start || readIndex && list.__index || 0;
+ if (!length)
+ length = list.length - index;
+ var obj = list[index];
+ if (obj instanceof this
+ || options && options.readNull && obj == null && length <= 1) {
+ if (readIndex)
+ list.__index = index + 1;
+ return obj && options && options.clone ? obj.clone() : obj;
+ }
+ obj = Base.create(this.prototype);
+ if (readIndex)
+ obj.__read = true;
+ obj = obj.initialize.apply(obj, index > 0 || length < list.length
+ ? Array.prototype.slice.call(list, index, index + length)
+ : list) || obj;
+ if (readIndex) {
+ list.__index = index + obj.__read;
+ obj.__read = undefined;
+ }
+ return obj;
+ },
+
+ peek: function(list, start) {
+ return list[list.__index = start || list.__index || 0];
+ },
+
+ remain: function(list) {
+ return list.length - (list.__index || 0);
+ },
+
+ readAll: function(list, start, options) {
+ var res = [],
+ entry;
+ for (var i = start || 0, l = list.length; i < l; i++) {
+ res.push(Array.isArray(entry = list[i])
+ ? this.read(entry, 0, options)
+ : this.read(list, i, options, 1));
+ }
+ return res;
+ },
+
+ readNamed: function(list, name, start, options, length) {
+ var value = this.getNamed(list, name),
+ hasObject = value !== undefined;
+ if (hasObject) {
+ var filtered = list._filtered;
+ if (!filtered) {
+ filtered = list._filtered = Base.create(list[0]);
+ filtered._filtering = list[0];
+ }
+ filtered[name] = undefined;
+ }
+ return this.read(hasObject ? [value] : list, start, options, length);
+ },
+
+ getNamed: function(list, name) {
+ var arg = list[0];
+ if (list._hasObject === undefined)
+ list._hasObject = list.length === 1 && Base.isPlainObject(arg);
+ if (list._hasObject)
+ return name ? arg[name] : list._filtered || arg;
+ },
+
+ hasNamed: function(list, name) {
+ return !!this.getNamed(list, name);
+ },
+
+ isPlainValue: function(obj, asString) {
+ return this.isPlainObject(obj) || Array.isArray(obj)
+ || asString && typeof obj === 'string';
+ },
+
+ serialize: function(obj, options, compact, dictionary) {
+ options = options || {};
+
+ var root = !dictionary,
+ res;
+ if (root) {
+ options.formatter = new Formatter(options.precision);
+ dictionary = {
+ length: 0,
+ definitions: {},
+ references: {},
+ add: function(item, create) {
+ var id = '#' + item._id,
+ ref = this.references[id];
+ if (!ref) {
+ this.length++;
+ var res = create.call(item),
+ name = item._class;
+ if (name && res[0] !== name)
+ res.unshift(name);
+ this.definitions[id] = res;
+ ref = this.references[id] = [id];
+ }
+ return ref;
+ }
+ };
+ }
+ if (obj && obj._serialize) {
+ res = obj._serialize(options, dictionary);
+ var name = obj._class;
+ if (name && !compact && !res._compact && res[0] !== name)
+ res.unshift(name);
+ } else if (Array.isArray(obj)) {
+ res = [];
+ for (var i = 0, l = obj.length; i < l; i++)
+ res[i] = Base.serialize(obj[i], options, compact,
+ dictionary);
+ if (compact)
+ res._compact = true;
+ } else if (Base.isPlainObject(obj)) {
+ res = {};
+ for (var i in obj)
+ if (obj.hasOwnProperty(i))
+ res[i] = Base.serialize(obj[i], options, compact,
+ dictionary);
+ } else if (typeof obj === 'number') {
+ res = options.formatter.number(obj, options.precision);
+ } else {
+ res = obj;
+ }
+ return root && dictionary.length > 0
+ ? [['dictionary', dictionary.definitions], res]
+ : res;
+ },
+
+ deserialize: function(json, create, _data) {
+ var res = json;
+ _data = _data || {};
+ if (Array.isArray(json)) {
+ var type = json[0],
+ isDictionary = type === 'dictionary';
+ if (!isDictionary) {
+ if (_data.dictionary && json.length == 1 && /^#/.test(type))
+ return _data.dictionary[type];
+ type = Base.exports[type];
+ }
+ res = [];
+ for (var i = type ? 1 : 0, l = json.length; i < l; i++)
+ res.push(Base.deserialize(json[i], create, _data));
+ if (isDictionary) {
+ _data.dictionary = res[0];
+ } else if (type) {
+ var args = res;
+ if (create) {
+ res = create(type, args);
+ } else {
+ res = Base.create(type.prototype);
+ type.apply(res, args);
+ }
+ }
+ } else if (Base.isPlainObject(json)) {
+ res = {};
+ for (var key in json)
+ res[key] = Base.deserialize(json[key], create, _data);
+ }
+ return res;
+ },
+
+ exportJSON: function(obj, options) {
+ var json = Base.serialize(obj, options);
+ return options && options.asString === false
+ ? json
+ : JSON.stringify(json);
+ },
+
+ importJSON: function(json, target) {
+ return Base.deserialize(
+ typeof json === 'string' ? JSON.parse(json) : json,
+ function(type, args) {
+ var obj = target && target.constructor === type
+ ? target
+ : Base.create(type.prototype),
+ isTarget = obj === target;
+ if (args.length === 1 && obj instanceof Item
+ && (isTarget || !(obj instanceof Layer))) {
+ var arg = args[0];
+ if (Base.isPlainObject(arg))
+ arg.insert = false;
+ }
+ type.apply(obj, args);
+ if (isTarget)
+ target = null;
+ return obj;
+ });
+ },
+
+ splice: function(list, items, index, remove) {
+ var amount = items && items.length,
+ append = index === undefined;
+ index = append ? list.length : index;
+ if (index > list.length)
+ index = list.length;
+ for (var i = 0; i < amount; i++)
+ items[i]._index = index + i;
+ if (append) {
+ list.push.apply(list, items);
+ return [];
+ } else {
+ var args = [index, remove];
+ if (items)
+ args.push.apply(args, items);
+ var removed = list.splice.apply(list, args);
+ for (var i = 0, l = removed.length; i < l; i++)
+ removed[i]._index = undefined;
+ for (var i = index + amount, l = list.length; i < l; i++)
+ list[i]._index = i;
+ return removed;
+ }
+ },
+
+ capitalize: function(str) {
+ return str.replace(/\b[a-z]/g, function(match) {
+ return match.toUpperCase();
+ });
+ },
+
+ camelize: function(str) {
+ return str.replace(/-(.)/g, function(all, chr) {
+ return chr.toUpperCase();
+ });
+ },
+
+ hyphenate: function(str) {
+ return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
+ }
+ }
+});
+
+var Emitter = {
+ on: function(type, func) {
+ if (typeof type !== 'string') {
+ Base.each(type, function(value, key) {
+ this.on(key, value);
+ }, this);
+ } else {
+ var entry = this._eventTypes[type];
+ if (entry) {
+ var handlers = this._callbacks = this._callbacks || {};
+ handlers = handlers[type] = handlers[type] || [];
+ if (handlers.indexOf(func) === -1) {
+ handlers.push(func);
+ if (entry.install && handlers.length == 1)
+ entry.install.call(this, type);
+ }
+ }
+ }
+ return this;
+ },
+
+ off: function(type, func) {
+ if (typeof type !== 'string') {
+ Base.each(type, function(value, key) {
+ this.off(key, value);
+ }, this);
+ return;
+ }
+ var entry = this._eventTypes[type],
+ handlers = this._callbacks && this._callbacks[type],
+ index;
+ if (entry && handlers) {
+ if (!func || (index = handlers.indexOf(func)) !== -1
+ && handlers.length === 1) {
+ if (entry.uninstall)
+ entry.uninstall.call(this, type);
+ delete this._callbacks[type];
+ } else if (index !== -1) {
+ handlers.splice(index, 1);
+ }
+ }
+ return this;
+ },
+
+ once: function(type, func) {
+ return this.on(type, function() {
+ func.apply(this, arguments);
+ this.off(type, func);
+ });
+ },
+
+ emit: function(type, event) {
+ var handlers = this._callbacks && this._callbacks[type];
+ if (!handlers)
+ return false;
+ var args = [].slice.call(arguments, 1);
+ for (var i = 0, l = handlers.length; i < l; i++) {
+ if (handlers[i].apply(this, args) === false
+ && event && event.stop) {
+ event.stop();
+ break;
+ }
+ }
+ return true;
+ },
+
+ responds: function(type) {
+ return !!(this._callbacks && this._callbacks[type]);
+ },
+
+ attach: '#on',
+ detach: '#off',
+ fire: '#emit',
+
+ _installEvents: function(install) {
+ var handlers = this._callbacks,
+ key = install ? 'install' : 'uninstall';
+ for (var type in handlers) {
+ if (handlers[type].length > 0) {
+ var entry = this._eventTypes[type],
+ func = entry[key];
+ if (func)
+ func.call(this, type);
+ }
+ }
+ },
+
+ statics: {
+ inject: function inject(src) {
+ var events = src._events;
+ if (events) {
+ var types = {};
+ Base.each(events, function(entry, key) {
+ var isString = typeof entry === 'string',
+ name = isString ? entry : key,
+ part = Base.capitalize(name),
+ type = name.substring(2).toLowerCase();
+ types[type] = isString ? {} : entry;
+ name = '_' + name;
+ src['get' + part] = function() {
+ return this[name];
+ };
+ src['set' + part] = function(func) {
+ var prev = this[name];
+ if (prev)
+ this.off(type, prev);
+ if (func)
+ this.on(type, func);
+ this[name] = func;
+ };
+ });
+ src._eventTypes = types;
+ }
+ return inject.base.apply(this, arguments);
+ }
+ }
+};
+
+var PaperScope = Base.extend({
+ _class: 'PaperScope',
+
+ initialize: function PaperScope() {
+ paper = this;
+ this.settings = new Base({
+ applyMatrix: true,
+ handleSize: 4,
+ hitTolerance: 0
+ });
+ this.project = null;
+ this.projects = [];
+ this.tools = [];
+ this.palettes = [];
+ this._id = PaperScope._id++;
+ PaperScope._scopes[this._id] = this;
+ var proto = PaperScope.prototype;
+ if (!this.support) {
+ var ctx = CanvasProvider.getContext(1, 1);
+ proto.support = {
+ nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx,
+ nativeBlendModes: BlendMode.nativeModes
+ };
+ CanvasProvider.release(ctx);
+ }
+
+ if (!this.browser) {
+ var browser = proto.browser = {};
+ navigator.userAgent.toLowerCase().replace(
+ /(opera|chrome|safari|webkit|firefox|msie|trident)\/?\s*([.\d]+)(?:.*version\/([.\d]+))?(?:.*rv\:([.\d]+))?/g,
+ function(all, n, v1, v2, rv) {
+ if (!browser.chrome) {
+ var v = n === 'opera' ? v2 : v1;
+ if (n === 'trident') {
+ v = rv;
+ n = 'msie';
+ }
+ browser.version = v;
+ browser.versionNumber = parseFloat(v);
+ browser.name = n;
+ browser[n] = true;
+ }
+ }
+ );
+ if (browser.chrome)
+ delete browser.webkit;
+ }
+ },
+
+ version: '0.9.21',
+
+ getView: function() {
+ return this.project && this.project.getView();
+ },
+
+ getPaper: function() {
+ return this;
+ },
+
+ execute: function(code, url, options) {
+ paper.PaperScript.execute(code, this, url, options);
+ View.updateFocus();
+ },
+
+ install: function(scope) {
+ var that = this;
+ Base.each(['project', 'view', 'tool'], function(key) {
+ Base.define(scope, key, {
+ configurable: true,
+ get: function() {
+ return that[key];
+ }
+ });
+ });
+ for (var key in this)
+ if (!/^_/.test(key) && this[key])
+ scope[key] = this[key];
+ },
+
+ setup: function(element) {
+ paper = this;
+ this.project = new Project(element);
+ return this;
+ },
+
+ activate: function() {
+ paper = this;
+ },
+
+ clear: function() {
+ for (var i = this.projects.length - 1; i >= 0; i--)
+ this.projects[i].remove();
+ for (var i = this.tools.length - 1; i >= 0; i--)
+ this.tools[i].remove();
+ for (var i = this.palettes.length - 1; i >= 0; i--)
+ this.palettes[i].remove();
+ },
+
+ remove: function() {
+ this.clear();
+ delete PaperScope._scopes[this._id];
+ },
+
+ statics: new function() {
+ function handleAttribute(name) {
+ name += 'Attribute';
+ return function(el, attr) {
+ return el[name](attr) || el[name]('data-paper-' + attr);
+ };
+ }
+
+ return {
+ _scopes: {},
+ _id: 0,
+
+ get: function(id) {
+ return this._scopes[id] || null;
+ },
+
+ getAttribute: handleAttribute('get'),
+ hasAttribute: handleAttribute('has')
+ };
+ }
+});
+
+var PaperScopeItem = Base.extend(Emitter, {
+
+ initialize: function(activate) {
+ this._scope = paper;
+ this._index = this._scope[this._list].push(this) - 1;
+ if (activate || !this._scope[this._reference])
+ this.activate();
+ },
+
+ activate: function() {
+ if (!this._scope)
+ return false;
+ var prev = this._scope[this._reference];
+ if (prev && prev !== this)
+ prev.emit('deactivate');
+ this._scope[this._reference] = this;
+ this.emit('activate', prev);
+ return true;
+ },
+
+ isActive: function() {
+ return this._scope[this._reference] === this;
+ },
+
+ remove: function() {
+ if (this._index == null)
+ return false;
+ Base.splice(this._scope[this._list], null, this._index, 1);
+ if (this._scope[this._reference] == this)
+ this._scope[this._reference] = null;
+ this._scope = null;
+ return true;
+ }
+});
+
+var Formatter = Base.extend({
+ initialize: function(precision) {
+ this.precision = precision || 5;
+ this.multiplier = Math.pow(10, this.precision);
+ },
+
+ number: function(val) {
+ return Math.round(val * this.multiplier) / this.multiplier;
+ },
+
+ pair: function(val1, val2, separator) {
+ return this.number(val1) + (separator || ',') + this.number(val2);
+ },
+
+ point: function(val, separator) {
+ return this.number(val.x) + (separator || ',') + this.number(val.y);
+ },
+
+ size: function(val, separator) {
+ return this.number(val.width) + (separator || ',')
+ + this.number(val.height);
+ },
+
+ rectangle: function(val, separator) {
+ return this.point(val, separator) + (separator || ',')
+ + this.size(val, separator);
+ }
+});
+
+Formatter.instance = new Formatter();
+
+var Numerical = new function() {
+
+ var abscissas = [
+ [ 0.5773502691896257645091488],
+ [0,0.7745966692414833770358531],
+ [ 0.3399810435848562648026658,0.8611363115940525752239465],
+ [0,0.5384693101056830910363144,0.9061798459386639927976269],
+ [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
+ [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
+ [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
+ [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
+ [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
+ [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
+ [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
+ [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
+ [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
+ [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
+ [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
+ ];
+
+ var weights = [
+ [1],
+ [0.8888888888888888888888889,0.5555555555555555555555556],
+ [0.6521451548625461426269361,0.3478548451374538573730639],
+ [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
+ [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
+ [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
+ [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
+ [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
+ [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
+ [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
+ [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
+ [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
+ [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
+ [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
+ [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
+ ];
+
+ var abs = Math.abs,
+ sqrt = Math.sqrt,
+ pow = Math.pow,
+ cos = Math.cos,
+ PI = Math.PI,
+ TOLERANCE = 10e-6,
+ EPSILON = 10e-12;
+
+ function setupRoots(roots, min, max) {
+ var unbound = min === undefined,
+ minE = min - EPSILON,
+ maxE = max + EPSILON,
+ count = 0;
+ return function(root) {
+ if (unbound || root > minE && root < maxE)
+ roots[count++] = root < min ? min : root > max ? max : root;
+ return count;
+ };
+ }
+
+ return {
+ TOLERANCE: TOLERANCE,
+ EPSILON: EPSILON,
+ KAPPA: 4 * (sqrt(2) - 1) / 3,
+
+ isZero: function(val) {
+ return abs(val) <= EPSILON;
+ },
+
+ integrate: function(f, a, b, n) {
+ var x = abscissas[n - 2],
+ w = weights[n - 2],
+ A = (b - a) * 0.5,
+ B = A + a,
+ i = 0,
+ m = (n + 1) >> 1,
+ sum = n & 1 ? w[i++] * f(B) : 0;
+ while (i < m) {
+ var Ax = A * x[i];
+ sum += w[i++] * (f(B + Ax) + f(B - Ax));
+ }
+ return A * sum;
+ },
+
+ findRoot: function(f, df, x, a, b, n, tolerance) {
+ for (var i = 0; i < n; i++) {
+ var fx = f(x),
+ dx = fx / df(x),
+ nx = x - dx;
+ if (abs(dx) < tolerance)
+ return nx;
+ if (fx > 0) {
+ b = x;
+ x = nx <= a ? (a + b) * 0.5 : nx;
+ } else {
+ a = x;
+ x = nx >= b ? (a + b) * 0.5 : nx;
+ }
+ }
+ return x;
+ },
+
+ solveQuadratic: function(a, b, c, roots, min, max) {
+ var add = setupRoots(roots, min, max);
+
+ if (abs(a) < EPSILON) {
+ if (abs(b) >= EPSILON)
+ return add(-c / b);
+ return abs(c) < EPSILON ? -1 : 0;
+ }
+ var p = b / (2 * a);
+ var q = c / a;
+ var p2 = p * p;
+ if (p2 < q - EPSILON)
+ return 0;
+ var s = p2 > q ? sqrt(p2 - q) : 0,
+ count = add(s - p);
+ if (s > 0)
+ count = add(-s - p);
+ return count;
+ },
+
+ solveCubic: function(a, b, c, d, roots, min, max) {
+ if (abs(a) < EPSILON)
+ return Numerical.solveQuadratic(b, c, d, roots, min, max);
+
+ b /= a;
+ c /= a;
+ d /= a;
+ var add = setupRoots(roots, min, max),
+ bb = b * b,
+ p = (bb - 3 * c) / 9,
+ q = (2 * bb * b - 9 * b * c + 27 * d) / 54,
+ ppp = p * p * p,
+ D = q * q - ppp;
+ b /= 3;
+ if (abs(D) < EPSILON) {
+ if (abs(q) < EPSILON)
+ return add(-b);
+ var sqp = sqrt(p),
+ snq = q > 0 ? 1 : -1;
+ add(-snq * 2 * sqp - b);
+ return add(snq * sqp - b);
+ }
+ if (D < 0) {
+ var sqp = sqrt(p),
+ phi = Math.acos(q / (sqp * sqp * sqp)) / 3,
+ t = -2 * sqp,
+ o = 2 * PI / 3;
+ add(t * cos(phi) - b);
+ add(t * cos(phi + o) - b);
+ return add(t * cos(phi - o) - b);
+ }
+ var A = (q > 0 ? -1 : 1) * pow(abs(q) + sqrt(D), 1 / 3);
+ return add(A + p / A - b);
+ }
+ };
+};
+
+var Point = Base.extend({
+ _class: 'Point',
+ _readIndex: true,
+
+ initialize: function Point(arg0, arg1) {
+ var type = typeof arg0;
+ if (type === 'number') {
+ var hasY = typeof arg1 === 'number';
+ this.x = arg0;
+ this.y = hasY ? arg1 : arg0;
+ if (this.__read)
+ this.__read = hasY ? 2 : 1;
+ } else if (type === 'undefined' || arg0 === null) {
+ this.x = this.y = 0;
+ if (this.__read)
+ this.__read = arg0 === null ? 1 : 0;
+ } else {
+ if (Array.isArray(arg0)) {
+ this.x = arg0[0];
+ this.y = arg0.length > 1 ? arg0[1] : arg0[0];
+ } else if (arg0.x != null) {
+ this.x = arg0.x;
+ this.y = arg0.y;
+ } else if (arg0.width != null) {
+ this.x = arg0.width;
+ this.y = arg0.height;
+ } else if (arg0.angle != null) {
+ this.x = arg0.length;
+ this.y = 0;
+ this.setAngle(arg0.angle);
+ } else {
+ this.x = this.y = 0;
+ if (this.__read)
+ this.__read = 0;
+ }
+ if (this.__read)
+ this.__read = 1;
+ }
+ },
+
+ set: function(x, y) {
+ this.x = x;
+ this.y = y;
+ return this;
+ },
+
+ equals: function(point) {
+ return this === point || point
+ && (this.x === point.x && this.y === point.y
+ || Array.isArray(point)
+ && this.x === point[0] && this.y === point[1])
+ || false;
+ },
+
+ clone: function() {
+ return new Point(this.x, this.y);
+ },
+
+ toString: function() {
+ var f = Formatter.instance;
+ return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
+ },
+
+ _serialize: function(options) {
+ var f = options.formatter;
+ return [f.number(this.x), f.number(this.y)];
+ },
+
+ getLength: function() {
+ return Math.sqrt(this.x * this.x + this.y * this.y);
+ },
+
+ setLength: function(length) {
+ if (this.isZero()) {
+ var angle = this._angle || 0;
+ this.set(
+ Math.cos(angle) * length,
+ Math.sin(angle) * length
+ );
+ } else {
+ var scale = length / this.getLength();
+ if (Numerical.isZero(scale))
+ this.getAngle();
+ this.set(
+ this.x * scale,
+ this.y * scale
+ );
+ }
+ },
+ getAngle: function() {
+ return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI;
+ },
+
+ setAngle: function(angle) {
+ this.setAngleInRadians.call(this, angle * Math.PI / 180);
+ },
+
+ getAngleInDegrees: '#getAngle',
+ setAngleInDegrees: '#setAngle',
+
+ getAngleInRadians: function() {
+ if (!arguments.length) {
+ return this.isZero()
+ ? this._angle || 0
+ : this._angle = Math.atan2(this.y, this.x);
+ } else {
+ var point = Point.read(arguments),
+ div = this.getLength() * point.getLength();
+ if (Numerical.isZero(div)) {
+ return NaN;
+ } else {
+ var a = this.dot(point) / div;
+ return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a);
+ }
+ }
+ },
+
+ setAngleInRadians: function(angle) {
+ this._angle = angle;
+ if (!this.isZero()) {
+ var length = this.getLength();
+ this.set(
+ Math.cos(angle) * length,
+ Math.sin(angle) * length
+ );
+ }
+ },
+
+ getQuadrant: function() {
+ return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
+ }
+}, {
+ beans: false,
+
+ getDirectedAngle: function() {
+ var point = Point.read(arguments);
+ return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
+ },
+
+ getDistance: function() {
+ var point = Point.read(arguments),
+ x = point.x - this.x,
+ y = point.y - this.y,
+ d = x * x + y * y,
+ squared = Base.read(arguments);
+ return squared ? d : Math.sqrt(d);
+ },
+
+ normalize: function(length) {
+ if (length === undefined)
+ length = 1;
+ var current = this.getLength(),
+ scale = current !== 0 ? length / current : 0,
+ point = new Point(this.x * scale, this.y * scale);
+ if (scale >= 0)
+ point._angle = this._angle;
+ return point;
+ },
+
+ rotate: function(angle, center) {
+ if (angle === 0)
+ return this.clone();
+ angle = angle * Math.PI / 180;
+ var point = center ? this.subtract(center) : this,
+ s = Math.sin(angle),
+ c = Math.cos(angle);
+ point = new Point(
+ point.x * c - point.y * s,
+ point.x * s + point.y * c
+ );
+ return center ? point.add(center) : point;
+ },
+
+ transform: function(matrix) {
+ return matrix ? matrix._transformPoint(this) : this;
+ },
+
+ add: function() {
+ var point = Point.read(arguments);
+ return new Point(this.x + point.x, this.y + point.y);
+ },
+
+ subtract: function() {
+ var point = Point.read(arguments);
+ return new Point(this.x - point.x, this.y - point.y);
+ },
+
+ multiply: function() {
+ var point = Point.read(arguments);
+ return new Point(this.x * point.x, this.y * point.y);
+ },
+
+ divide: function() {
+ var point = Point.read(arguments);
+ return new Point(this.x / point.x, this.y / point.y);
+ },
+
+ modulo: function() {
+ var point = Point.read(arguments);
+ return new Point(this.x % point.x, this.y % point.y);
+ },
+
+ negate: function() {
+ return new Point(-this.x, -this.y);
+ },
+
+ isInside: function() {
+ return Rectangle.read(arguments).contains(this);
+ },
+
+ isClose: function(point, tolerance) {
+ return this.getDistance(point) < tolerance;
+ },
+
+ isColinear: function(point) {
+ return Math.abs(this.cross(point)) < 0.00001;
+ },
+
+ isOrthogonal: function(point) {
+ return Math.abs(this.dot(point)) < 0.00001;
+ },
+
+ isZero: function() {
+ return Numerical.isZero(this.x) && Numerical.isZero(this.y);
+ },
+
+ isNaN: function() {
+ return isNaN(this.x) || isNaN(this.y);
+ },
+
+ dot: function() {
+ var point = Point.read(arguments);
+ return this.x * point.x + this.y * point.y;
+ },
+
+ cross: function() {
+ var point = Point.read(arguments);
+ return this.x * point.y - this.y * point.x;
+ },
+
+ project: function() {
+ var point = Point.read(arguments);
+ if (point.isZero()) {
+ return new Point(0, 0);
+ } else {
+ var scale = this.dot(point) / point.dot(point);
+ return new Point(
+ point.x * scale,
+ point.y * scale
+ );
+ }
+ },
+
+ statics: {
+ min: function() {
+ var point1 = Point.read(arguments),
+ point2 = Point.read(arguments);
+ return new Point(
+ Math.min(point1.x, point2.x),
+ Math.min(point1.y, point2.y)
+ );
+ },
+
+ max: function() {
+ var point1 = Point.read(arguments),
+ point2 = Point.read(arguments);
+ return new Point(
+ Math.max(point1.x, point2.x),
+ Math.max(point1.y, point2.y)
+ );
+ },
+
+ random: function() {
+ return new Point(Math.random(), Math.random());
+ }
+ }
+}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
+ var op = Math[name];
+ this[name] = function() {
+ return new Point(op(this.x), op(this.y));
+ };
+}, {}));
+
+var LinkedPoint = Point.extend({
+ initialize: function Point(x, y, owner, setter) {
+ this._x = x;
+ this._y = y;
+ this._owner = owner;
+ this._setter = setter;
+ },
+
+ set: function(x, y, _dontNotify) {
+ this._x = x;
+ this._y = y;
+ if (!_dontNotify)
+ this._owner[this._setter](this);
+ return this;
+ },
+
+ getX: function() {
+ return this._x;
+ },
+
+ setX: function(x) {
+ this._x = x;
+ this._owner[this._setter](this);
+ },
+
+ getY: function() {
+ return this._y;
+ },
+
+ setY: function(y) {
+ this._y = y;
+ this._owner[this._setter](this);
+ }
+});
+
+var Size = Base.extend({
+ _class: 'Size',
+ _readIndex: true,
+
+ initialize: function Size(arg0, arg1) {
+ var type = typeof arg0;
+ if (type === 'number') {
+ var hasHeight = typeof arg1 === 'number';
+ this.width = arg0;
+ this.height = hasHeight ? arg1 : arg0;
+ if (this.__read)
+ this.__read = hasHeight ? 2 : 1;
+ } else if (type === 'undefined' || arg0 === null) {
+ this.width = this.height = 0;
+ if (this.__read)
+ this.__read = arg0 === null ? 1 : 0;
+ } else {
+ if (Array.isArray(arg0)) {
+ this.width = arg0[0];
+ this.height = arg0.length > 1 ? arg0[1] : arg0[0];
+ } else if (arg0.width != null) {
+ this.width = arg0.width;
+ this.height = arg0.height;
+ } else if (arg0.x != null) {
+ this.width = arg0.x;
+ this.height = arg0.y;
+ } else {
+ this.width = this.height = 0;
+ if (this.__read)
+ this.__read = 0;
+ }
+ if (this.__read)
+ this.__read = 1;
+ }
+ },
+
+ set: function(width, height) {
+ this.width = width;
+ this.height = height;
+ return this;
+ },
+
+ equals: function(size) {
+ return size === this || size && (this.width === size.width
+ && this.height === size.height
+ || Array.isArray(size) && this.width === size[0]
+ && this.height === size[1]) || false;
+ },
+
+ clone: function() {
+ return new Size(this.width, this.height);
+ },
+
+ toString: function() {
+ var f = Formatter.instance;
+ return '{ width: ' + f.number(this.width)
+ + ', height: ' + f.number(this.height) + ' }';
+ },
+
+ _serialize: function(options) {
+ var f = options.formatter;
+ return [f.number(this.width),
+ f.number(this.height)];
+ },
+
+ add: function() {
+ var size = Size.read(arguments);
+ return new Size(this.width + size.width, this.height + size.height);
+ },
+
+ subtract: function() {
+ var size = Size.read(arguments);
+ return new Size(this.width - size.width, this.height - size.height);
+ },
+
+ multiply: function() {
+ var size = Size.read(arguments);
+ return new Size(this.width * size.width, this.height * size.height);
+ },
+
+ divide: function() {
+ var size = Size.read(arguments);
+ return new Size(this.width / size.width, this.height / size.height);
+ },
+
+ modulo: function() {
+ var size = Size.read(arguments);
+ return new Size(this.width % size.width, this.height % size.height);
+ },
+
+ negate: function() {
+ return new Size(-this.width, -this.height);
+ },
+
+ isZero: function() {
+ return Numerical.isZero(this.width) && Numerical.isZero(this.height);
+ },
+
+ isNaN: function() {
+ return isNaN(this.width) || isNaN(this.height);
+ },
+
+ statics: {
+ min: function(size1, size2) {
+ return new Size(
+ Math.min(size1.width, size2.width),
+ Math.min(size1.height, size2.height));
+ },
+
+ max: function(size1, size2) {
+ return new Size(
+ Math.max(size1.width, size2.width),
+ Math.max(size1.height, size2.height));
+ },
+
+ random: function() {
+ return new Size(Math.random(), Math.random());
+ }
+ }
+}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
+ var op = Math[name];
+ this[name] = function() {
+ return new Size(op(this.width), op(this.height));
+ };
+}, {}));
+
+var LinkedSize = Size.extend({
+ initialize: function Size(width, height, owner, setter) {
+ this._width = width;
+ this._height = height;
+ this._owner = owner;
+ this._setter = setter;
+ },
+
+ set: function(width, height, _dontNotify) {
+ this._width = width;
+ this._height = height;
+ if (!_dontNotify)
+ this._owner[this._setter](this);
+ return this;
+ },
+
+ getWidth: function() {
+ return this._width;
+ },
+
+ setWidth: function(width) {
+ this._width = width;
+ this._owner[this._setter](this);
+ },
+
+ getHeight: function() {
+ return this._height;
+ },
+
+ setHeight: function(height) {
+ this._height = height;
+ this._owner[this._setter](this);
+ }
+});
+
+var Rectangle = Base.extend({
+ _class: 'Rectangle',
+ _readIndex: true,
+ beans: true,
+
+ initialize: function Rectangle(arg0, arg1, arg2, arg3) {
+ var type = typeof arg0,
+ read = 0;
+ if (type === 'number') {
+ this.x = arg0;
+ this.y = arg1;
+ this.width = arg2;
+ this.height = arg3;
+ read = 4;
+ } else if (type === 'undefined' || arg0 === null) {
+ this.x = this.y = this.width = this.height = 0;
+ read = arg0 === null ? 1 : 0;
+ } else if (arguments.length === 1) {
+ if (Array.isArray(arg0)) {
+ this.x = arg0[0];
+ this.y = arg0[1];
+ this.width = arg0[2];
+ this.height = arg0[3];
+ read = 1;
+ } else if (arg0.x !== undefined || arg0.width !== undefined) {
+ this.x = arg0.x || 0;
+ this.y = arg0.y || 0;
+ this.width = arg0.width || 0;
+ this.height = arg0.height || 0;
+ read = 1;
+ } else if (arg0.from === undefined && arg0.to === undefined) {
+ this.x = this.y = this.width = this.height = 0;
+ this._set(arg0);
+ read = 1;
+ }
+ }
+ if (!read) {
+ var point = Point.readNamed(arguments, 'from'),
+ next = Base.peek(arguments);
+ this.x = point.x;
+ this.y = point.y;
+ if (next && next.x !== undefined || Base.hasNamed(arguments, 'to')) {
+ var to = Point.readNamed(arguments, 'to');
+ this.width = to.x - point.x;
+ this.height = to.y - point.y;
+ if (this.width < 0) {
+ this.x = to.x;
+ this.width = -this.width;
+ }
+ if (this.height < 0) {
+ this.y = to.y;
+ this.height = -this.height;
+ }
+ } else {
+ var size = Size.read(arguments);
+ this.width = size.width;
+ this.height = size.height;
+ }
+ read = arguments.__index;
+ }
+ if (this.__read)
+ this.__read = read;
+ },
+
+ set: function(x, y, width, height) {
+ this.x = x;
+ this.y = y;
+ this.width = width;
+ this.height = height;
+ return this;
+ },
+
+ clone: function() {
+ return new Rectangle(this.x, this.y, this.width, this.height);
+ },
+
+ equals: function(rect) {
+ var rt = Base.isPlainValue(rect)
+ ? Rectangle.read(arguments)
+ : rect;
+ return rt === this
+ || rt && this.x === rt.x && this.y === rt.y
+ && this.width === rt.width && this.height === rt.height
+ || false;
+ },
+
+ toString: function() {
+ var f = Formatter.instance;
+ return '{ x: ' + f.number(this.x)
+ + ', y: ' + f.number(this.y)
+ + ', width: ' + f.number(this.width)
+ + ', height: ' + f.number(this.height)
+ + ' }';
+ },
+
+ _serialize: function(options) {
+ var f = options.formatter;
+ return [f.number(this.x),
+ f.number(this.y),
+ f.number(this.width),
+ f.number(this.height)];
+ },
+
+ getPoint: function(_dontLink) {
+ var ctor = _dontLink ? Point : LinkedPoint;
+ return new ctor(this.x, this.y, this, 'setPoint');
+ },
+
+ setPoint: function() {
+ var point = Point.read(arguments);
+ this.x = point.x;
+ this.y = point.y;
+ },
+
+ getSize: function(_dontLink) {
+ var ctor = _dontLink ? Size : LinkedSize;
+ return new ctor(this.width, this.height, this, 'setSize');
+ },
+
+ setSize: function() {
+ var size = Size.read(arguments);
+ if (this._fixX)
+ this.x += (this.width - size.width) * this._fixX;
+ if (this._fixY)
+ this.y += (this.height - size.height) * this._fixY;
+ this.width = size.width;
+ this.height = size.height;
+ this._fixW = 1;
+ this._fixH = 1;
+ },
+
+ getLeft: function() {
+ return this.x;
+ },
+
+ setLeft: function(left) {
+ if (!this._fixW)
+ this.width -= left - this.x;
+ this.x = left;
+ this._fixX = 0;
+ },
+
+ getTop: function() {
+ return this.y;
+ },
+
+ setTop: function(top) {
+ if (!this._fixH)
+ this.height -= top - this.y;
+ this.y = top;
+ this._fixY = 0;
+ },
+
+ getRight: function() {
+ return this.x + this.width;
+ },
+
+ setRight: function(right) {
+ if (this._fixX !== undefined && this._fixX !== 1)
+ this._fixW = 0;
+ if (this._fixW)
+ this.x = right - this.width;
+ else
+ this.width = right - this.x;
+ this._fixX = 1;
+ },
+
+ getBottom: function() {
+ return this.y + this.height;
+ },
+
+ setBottom: function(bottom) {
+ if (this._fixY !== undefined && this._fixY !== 1)
+ this._fixH = 0;
+ if (this._fixH)
+ this.y = bottom - this.height;
+ else
+ this.height = bottom - this.y;
+ this._fixY = 1;
+ },
+
+ getCenterX: function() {
+ return this.x + this.width * 0.5;
+ },
+
+ setCenterX: function(x) {
+ this.x = x - this.width * 0.5;
+ this._fixX = 0.5;
+ },
+
+ getCenterY: function() {
+ return this.y + this.height * 0.5;
+ },
+
+ setCenterY: function(y) {
+ this.y = y - this.height * 0.5;
+ this._fixY = 0.5;
+ },
+
+ getCenter: function(_dontLink) {
+ var ctor = _dontLink ? Point : LinkedPoint;
+ return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter');
+ },
+
+ setCenter: function() {
+ var point = Point.read(arguments);
+ this.setCenterX(point.x);
+ this.setCenterY(point.y);
+ return this;
+ },
+
+ getArea: function() {
+ return this.width * this.height;
+ },
+
+ isEmpty: function() {
+ return this.width === 0 || this.height === 0;
+ },
+
+ contains: function(arg) {
+ return arg && arg.width !== undefined
+ || (Array.isArray(arg) ? arg : arguments).length == 4
+ ? this._containsRectangle(Rectangle.read(arguments))
+ : this._containsPoint(Point.read(arguments));
+ },
+
+ _containsPoint: function(point) {
+ var x = point.x,
+ y = point.y;
+ return x >= this.x && y >= this.y
+ && x <= this.x + this.width
+ && y <= this.y + this.height;
+ },
+
+ _containsRectangle: function(rect) {
+ var x = rect.x,
+ y = rect.y;
+ return x >= this.x && y >= this.y
+ && x + rect.width <= this.x + this.width
+ && y + rect.height <= this.y + this.height;
+ },
+
+ intersects: function() {
+ var rect = Rectangle.read(arguments);
+ return rect.x + rect.width > this.x
+ && rect.y + rect.height > this.y
+ && rect.x < this.x + this.width
+ && rect.y < this.y + this.height;
+ },
+
+ touches: function() {
+ var rect = Rectangle.read(arguments);
+ return rect.x + rect.width >= this.x
+ && rect.y + rect.height >= this.y
+ && rect.x <= this.x + this.width
+ && rect.y <= this.y + this.height;
+ },
+
+ intersect: function() {
+ var rect = Rectangle.read(arguments),
+ x1 = Math.max(this.x, rect.x),
+ y1 = Math.max(this.y, rect.y),
+ x2 = Math.min(this.x + this.width, rect.x + rect.width),
+ y2 = Math.min(this.y + this.height, rect.y + rect.height);
+ return new Rectangle(x1, y1, x2 - x1, y2 - y1);
+ },
+
+ unite: function() {
+ var rect = Rectangle.read(arguments),
+ x1 = Math.min(this.x, rect.x),
+ y1 = Math.min(this.y, rect.y),
+ x2 = Math.max(this.x + this.width, rect.x + rect.width),
+ y2 = Math.max(this.y + this.height, rect.y + rect.height);
+ return new Rectangle(x1, y1, x2 - x1, y2 - y1);
+ },
+
+ include: function() {
+ var point = Point.read(arguments);
+ var x1 = Math.min(this.x, point.x),
+ y1 = Math.min(this.y, point.y),
+ x2 = Math.max(this.x + this.width, point.x),
+ y2 = Math.max(this.y + this.height, point.y);
+ return new Rectangle(x1, y1, x2 - x1, y2 - y1);
+ },
+
+ expand: function() {
+ var amount = Size.read(arguments),
+ hor = amount.width,
+ ver = amount.height;
+ return new Rectangle(this.x - hor / 2, this.y - ver / 2,
+ this.width + hor, this.height + ver);
+ },
+
+ scale: function(hor, ver) {
+ return this.expand(this.width * hor - this.width,
+ this.height * (ver === undefined ? hor : ver) - this.height);
+ }
+}, Base.each([
+ ['Top', 'Left'], ['Top', 'Right'],
+ ['Bottom', 'Left'], ['Bottom', 'Right'],
+ ['Left', 'Center'], ['Top', 'Center'],
+ ['Right', 'Center'], ['Bottom', 'Center']
+ ],
+ function(parts, index) {
+ var part = parts.join('');
+ var xFirst = /^[RL]/.test(part);
+ if (index >= 4)
+ parts[1] += xFirst ? 'Y' : 'X';
+ var x = parts[xFirst ? 0 : 1],
+ y = parts[xFirst ? 1 : 0],
+ getX = 'get' + x,
+ getY = 'get' + y,
+ setX = 'set' + x,
+ setY = 'set' + y,
+ get = 'get' + part,
+ set = 'set' + part;
+ this[get] = function(_dontLink) {
+ var ctor = _dontLink ? Point : LinkedPoint;
+ return new ctor(this[getX](), this[getY](), this, set);
+ };
+ this[set] = function() {
+ var point = Point.read(arguments);
+ this[setX](point.x);
+ this[setY](point.y);
+ };
+ }, {
+ beans: true
+ }
+));
+
+var LinkedRectangle = Rectangle.extend({
+ initialize: function Rectangle(x, y, width, height, owner, setter) {
+ this.set(x, y, width, height, true);
+ this._owner = owner;
+ this._setter = setter;
+ },
+
+ set: function(x, y, width, height, _dontNotify) {
+ this._x = x;
+ this._y = y;
+ this._width = width;
+ this._height = height;
+ if (!_dontNotify)
+ this._owner[this._setter](this);
+ return this;
+ }
+}, new function() {
+ var proto = Rectangle.prototype;
+
+ return Base.each(['x', 'y', 'width', 'height'], function(key) {
+ var part = Base.capitalize(key);
+ var internal = '_' + key;
+ this['get' + part] = function() {
+ return this[internal];
+ };
+
+ this['set' + part] = function(value) {
+ this[internal] = value;
+ if (!this._dontNotify)
+ this._owner[this._setter](this);
+ };
+ }, Base.each(['Point', 'Size', 'Center',
+ 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
+ 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
+ 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
+ function(key) {
+ var name = 'set' + key;
+ this[name] = function() {
+ this._dontNotify = true;
+ proto[name].apply(this, arguments);
+ this._dontNotify = false;
+ this._owner[this._setter](this);
+ };
+ }, {
+ isSelected: function() {
+ return this._owner._boundsSelected;
+ },
+
+ setSelected: function(selected) {
+ var owner = this._owner;
+ if (owner.setSelected) {
+ owner._boundsSelected = selected;
+ owner.setSelected(selected || owner._selectedSegmentState > 0);
+ }
+ }
+ })
+ );
+});
+
+var Matrix = Base.extend({
+ _class: 'Matrix',
+
+ initialize: function Matrix(arg) {
+ var count = arguments.length,
+ ok = true;
+ if (count === 6) {
+ this.set.apply(this, arguments);
+ } else if (count === 1) {
+ if (arg instanceof Matrix) {
+ this.set(arg._a, arg._c, arg._b, arg._d, arg._tx, arg._ty);
+ } else if (Array.isArray(arg)) {
+ this.set.apply(this, arg);
+ } else {
+ ok = false;
+ }
+ } else if (count === 0) {
+ this.reset();
+ } else {
+ ok = false;
+ }
+ if (!ok)
+ throw new Error('Unsupported matrix parameters');
+ },
+
+ set: function(a, c, b, d, tx, ty, _dontNotify) {
+ this._a = a;
+ this._c = c;
+ this._b = b;
+ this._d = d;
+ this._tx = tx;
+ this._ty = ty;
+ if (!_dontNotify)
+ this._changed();
+ return this;
+ },
+
+ _serialize: function(options) {
+ return Base.serialize(this.getValues(), options);
+ },
+
+ _changed: function() {
+ var owner = this._owner;
+ if (owner) {
+ if (owner._applyMatrix) {
+ owner.transform(null, true);
+ } else {
+ owner._changed(9);
+ }
+ }
+ },
+
+ clone: function() {
+ return new Matrix(this._a, this._c, this._b, this._d,
+ this._tx, this._ty);
+ },
+
+ equals: function(mx) {
+ return mx === this || mx && this._a === mx._a && this._b === mx._b
+ && this._c === mx._c && this._d === mx._d
+ && this._tx === mx._tx && this._ty === mx._ty
+ || false;
+ },
+
+ toString: function() {
+ var f = Formatter.instance;
+ return '[[' + [f.number(this._a), f.number(this._b),
+ f.number(this._tx)].join(', ') + '], ['
+ + [f.number(this._c), f.number(this._d),
+ f.number(this._ty)].join(', ') + ']]';
+ },
+
+ reset: function(_dontNotify) {
+ this._a = this._d = 1;
+ this._c = this._b = this._tx = this._ty = 0;
+ if (!_dontNotify)
+ this._changed();
+ return this;
+ },
+
+ apply: function() {
+ var owner = this._owner;
+ if (owner) {
+ owner.transform(null, true);
+ return this.isIdentity();
+ }
+ return false;
+ },
+
+ translate: function() {
+ var point = Point.read(arguments),
+ x = point.x,
+ y = point.y;
+ this._tx += x * this._a + y * this._b;
+ this._ty += x * this._c + y * this._d;
+ this._changed();
+ return this;
+ },
+
+ scale: function() {
+ var scale = Point.read(arguments),
+ center = Point.read(arguments, 0, { readNull: true });
+ if (center)
+ this.translate(center);
+ this._a *= scale.x;
+ this._c *= scale.x;
+ this._b *= scale.y;
+ this._d *= scale.y;
+ if (center)
+ this.translate(center.negate());
+ this._changed();
+ return this;
+ },
+
+ rotate: function(angle ) {
+ angle *= Math.PI / 180;
+ var center = Point.read(arguments, 1),
+ x = center.x,
+ y = center.y,
+ cos = Math.cos(angle),
+ sin = Math.sin(angle),
+ tx = x - x * cos + y * sin,
+ ty = y - x * sin - y * cos,
+ a = this._a,
+ b = this._b,
+ c = this._c,
+ d = this._d;
+ this._a = cos * a + sin * b;
+ this._b = -sin * a + cos * b;
+ this._c = cos * c + sin * d;
+ this._d = -sin * c + cos * d;
+ this._tx += tx * a + ty * b;
+ this._ty += tx * c + ty * d;
+ this._changed();
+ return this;
+ },
+
+ shear: function() {
+ var shear = Point.read(arguments),
+ center = Point.read(arguments, 0, { readNull: true });
+ if (center)
+ this.translate(center);
+ var a = this._a,
+ c = this._c;
+ this._a += shear.y * this._b;
+ this._c += shear.y * this._d;
+ this._b += shear.x * a;
+ this._d += shear.x * c;
+ if (center)
+ this.translate(center.negate());
+ this._changed();
+ return this;
+ },
+
+ skew: function() {
+ var skew = Point.read(arguments),
+ center = Point.read(arguments, 0, { readNull: true }),
+ toRadians = Math.PI / 180,
+ shear = new Point(Math.tan(skew.x * toRadians),
+ Math.tan(skew.y * toRadians));
+ return this.shear(shear, center);
+ },
+
+ concatenate: function(mx) {
+ var a1 = this._a,
+ b1 = this._b,
+ c1 = this._c,
+ d1 = this._d,
+ a2 = mx._a,
+ b2 = mx._b,
+ c2 = mx._c,
+ d2 = mx._d,
+ tx2 = mx._tx,
+ ty2 = mx._ty;
+ this._a = a2 * a1 + c2 * b1;
+ this._b = b2 * a1 + d2 * b1;
+ this._c = a2 * c1 + c2 * d1;
+ this._d = b2 * c1 + d2 * d1;
+ this._tx += tx2 * a1 + ty2 * b1;
+ this._ty += tx2 * c1 + ty2 * d1;
+ this._changed();
+ return this;
+ },
+
+ preConcatenate: function(mx) {
+ var a1 = this._a,
+ b1 = this._b,
+ c1 = this._c,
+ d1 = this._d,
+ tx1 = this._tx,
+ ty1 = this._ty,
+ a2 = mx._a,
+ b2 = mx._b,
+ c2 = mx._c,
+ d2 = mx._d,
+ tx2 = mx._tx,
+ ty2 = mx._ty;
+ this._a = a2 * a1 + b2 * c1;
+ this._b = a2 * b1 + b2 * d1;
+ this._c = c2 * a1 + d2 * c1;
+ this._d = c2 * b1 + d2 * d1;
+ this._tx = a2 * tx1 + b2 * ty1 + tx2;
+ this._ty = c2 * tx1 + d2 * ty1 + ty2;
+ this._changed();
+ return this;
+ },
+
+ chain: function(mx) {
+ var a1 = this._a,
+ b1 = this._b,
+ c1 = this._c,
+ d1 = this._d,
+ tx1 = this._tx,
+ ty1 = this._ty,
+ a2 = mx._a,
+ b2 = mx._b,
+ c2 = mx._c,
+ d2 = mx._d,
+ tx2 = mx._tx,
+ ty2 = mx._ty;
+ return new Matrix(
+ a2 * a1 + c2 * b1,
+ a2 * c1 + c2 * d1,
+ b2 * a1 + d2 * b1,
+ b2 * c1 + d2 * d1,
+ tx1 + tx2 * a1 + ty2 * b1,
+ ty1 + tx2 * c1 + ty2 * d1);
+ },
+
+ isIdentity: function() {
+ return this._a === 1 && this._c === 0 && this._b === 0 && this._d === 1
+ && this._tx === 0 && this._ty === 0;
+ },
+
+ orNullIfIdentity: function() {
+ return this.isIdentity() ? null : this;
+ },
+
+ isInvertible: function() {
+ return !!this._getDeterminant();
+ },
+
+ isSingular: function() {
+ return !this._getDeterminant();
+ },
+
+ transform: function( src, dst, count) {
+ return arguments.length < 3
+ ? this._transformPoint(Point.read(arguments))
+ : this._transformCoordinates(src, dst, count);
+ },
+
+ _transformPoint: function(point, dest, _dontNotify) {
+ var x = point.x,
+ y = point.y;
+ if (!dest)
+ dest = new Point();
+ return dest.set(
+ x * this._a + y * this._b + this._tx,
+ x * this._c + y * this._d + this._ty,
+ _dontNotify
+ );
+ },
+
+ _transformCoordinates: function(src, dst, count) {
+ var i = 0,
+ j = 0,
+ max = 2 * count;
+ while (i < max) {
+ var x = src[i++],
+ y = src[i++];
+ dst[j++] = x * this._a + y * this._b + this._tx;
+ dst[j++] = x * this._c + y * this._d + this._ty;
+ }
+ return dst;
+ },
+
+ _transformCorners: function(rect) {
+ var x1 = rect.x,
+ y1 = rect.y,
+ x2 = x1 + rect.width,
+ y2 = y1 + rect.height,
+ coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
+ return this._transformCoordinates(coords, coords, 4);
+ },
+
+ _transformBounds: function(bounds, dest, _dontNotify) {
+ var coords = this._transformCorners(bounds),
+ min = coords.slice(0, 2),
+ max = coords.slice();
+ for (var i = 2; i < 8; i++) {
+ var val = coords[i],
+ j = i & 1;
+ if (val < min[j])
+ min[j] = val;
+ else if (val > max[j])
+ max[j] = val;
+ }
+ if (!dest)
+ dest = new Rectangle();
+ return dest.set(min[0], min[1], max[0] - min[0], max[1] - min[1],
+ _dontNotify);
+ },
+
+ inverseTransform: function() {
+ return this._inverseTransform(Point.read(arguments));
+ },
+
+ _getDeterminant: function() {
+ var det = this._a * this._d - this._b * this._c;
+ return isFinite(det) && !Numerical.isZero(det)
+ && isFinite(this._tx) && isFinite(this._ty)
+ ? det : null;
+ },
+
+ _inverseTransform: function(point, dest, _dontNotify) {
+ var det = this._getDeterminant();
+ if (!det)
+ return null;
+ var x = point.x - this._tx,
+ y = point.y - this._ty;
+ if (!dest)
+ dest = new Point();
+ return dest.set(
+ (x * this._d - y * this._b) / det,
+ (y * this._a - x * this._c) / det,
+ _dontNotify
+ );
+ },
+
+ decompose: function() {
+ var a = this._a, b = this._b, c = this._c, d = this._d;
+ if (Numerical.isZero(a * d - b * c))
+ return null;
+
+ var scaleX = Math.sqrt(a * a + b * b);
+ a /= scaleX;
+ b /= scaleX;
+
+ var shear = a * c + b * d;
+ c -= a * shear;
+ d -= b * shear;
+
+ var scaleY = Math.sqrt(c * c + d * d);
+ c /= scaleY;
+ d /= scaleY;
+ shear /= scaleY;
+
+ if (a * d < b * c) {
+ a = -a;
+ b = -b;
+ shear = -shear;
+ scaleX = -scaleX;
+ }
+
+ return {
+ scaling: new Point(scaleX, scaleY),
+ rotation: -Math.atan2(b, a) * 180 / Math.PI,
+ shearing: shear
+ };
+ },
+
+ getValues: function() {
+ return [ this._a, this._c, this._b, this._d, this._tx, this._ty ];
+ },
+
+ getTranslation: function() {
+ return new Point(this._tx, this._ty);
+ },
+
+ getScaling: function() {
+ return (this.decompose() || {}).scaling;
+ },
+
+ getRotation: function() {
+ return (this.decompose() || {}).rotation;
+ },
+
+ inverted: function() {
+ var det = this._getDeterminant();
+ return det && new Matrix(
+ this._d / det,
+ -this._c / det,
+ -this._b / det,
+ this._a / det,
+ (this._b * this._ty - this._d * this._tx) / det,
+ (this._c * this._tx - this._a * this._ty) / det);
+ },
+
+ shiftless: function() {
+ return new Matrix(this._a, this._c, this._b, this._d, 0, 0);
+ },
+
+ applyToContext: function(ctx) {
+ ctx.transform(this._a, this._c, this._b, this._d, this._tx, this._ty);
+ }
+}, Base.each(['a', 'c', 'b', 'd', 'tx', 'ty'], function(name) {
+ var part = Base.capitalize(name),
+ prop = '_' + name;
+ this['get' + part] = function() {
+ return this[prop];
+ };
+ this['set' + part] = function(value) {
+ this[prop] = value;
+ this._changed();
+ };
+}, {}));
+
+var Line = Base.extend({
+ _class: 'Line',
+
+ initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
+ var asVector = false;
+ if (arguments.length >= 4) {
+ this._px = arg0;
+ this._py = arg1;
+ this._vx = arg2;
+ this._vy = arg3;
+ asVector = arg4;
+ } else {
+ this._px = arg0.x;
+ this._py = arg0.y;
+ this._vx = arg1.x;
+ this._vy = arg1.y;
+ asVector = arg2;
+ }
+ if (!asVector) {
+ this._vx -= this._px;
+ this._vy -= this._py;
+ }
+ },
+
+ getPoint: function() {
+ return new Point(this._px, this._py);
+ },
+
+ getVector: function() {
+ return new Point(this._vx, this._vy);
+ },
+
+ getLength: function() {
+ return this.getVector().getLength();
+ },
+
+ intersect: function(line, isInfinite) {
+ return Line.intersect(
+ this._px, this._py, this._vx, this._vy,
+ line._px, line._py, line._vx, line._vy,
+ true, isInfinite);
+ },
+
+ getSide: function(point) {
+ return Line.getSide(
+ this._px, this._py, this._vx, this._vy,
+ point.x, point.y, true);
+ },
+
+ getDistance: function(point) {
+ return Math.abs(Line.getSignedDistance(
+ this._px, this._py, this._vx, this._vy,
+ point.x, point.y, true));
+ },
+
+ statics: {
+ intersect: function(apx, apy, avx, avy, bpx, bpy, bvx, bvy, asVector,
+ isInfinite) {
+ if (!asVector) {
+ avx -= apx;
+ avy -= apy;
+ bvx -= bpx;
+ bvy -= bpy;
+ }
+ var cross = avx * bvy - avy * bvx;
+ if (!Numerical.isZero(cross)) {
+ var dx = apx - bpx,
+ dy = apy - bpy,
+ ta = (bvx * dy - bvy * dx) / cross,
+ tb = (avx * dy - avy * dx) / cross;
+ if (isInfinite || 0 <= ta && ta <= 1 && 0 <= tb && tb <= 1)
+ return new Point(
+ apx + ta * avx,
+ apy + ta * avy);
+ }
+ },
+
+ getSide: function(px, py, vx, vy, x, y, asVector) {
+ if (!asVector) {
+ vx -= px;
+ vy -= py;
+ }
+ var v2x = x - px,
+ v2y = y - py,
+ ccw = v2x * vy - v2y * vx;
+ if (ccw === 0) {
+ ccw = v2x * vx + v2y * vy;
+ if (ccw > 0) {
+ v2x -= vx;
+ v2y -= vy;
+ ccw = v2x * vx + v2y * vy;
+ if (ccw < 0)
+ ccw = 0;
+ }
+ }
+ return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
+ },
+
+ getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
+ if (!asVector) {
+ vx -= px;
+ vy -= py;
+ }
+ if (Numerical.isZero(vx))
+ return x - px;
+ var m = vy / vx,
+ b = py - m * px;
+ return (y - (m * x) - b) / Math.sqrt(m * m + 1);
+ }
+ }
+});
+
+var Project = PaperScopeItem.extend({
+ _class: 'Project',
+ _list: 'projects',
+ _reference: 'project',
+
+ initialize: function Project(element) {
+ PaperScopeItem.call(this, true);
+ this.layers = [];
+ this._activeLayer = null;
+ this.symbols = [];
+ this._currentStyle = new Style(null, null, this);
+ this._view = View.create(this,
+ element || CanvasProvider.getCanvas(1, 1));
+ this._selectedItems = {};
+ this._selectedItemCount = 0;
+ this._updateVersion = 0;
+ },
+
+ _serialize: function(options, dictionary) {
+ return Base.serialize(this.layers, options, true, dictionary);
+ },
+
+ clear: function() {
+ for (var i = this.layers.length - 1; i >= 0; i--)
+ this.layers[i].remove();
+ this.symbols = [];
+ },
+
+ isEmpty: function() {
+ return this.layers.length === 0;
+ },
+
+ remove: function remove() {
+ if (!remove.base.call(this))
+ return false;
+ if (this._view)
+ this._view.remove();
+ return true;
+ },
+
+ getView: function() {
+ return this._view;
+ },
+
+ getCurrentStyle: function() {
+ return this._currentStyle;
+ },
+
+ setCurrentStyle: function(style) {
+ this._currentStyle.initialize(style);
+ },
+
+ getIndex: function() {
+ return this._index;
+ },
+
+ getOptions: function() {
+ return this._scope.settings;
+ },
+
+ getActiveLayer: function() {
+ return this._activeLayer || new Layer({ project: this });
+ },
+
+ getSelectedItems: function() {
+ var items = [];
+ for (var id in this._selectedItems) {
+ var item = this._selectedItems[id];
+ if (item.isInserted())
+ items.push(item);
+ }
+ return items;
+ },
+
+ addChild: function(child) {
+ if (child instanceof Layer) {
+ Base.splice(this.layers, [child]);
+ if (!this._activeLayer)
+ this._activeLayer = child;
+ } else if (child instanceof Item) {
+ (this._activeLayer
+ || this.addChild(new Layer(Item.NO_INSERT))).addChild(child);
+ } else {
+ child = null;
+ }
+ return child;
+ },
+
+ _updateSelection: function(item) {
+ var id = item._id,
+ selectedItems = this._selectedItems;
+ if (item._selected) {
+ if (selectedItems[id] !== item) {
+ this._selectedItemCount++;
+ selectedItems[id] = item;
+ }
+ } else if (selectedItems[id] === item) {
+ this._selectedItemCount--;
+ delete selectedItems[id];
+ }
+ },
+
+ selectAll: function() {
+ var layers = this.layers;
+ for (var i = 0, l = layers.length; i < l; i++)
+ layers[i].setFullySelected(true);
+ },
+
+ deselectAll: function() {
+ var selectedItems = this._selectedItems;
+ for (var i in selectedItems)
+ selectedItems[i].setFullySelected(false);
+ },
+
+ hitTest: function() {
+ var point = Point.read(arguments),
+ options = HitResult.getOptions(Base.read(arguments));
+ for (var i = this.layers.length - 1; i >= 0; i--) {
+ var res = this.layers[i]._hitTest(point, options);
+ if (res) return res;
+ }
+ return null;
+ },
+
+ getItems: function(match) {
+ return Item._getItems(this.layers, match);
+ },
+
+ getItem: function(match) {
+ return Item._getItems(this.layers, match, null, null, true)[0] || null;
+ },
+
+ importJSON: function(json) {
+ this.activate();
+ var layer = this._activeLayer;
+ return Base.importJSON(json, layer && layer.isEmpty() && layer);
+ },
+
+ draw: function(ctx, matrix, pixelRatio) {
+ this._updateVersion++;
+ ctx.save();
+ matrix.applyToContext(ctx);
+ var param = new Base({
+ offset: new Point(0, 0),
+ pixelRatio: pixelRatio,
+ viewMatrix: matrix.isIdentity() ? null : matrix,
+ matrices: [new Matrix()],
+ updateMatrix: true
+ });
+ for (var i = 0, layers = this.layers, l = layers.length; i < l; i++)
+ layers[i].draw(ctx, param);
+ ctx.restore();
+
+ if (this._selectedItemCount > 0) {
+ ctx.save();
+ ctx.strokeWidth = 1;
+ var items = this._selectedItems,
+ size = this._scope.settings.handleSize,
+ version = this._updateVersion;
+ for (var id in items)
+ items[id]._drawSelection(ctx, matrix, size, items, version);
+ ctx.restore();
+ }
+ }
+});
+
+var Symbol = Base.extend({
+ _class: 'Symbol',
+
+ initialize: function Symbol(item, dontCenter) {
+ this._id = Symbol._id = (Symbol._id || 0) + 1;
+ this.project = paper.project;
+ this.project.symbols.push(this);
+ if (item)
+ this.setDefinition(item, dontCenter);
+ },
+
+ _serialize: function(options, dictionary) {
+ return dictionary.add(this, function() {
+ return Base.serialize([this._class, this._definition],
+ options, false, dictionary);
+ });
+ },
+
+ _changed: function(flags) {
+ if (flags & 8) {
+ Item._clearBoundsCache(this);
+ }
+ if (flags & 1) {
+ this.project._needsUpdate = true;
+ }
+ },
+
+ getDefinition: function() {
+ return this._definition;
+ },
+
+ setDefinition: function(item, _dontCenter) {
+ if (item._parentSymbol)
+ item = item.clone();
+ if (this._definition)
+ this._definition._parentSymbol = null;
+ this._definition = item;
+ item.remove();
+ item.setSelected(false);
+ if (!_dontCenter)
+ item.setPosition(new Point());
+ item._parentSymbol = this;
+ this._changed(9);
+ },
+
+ place: function(position) {
+ return new PlacedSymbol(this, position);
+ },
+
+ clone: function() {
+ return new Symbol(this._definition.clone(false));
+ }
+});
+
+var Item = Base.extend(Emitter, {
+ statics: {
+ extend: function extend(src) {
+ if (src._serializeFields)
+ src._serializeFields = new Base(
+ this.prototype._serializeFields, src._serializeFields);
+ return extend.base.apply(this, arguments);
+ },
+
+ NO_INSERT: { insert: false }
+ },
+
+ _class: 'Item',
+ _applyMatrix: true,
+ _canApplyMatrix: true,
+ _boundsSelected: false,
+ _selectChildren: false,
+ _serializeFields: {
+ name: null,
+ applyMatrix: null,
+ matrix: new Matrix(),
+ pivot: null,
+ locked: false,
+ visible: true,
+ blendMode: 'normal',
+ opacity: 1,
+ guide: false,
+ selected: false,
+ clipMask: false,
+ data: {}
+ },
+
+ initialize: function Item() {
+ },
+
+ _initialize: function(props, point) {
+ var hasProps = props && Base.isPlainObject(props),
+ internal = hasProps && props.internal === true,
+ matrix = this._matrix = new Matrix(),
+ project = hasProps && props.project || paper.project;
+ if (!internal)
+ this._id = Item._id = (Item._id || 0) + 1;
+ this._applyMatrix = this._canApplyMatrix && paper.settings.applyMatrix;
+ if (point)
+ matrix.translate(point);
+ matrix._owner = this;
+ this._style = new Style(project._currentStyle, this, project);
+ if (!this._project) {
+ if (internal || hasProps && props.insert === false) {
+ this._setProject(project);
+ } else if (hasProps && props.parent) {
+ this.setParent(props.parent);
+ } else {
+ (project._activeLayer || new Layer()).addChild(this);
+ }
+ }
+ if (hasProps && props !== Item.NO_INSERT)
+ this._set(props, { insert: true, parent: true }, true);
+ return hasProps;
+ },
+
+ _events: new function() {
+
+ var mouseFlags = {
+ mousedown: {
+ mousedown: 1,
+ mousedrag: 1,
+ click: 1,
+ doubleclick: 1
+ },
+ mouseup: {
+ mouseup: 1,
+ mousedrag: 1,
+ click: 1,
+ doubleclick: 1
+ },
+ mousemove: {
+ mousedrag: 1,
+ mousemove: 1,
+ mouseenter: 1,
+ mouseleave: 1
+ }
+ };
+
+ var mouseEvent = {
+ install: function(type) {
+ var counters = this.getView()._eventCounters;
+ if (counters) {
+ for (var key in mouseFlags) {
+ counters[key] = (counters[key] || 0)
+ + (mouseFlags[key][type] || 0);
+ }
+ }
+ },
+ uninstall: function(type) {
+ var counters = this.getView()._eventCounters;
+ if (counters) {
+ for (var key in mouseFlags)
+ counters[key] -= mouseFlags[key][type] || 0;
+ }
+ }
+ };
+
+ return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
+ 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'],
+ function(name) {
+ this[name] = mouseEvent;
+ }, {
+ onFrame: {
+ install: function() {
+ this._animateItem(true);
+ },
+ uninstall: function() {
+ this._animateItem(false);
+ }
+ },
+
+ onLoad: {}
+ }
+ );
+ },
+
+ _animateItem: function(animate) {
+ this.getView()._animateItem(this, animate);
+ },
+
+ _serialize: function(options, dictionary) {
+ var props = {},
+ that = this;
+
+ function serialize(fields) {
+ for (var key in fields) {
+ var value = that[key];
+ if (!Base.equals(value, key === 'leading'
+ ? fields.fontSize * 1.2 : fields[key])) {
+ props[key] = Base.serialize(value, options,
+ key !== 'data', dictionary);
+ }
+ }
+ }
+
+ serialize(this._serializeFields);
+ if (!(this instanceof Group))
+ serialize(this._style._defaults);
+ return [ this._class, props ];
+ },
+
+ _changed: function(flags) {
+ var symbol = this._parentSymbol,
+ cacheParent = this._parent || symbol,
+ project = this._project;
+ if (flags & 8) {
+ this._bounds = this._position = this._decomposed =
+ this._globalMatrix = this._currentPath = undefined;
+ }
+ if (cacheParent
+ && (flags & 40)) {
+ Item._clearBoundsCache(cacheParent);
+ }
+ if (flags & 2) {
+ Item._clearBoundsCache(this);
+ }
+ if (project) {
+ if (flags & 1) {
+ project._needsUpdate = true;
+ }
+ if (project._changes) {
+ var entry = project._changesById[this._id];
+ if (entry) {
+ entry.flags |= flags;
+ } else {
+ entry = { item: this, flags: flags };
+ project._changesById[this._id] = entry;
+ project._changes.push(entry);
+ }
+ }
+ }
+ if (symbol)
+ symbol._changed(flags);
+ },
+
+ set: function(props) {
+ if (props)
+ this._set(props);
+ return this;
+ },
+
+ getId: function() {
+ return this._id;
+ },
+
+ getClassName: function() {
+ return this._class;
+ },
+
+ getName: function() {
+ return this._name;
+ },
+
+ setName: function(name, unique) {
+
+ if (this._name)
+ this._removeNamed();
+ if (name === (+name) + '')
+ throw new Error(
+ 'Names consisting only of numbers are not supported.');
+ var parent = this._parent;
+ if (name && parent) {
+ var children = parent._children,
+ namedChildren = parent._namedChildren,
+ orig = name,
+ i = 1;
+ while (unique && children[name])
+ name = orig + ' ' + (i++);
+ (namedChildren[name] = namedChildren[name] || []).push(this);
+ children[name] = this;
+ }
+ this._name = name || undefined;
+ this._changed(128);
+ },
+
+ getStyle: function() {
+ return this._style;
+ },
+
+ setStyle: function(style) {
+ this.getStyle().set(style);
+ }
+}, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
+ function(name) {
+ var part = Base.capitalize(name),
+ name = '_' + name;
+ this['get' + part] = function() {
+ return this[name];
+ };
+ this['set' + part] = function(value) {
+ if (value != this[name]) {
+ this[name] = value;
+ this._changed(name === '_locked'
+ ? 128 : 129);
+ }
+ };
+ },
+{}), {
+ beans: true,
+
+ _locked: false,
+
+ _visible: true,
+
+ _blendMode: 'normal',
+
+ _opacity: 1,
+
+ _guide: false,
+
+ isSelected: function() {
+ if (this._selectChildren) {
+ var children = this._children;
+ for (var i = 0, l = children.length; i < l; i++)
+ if (children[i].isSelected())
+ return true;
+ }
+ return this._selected;
+ },
+
+ setSelected: function(selected, noChildren) {
+ if (!noChildren && this._selectChildren) {
+ var children = this._children;
+ for (var i = 0, l = children.length; i < l; i++)
+ children[i].setSelected(selected);
+ }
+ if ((selected = !!selected) ^ this._selected) {
+ this._selected = selected;
+ this._project._updateSelection(this);
+ this._changed(129);
+ }
+ },
+
+ _selected: false,
+
+ isFullySelected: function() {
+ var children = this._children;
+ if (children && this._selected) {
+ for (var i = 0, l = children.length; i < l; i++)
+ if (!children[i].isFullySelected())
+ return false;
+ return true;
+ }
+ return this._selected;
+ },
+
+ setFullySelected: function(selected) {
+ var children = this._children;
+ if (children) {
+ for (var i = 0, l = children.length; i < l; i++)
+ children[i].setFullySelected(selected);
+ }
+ this.setSelected(selected, true);
+ },
+
+ isClipMask: function() {
+ return this._clipMask;
+ },
+
+ setClipMask: function(clipMask) {
+ if (this._clipMask != (clipMask = !!clipMask)) {
+ this._clipMask = clipMask;
+ if (clipMask) {
+ this.setFillColor(null);
+ this.setStrokeColor(null);
+ }
+ this._changed(129);
+ if (this._parent)
+ this._parent._changed(1024);
+ }
+ },
+
+ _clipMask: false,
+
+ getData: function() {
+ if (!this._data)
+ this._data = {};
+ return this._data;
+ },
+
+ setData: function(data) {
+ this._data = data;
+ },
+
+ getPosition: function(_dontLink) {
+ var position = this._position,
+ ctor = _dontLink ? Point : LinkedPoint;
+ if (!position) {
+ var pivot = this._pivot;
+ position = this._position = pivot
+ ? this._matrix._transformPoint(pivot)
+ : this.getBounds().getCenter(true);
+ }
+ return new ctor(position.x, position.y, this, 'setPosition');
+ },
+
+ setPosition: function() {
+ this.translate(Point.read(arguments).subtract(this.getPosition(true)));
+ },
+
+ getPivot: function(_dontLink) {
+ var pivot = this._pivot;
+ if (pivot) {
+ var ctor = _dontLink ? Point : LinkedPoint;
+ pivot = new ctor(pivot.x, pivot.y, this, 'setPivot');
+ }
+ return pivot;
+ },
+
+ setPivot: function() {
+ this._pivot = Point.read(arguments);
+ this._position = undefined;
+ },
+
+ _pivot: null,
+
+ getRegistration: '#getPivot',
+ setRegistration: '#setPivot'
+}, Base.each(['bounds', 'strokeBounds', 'handleBounds', 'roughBounds',
+ 'internalBounds', 'internalRoughBounds'],
+ function(key) {
+ var getter = 'get' + Base.capitalize(key),
+ match = key.match(/^internal(.*)$/),
+ internalGetter = match ? 'get' + match[1] : null;
+ this[getter] = function(_matrix) {
+ var boundsGetter = this._boundsGetter,
+ name = !internalGetter && (typeof boundsGetter === 'string'
+ ? boundsGetter : boundsGetter && boundsGetter[getter])
+ || getter,
+ bounds = this._getCachedBounds(name, _matrix, this,
+ internalGetter);
+ return key === 'bounds'
+ ? new LinkedRectangle(bounds.x, bounds.y, bounds.width,
+ bounds.height, this, 'setBounds')
+ : bounds;
+ };
+ },
+{
+ beans: true,
+
+ _getBounds: function(getter, matrix, cacheItem) {
+ var children = this._children;
+ if (!children || children.length == 0)
+ return new Rectangle();
+ var x1 = Infinity,
+ x2 = -x1,
+ y1 = x1,
+ y2 = x2;
+ for (var i = 0, l = children.length; i < l; i++) {
+ var child = children[i];
+ if (child._visible && !child.isEmpty()) {
+ var rect = child._getCachedBounds(getter,
+ matrix && matrix.chain(child._matrix), cacheItem);
+ x1 = Math.min(rect.x, x1);
+ y1 = Math.min(rect.y, y1);
+ x2 = Math.max(rect.x + rect.width, x2);
+ y2 = Math.max(rect.y + rect.height, y2);
+ }
+ }
+ return isFinite(x1)
+ ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
+ : new Rectangle();
+ },
+
+ setBounds: function() {
+ var rect = Rectangle.read(arguments),
+ bounds = this.getBounds(),
+ matrix = new Matrix(),
+ center = rect.getCenter();
+ matrix.translate(center);
+ if (rect.width != bounds.width || rect.height != bounds.height) {
+ matrix.scale(
+ bounds.width != 0 ? rect.width / bounds.width : 1,
+ bounds.height != 0 ? rect.height / bounds.height : 1);
+ }
+ center = bounds.getCenter();
+ matrix.translate(-center.x, -center.y);
+ this.transform(matrix);
+ },
+
+ _getCachedBounds: function(getter, matrix, cacheItem, internalGetter) {
+ matrix = matrix && matrix.orNullIfIdentity();
+ var _matrix = internalGetter ? null : this._matrix.orNullIfIdentity(),
+ cache = (!matrix || matrix.equals(_matrix)) && getter;
+ var cacheParent = this._parent || this._parentSymbol;
+ if (cacheParent) {
+ var id = cacheItem._id,
+ ref = cacheParent._boundsCache = cacheParent._boundsCache || {
+ ids: {},
+ list: []
+ };
+ if (!ref.ids[id]) {
+ ref.list.push(cacheItem);
+ ref.ids[id] = cacheItem;
+ }
+ }
+ if (cache && this._bounds && this._bounds[cache])
+ return this._bounds[cache].clone();
+ var bounds = this._getBounds(internalGetter || getter,
+ matrix || _matrix, cacheItem);
+ if (cache) {
+ if (!this._bounds)
+ this._bounds = {};
+ var cached = this._bounds[cache] = bounds.clone();
+ cached._internal = !!internalGetter;
+ }
+ return bounds;
+ },
+
+ statics: {
+ _clearBoundsCache: function(item) {
+ var cache = item._boundsCache;
+ if (cache) {
+ item._bounds = item._position = item._boundsCache = undefined;
+ for (var i = 0, list = cache.list, l = list.length; i < l; i++) {
+ var other = list[i];
+ if (other !== item) {
+ other._bounds = other._position = undefined;
+ if (other._boundsCache)
+ Item._clearBoundsCache(other);
+ }
+ }
+ }
+ }
+ }
+
+}), {
+ beans: true,
+
+ _decompose: function() {
+ return this._decomposed = this._matrix.decompose();
+ },
+
+ getRotation: function() {
+ var decomposed = this._decomposed || this._decompose();
+ return decomposed && decomposed.rotation;
+ },
+
+ setRotation: function(rotation) {
+ var current = this.getRotation();
+ if (current != null && rotation != null) {
+ var decomposed = this._decomposed;
+ this.rotate(rotation - current);
+ decomposed.rotation = rotation;
+ this._decomposed = decomposed;
+ }
+ },
+
+ getScaling: function(_dontLink) {
+ var decomposed = this._decomposed || this._decompose(),
+ scaling = decomposed && decomposed.scaling,
+ ctor = _dontLink ? Point : LinkedPoint;
+ return scaling && new ctor(scaling.x, scaling.y, this, 'setScaling');
+ },
+
+ setScaling: function() {
+ var current = this.getScaling();
+ if (current) {
+ var scaling = Point.read(arguments, 0, { clone: true }),
+ decomposed = this._decomposed;
+ this.scale(scaling.x / current.x, scaling.y / current.y);
+ decomposed.scaling = scaling;
+ this._decomposed = decomposed;
+ }
+ },
+
+ getMatrix: function() {
+ return this._matrix;
+ },
+
+ setMatrix: function(matrix) {
+ this._matrix.initialize(matrix);
+ if (this._applyMatrix) {
+ this.transform(null, true);
+ } else {
+ this._changed(9);
+ }
+ },
+
+ getGlobalMatrix: function(_dontClone) {
+ var matrix = this._globalMatrix,
+ updateVersion = this._project._updateVersion;
+ if (matrix && matrix._updateVersion !== updateVersion)
+ matrix = null;
+ if (!matrix) {
+ matrix = this._globalMatrix = this._matrix.clone();
+ var parent = this._parent;
+ if (parent)
+ matrix.preConcatenate(parent.getGlobalMatrix(true));
+ matrix._updateVersion = updateVersion;
+ }
+ return _dontClone ? matrix : matrix.clone();
+ },
+
+ getApplyMatrix: function() {
+ return this._applyMatrix;
+ },
+
+ setApplyMatrix: function(transform) {
+ if (this._applyMatrix = this._canApplyMatrix && !!transform)
+ this.transform(null, true);
+ },
+
+ getTransformContent: '#getApplyMatrix',
+ setTransformContent: '#setApplyMatrix',
+}, {
+ getProject: function() {
+ return this._project;
+ },
+
+ _setProject: function(project, installEvents) {
+ if (this._project !== project) {
+ if (this._project)
+ this._installEvents(false);
+ this._project = project;
+ var children = this._children;
+ for (var i = 0, l = children && children.length; i < l; i++)
+ children[i]._setProject(project);
+ installEvents = true;
+ }
+ if (installEvents)
+ this._installEvents(true);
+ },
+
+ getView: function() {
+ return this._project.getView();
+ },
+
+ _installEvents: function _installEvents(install) {
+ _installEvents.base.call(this, install);
+ var children = this._children;
+ for (var i = 0, l = children && children.length; i < l; i++)
+ children[i]._installEvents(install);
+ },
+
+ getLayer: function() {
+ var parent = this;
+ while (parent = parent._parent) {
+ if (parent instanceof Layer)
+ return parent;
+ }
+ return null;
+ },
+
+ getParent: function() {
+ return this._parent;
+ },
+
+ setParent: function(item) {
+ return item.addChild(this);
+ },
+
+ getChildren: function() {
+ return this._children;
+ },
+
+ setChildren: function(items) {
+ this.removeChildren();
+ this.addChildren(items);
+ },
+
+ getFirstChild: function() {
+ return this._children && this._children[0] || null;
+ },
+
+ getLastChild: function() {
+ return this._children && this._children[this._children.length - 1]
+ || null;
+ },
+
+ getNextSibling: function() {
+ return this._parent && this._parent._children[this._index + 1] || null;
+ },
+
+ getPreviousSibling: function() {
+ return this._parent && this._parent._children[this._index - 1] || null;
+ },
+
+ getIndex: function() {
+ return this._index;
+ },
+
+ equals: function(item) {
+ return item === this || item && this._class === item._class
+ && this._style.equals(item._style)
+ && this._matrix.equals(item._matrix)
+ && this._locked === item._locked
+ && this._visible === item._visible
+ && this._blendMode === item._blendMode
+ && this._opacity === item._opacity
+ && this._clipMask === item._clipMask
+ && this._guide === item._guide
+ && this._equals(item)
+ || false;
+ },
+
+ _equals: function(item) {
+ return Base.equals(this._children, item._children);
+ },
+
+ clone: function(insert) {
+ return this._clone(new this.constructor(Item.NO_INSERT), insert);
+ },
+
+ _clone: function(copy, insert) {
+ copy.setStyle(this._style);
+ if (this._children) {
+ for (var i = 0, l = this._children.length; i < l; i++)
+ copy.addChild(this._children[i].clone(false), true);
+ }
+ if (insert || insert === undefined)
+ copy.insertAbove(this);
+ var keys = ['_locked', '_visible', '_blendMode', '_opacity',
+ '_clipMask', '_guide', '_applyMatrix'];
+ for (var i = 0, l = keys.length; i < l; i++) {
+ var key = keys[i];
+ if (this.hasOwnProperty(key))
+ copy[key] = this[key];
+ }
+ copy._matrix.initialize(this._matrix);
+ copy._data = this._data ? Base.clone(this._data) : null;
+ copy.setSelected(this._selected);
+ if (this._name)
+ copy.setName(this._name, true);
+ return copy;
+ },
+
+ copyTo: function(itemOrProject) {
+ return itemOrProject.addChild(this.clone(false));
+ },
+
+ rasterize: function(resolution) {
+ var bounds = this.getStrokeBounds(),
+ scale = (resolution || this.getView().getResolution()) / 72,
+ topLeft = bounds.getTopLeft().floor(),
+ bottomRight = bounds.getBottomRight().ceil(),
+ size = new Size(bottomRight.subtract(topLeft)),
+ canvas = CanvasProvider.getCanvas(size.multiply(scale)),
+ ctx = canvas.getContext('2d'),
+ matrix = new Matrix().scale(scale).translate(topLeft.negate());
+ ctx.save();
+ matrix.applyToContext(ctx);
+ this.draw(ctx, new Base({ matrices: [matrix] }));
+ ctx.restore();
+ var raster = new Raster(Item.NO_INSERT);
+ raster.setCanvas(canvas);
+ raster.transform(new Matrix().translate(topLeft.add(size.divide(2)))
+ .scale(1 / scale));
+ raster.insertAbove(this);
+ return raster;
+ },
+
+ contains: function() {
+ return !!this._contains(
+ this._matrix._inverseTransform(Point.read(arguments)));
+ },
+
+ _contains: function(point) {
+ if (this._children) {
+ for (var i = this._children.length - 1; i >= 0; i--) {
+ if (this._children[i].contains(point))
+ return true;
+ }
+ return false;
+ }
+ return point.isInside(this.getInternalBounds());
+ },
+
+ isInside: function() {
+ return Rectangle.read(arguments).contains(this.getBounds());
+ },
+
+ _asPathItem: function() {
+ return new Path.Rectangle({
+ rectangle: this.getInternalBounds(),
+ matrix: this._matrix,
+ insert: false,
+ });
+ },
+
+ intersects: function(item, _matrix) {
+ if (!(item instanceof Item))
+ return false;
+ return this._asPathItem().getIntersections(item._asPathItem(),
+ _matrix || item._matrix).length > 0;
+ },
+
+ hitTest: function() {
+ return this._hitTest(
+ Point.read(arguments),
+ HitResult.getOptions(Base.read(arguments)));
+ },
+
+ _hitTest: function(point, options) {
+ if (this._locked || !this._visible || this._guide && !options.guides
+ || this.isEmpty())
+ return null;
+
+ var matrix = this._matrix,
+ parentTotalMatrix = options._totalMatrix,
+ view = this.getView(),
+ totalMatrix = options._totalMatrix = parentTotalMatrix
+ ? parentTotalMatrix.chain(matrix)
+ : this.getGlobalMatrix().preConcatenate(view._matrix),
+ tolerancePadding = options._tolerancePadding = new Size(
+ Path._getPenPadding(1, totalMatrix.inverted())
+ ).multiply(
+ Math.max(options.tolerance, 0.00001)
+ );
+ point = matrix._inverseTransform(point);
+
+ if (!this._children && !this.getInternalRoughBounds()
+ .expand(tolerancePadding.multiply(2))._containsPoint(point))
+ return null;
+ var checkSelf = !(options.guides && !this._guide
+ || options.selected && !this._selected
+ || options.type && options.type !== Base.hyphenate(this._class)
+ || options.class && !(this instanceof options.class)),
+ that = this,
+ res;
+
+ function checkBounds(type, part) {
+ var pt = bounds['get' + part]();
+ if (point.subtract(pt).divide(tolerancePadding).length <= 1)
+ return new HitResult(type, that,
+ { name: Base.hyphenate(part), point: pt });
+ }
+
+ if (checkSelf && (options.center || options.bounds) && this._parent) {
+ var bounds = this.getInternalBounds();
+ if (options.center)
+ res = checkBounds('center', 'Center');
+ if (!res && options.bounds) {
+ var points = [
+ 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
+ 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
+ ];
+ for (var i = 0; i < 8 && !res; i++)
+ res = checkBounds('bounds', points[i]);
+ }
+ }
+
+ var children = !res && this._children;
+ if (children) {
+ var opts = this._getChildHitTestOptions(options);
+ for (var i = children.length - 1; i >= 0 && !res; i--)
+ res = children[i]._hitTest(point, opts);
+ }
+ if (!res && checkSelf)
+ res = this._hitTestSelf(point, options);
+ if (res && res.point)
+ res.point = matrix.transform(res.point);
+ options._totalMatrix = parentTotalMatrix;
+ return res;
+ },
+
+ _getChildHitTestOptions: function(options) {
+ return options;
+ },
+
+ _hitTestSelf: function(point, options) {
+ if (options.fill && this.hasFill() && this._contains(point))
+ return new HitResult('fill', this);
+ },
+
+ matches: function(name, compare) {
+ function matchObject(obj1, obj2) {
+ for (var i in obj1) {
+ if (obj1.hasOwnProperty(i)) {
+ var val1 = obj1[i],
+ val2 = obj2[i];
+ if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
+ if (!matchObject(val1, val2))
+ return false;
+ } else if (!Base.equals(val1, val2)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ if (typeof name === 'object') {
+ for (var key in name) {
+ if (name.hasOwnProperty(key) && !this.matches(key, name[key]))
+ return false;
+ }
+ } else {
+ var value = /^(empty|editable)$/.test(name)
+ ? this['is' + Base.capitalize(name)]()
+ : name === 'type'
+ ? Base.hyphenate(this._class)
+ : this[name];
+ if (/^(constructor|class)$/.test(name)) {
+ if (!(this instanceof compare))
+ return false;
+ } else if (compare instanceof RegExp) {
+ if (!compare.test(value))
+ return false;
+ } else if (typeof compare === 'function') {
+ if (!compare(value))
+ return false;
+ } else if (Base.isPlainObject(compare)) {
+ if (!matchObject(compare, value))
+ return false;
+ } else if (!Base.equals(value, compare)) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ getItems: function(match) {
+ return Item._getItems(this._children, match, this._matrix);
+ },
+
+ getItem: function(match) {
+ return Item._getItems(this._children, match, this._matrix, null, true)
+ [0] || null;
+ },
+
+ statics: {
+ _getItems: function _getItems(children, match, matrix, param,
+ firstOnly) {
+ if (!param) {
+ var overlapping = match.overlapping,
+ inside = match.inside,
+ bounds = overlapping || inside,
+ rect = bounds && Rectangle.read([bounds]);
+ param = {
+ items: [],
+ inside: rect,
+ overlapping: overlapping && new Path.Rectangle({
+ rectangle: rect,
+ insert: false
+ })
+ };
+ if (bounds)
+ match = Base.set({}, match,
+ { inside: true, overlapping: true });
+ }
+ var items = param.items,
+ inside = param.inside,
+ overlapping = param.overlapping;
+ matrix = inside && (matrix || new Matrix());
+ for (var i = 0, l = children && children.length; i < l; i++) {
+ var child = children[i],
+ childMatrix = matrix && matrix.chain(child._matrix),
+ add = true;
+ if (inside) {
+ var bounds = child.getBounds(childMatrix);
+ if (!inside.intersects(bounds))
+ continue;
+ if (!(inside && inside.contains(bounds)) && !(overlapping
+ && overlapping.intersects(child, childMatrix)))
+ add = false;
+ }
+ if (add && child.matches(match)) {
+ items.push(child);
+ if (firstOnly)
+ break;
+ }
+ _getItems(child._children, match,
+ childMatrix, param,
+ firstOnly);
+ if (firstOnly && items.length > 0)
+ break;
+ }
+ return items;
+ }
+ }
+}, {
+
+ importJSON: function(json) {
+ var res = Base.importJSON(json, this);
+ return res !== this
+ ? this.addChild(res)
+ : res;
+ },
+
+ addChild: function(item, _preserve) {
+ return this.insertChild(undefined, item, _preserve);
+ },
+
+ insertChild: function(index, item, _preserve) {
+ var res = this.insertChildren(index, [item], _preserve);
+ return res && res[0];
+ },
+
+ addChildren: function(items, _preserve) {
+ return this.insertChildren(this._children.length, items, _preserve);
+ },
+
+ insertChildren: function(index, items, _preserve, _proto) {
+ var children = this._children;
+ if (children && items && items.length > 0) {
+ items = Array.prototype.slice.apply(items);
+ for (var i = items.length - 1; i >= 0; i--) {
+ var item = items[i];
+ if (_proto && !(item instanceof _proto)) {
+ items.splice(i, 1);
+ } else {
+ item._remove(false, true);
+ }
+ }
+ Base.splice(children, items, index, 0);
+ var project = this._project,
+ notifySelf = project && project._changes;
+ for (var i = 0, l = items.length; i < l; i++) {
+ var item = items[i];
+ item._parent = this;
+ item._setProject(this._project, true);
+ if (item._name)
+ item.setName(item._name);
+ if (notifySelf)
+ this._changed(5);
+ }
+ this._changed(11);
+ } else {
+ items = null;
+ }
+ return items;
+ },
+
+ _insert: function(above, item, _preserve) {
+ if (!item._parent)
+ return null;
+ var index = item._index + (above ? 1 : 0);
+ if (item._parent === this._parent && index > this._index)
+ index--;
+ return item._parent.insertChild(index, this, _preserve);
+ },
+
+ insertAbove: function(item, _preserve) {
+ return this._insert(true, item, _preserve);
+ },
+
+ insertBelow: function(item, _preserve) {
+ return this._insert(false, item, _preserve);
+ },
+
+ sendToBack: function() {
+ return this._parent.insertChild(0, this);
+ },
+
+ bringToFront: function() {
+ return this._parent.addChild(this);
+ },
+
+ appendTop: '#addChild',
+
+ appendBottom: function(item) {
+ return this.insertChild(0, item);
+ },
+
+ moveAbove: '#insertAbove',
+
+ moveBelow: '#insertBelow',
+
+ reduce: function() {
+ if (this._children && this._children.length === 1) {
+ var child = this._children[0].reduce();
+ child.insertAbove(this);
+ child.setStyle(this._style);
+ this.remove();
+ return child;
+ }
+ return this;
+ },
+
+ _removeNamed: function() {
+ var parent = this._parent;
+ if (parent) {
+ var children = parent._children,
+ namedChildren = parent._namedChildren,
+ name = this._name,
+ namedArray = namedChildren[name],
+ index = namedArray ? namedArray.indexOf(this) : -1;
+ if (index !== -1) {
+ if (children[name] == this)
+ delete children[name];
+ namedArray.splice(index, 1);
+ if (namedArray.length) {
+ children[name] = namedArray[namedArray.length - 1];
+ } else {
+ delete namedChildren[name];
+ }
+ }
+ }
+ },
+
+ _remove: function(notifySelf, notifyParent) {
+ var parent = this._parent;
+ if (parent) {
+ if (this._name)
+ this._removeNamed();
+ if (this._index != null)
+ Base.splice(parent._children, null, this._index, 1);
+ this._installEvents(false);
+ if (notifySelf) {
+ var project = this._project;
+ if (project && project._changes)
+ this._changed(5);
+ }
+ if (notifyParent)
+ parent._changed(11);
+ this._parent = null;
+ return true;
+ }
+ return false;
+ },
+
+ remove: function() {
+ return this._remove(true, true);
+ },
+
+ replaceWith: function(item) {
+ var ok = item && item.insertBelow(this);
+ if (ok)
+ this.remove();
+ return ok;
+ },
+
+ removeChildren: function(from, to) {
+ if (!this._children)
+ return null;
+ from = from || 0;
+ to = Base.pick(to, this._children.length);
+ var removed = Base.splice(this._children, null, from, to - from);
+ for (var i = removed.length - 1; i >= 0; i--) {
+ removed[i]._remove(true, false);
+ }
+ if (removed.length > 0)
+ this._changed(11);
+ return removed;
+ },
+
+ clear: '#removeChildren',
+
+ reverseChildren: function() {
+ if (this._children) {
+ this._children.reverse();
+ for (var i = 0, l = this._children.length; i < l; i++)
+ this._children[i]._index = i;
+ this._changed(11);
+ }
+ },
+
+ isEmpty: function() {
+ return !this._children || this._children.length === 0;
+ },
+
+ isEditable: function() {
+ var item = this;
+ while (item) {
+ if (!item._visible || item._locked)
+ return false;
+ item = item._parent;
+ }
+ return true;
+ },
+
+ hasFill: function() {
+ return this.getStyle().hasFill();
+ },
+
+ hasStroke: function() {
+ return this.getStyle().hasStroke();
+ },
+
+ hasShadow: function() {
+ return this.getStyle().hasShadow();
+ },
+
+ _getOrder: function(item) {
+ function getList(item) {
+ var list = [];
+ do {
+ list.unshift(item);
+ } while (item = item._parent);
+ return list;
+ }
+ var list1 = getList(this),
+ list2 = getList(item);
+ for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
+ if (list1[i] != list2[i]) {
+ return list1[i]._index < list2[i]._index ? 1 : -1;
+ }
+ }
+ return 0;
+ },
+
+ hasChildren: function() {
+ return this._children && this._children.length > 0;
+ },
+
+ isInserted: function() {
+ return this._parent ? this._parent.isInserted() : false;
+ },
+
+ isAbove: function(item) {
+ return this._getOrder(item) === -1;
+ },
+
+ isBelow: function(item) {
+ return this._getOrder(item) === 1;
+ },
+
+ isParent: function(item) {
+ return this._parent === item;
+ },
+
+ isChild: function(item) {
+ return item && item._parent === this;
+ },
+
+ isDescendant: function(item) {
+ var parent = this;
+ while (parent = parent._parent) {
+ if (parent == item)
+ return true;
+ }
+ return false;
+ },
+
+ isAncestor: function(item) {
+ return item ? item.isDescendant(this) : false;
+ },
+
+ isGroupedWith: function(item) {
+ var parent = this._parent;
+ while (parent) {
+ if (parent._parent
+ && /^(Group|Layer|CompoundPath)$/.test(parent._class)
+ && item.isDescendant(parent))
+ return true;
+ parent = parent._parent;
+ }
+ return false;
+ },
+
+ translate: function() {
+ var mx = new Matrix();
+ return this.transform(mx.translate.apply(mx, arguments));
+ },
+
+ rotate: function(angle ) {
+ return this.transform(new Matrix().rotate(angle,
+ Point.read(arguments, 1, { readNull: true })
+ || this.getPosition(true)));
+ }
+}, Base.each(['scale', 'shear', 'skew'], function(name) {
+ this[name] = function() {
+ var point = Point.read(arguments),
+ center = Point.read(arguments, 0, { readNull: true });
+ return this.transform(new Matrix()[name](point,
+ center || this.getPosition(true)));
+ };
+}, {
+
+}), {
+ transform: function(matrix, _applyMatrix) {
+ if (matrix && matrix.isIdentity())
+ matrix = null;
+ var _matrix = this._matrix,
+ applyMatrix = (_applyMatrix || this._applyMatrix)
+ && (!_matrix.isIdentity() || matrix);
+ if (!matrix && !applyMatrix)
+ return this;
+ if (matrix)
+ _matrix.preConcatenate(matrix);
+ if (applyMatrix = applyMatrix && this._transformContent(_matrix)) {
+ var pivot = this._pivot,
+ style = this._style,
+ fillColor = style.getFillColor(true),
+ strokeColor = style.getStrokeColor(true);
+ if (pivot)
+ _matrix._transformPoint(pivot, pivot, true);
+ if (fillColor)
+ fillColor.transform(_matrix);
+ if (strokeColor)
+ strokeColor.transform(_matrix);
+ _matrix.reset(true);
+ }
+ var bounds = this._bounds,
+ position = this._position;
+ this._changed(9);
+ var decomp = bounds && matrix && matrix.decompose();
+ if (decomp && !decomp.shearing && decomp.rotation % 90 === 0) {
+ for (var key in bounds) {
+ var rect = bounds[key];
+ if (applyMatrix || !rect._internal)
+ matrix._transformBounds(rect, rect);
+ }
+ var getter = this._boundsGetter,
+ rect = bounds[getter && getter.getBounds || getter || 'getBounds'];
+ if (rect)
+ this._position = rect.getCenter(true);
+ this._bounds = bounds;
+ } else if (matrix && position) {
+ this._position = matrix._transformPoint(position, position);
+ }
+ return this;
+ },
+
+ _transformContent: function(matrix) {
+ var children = this._children;
+ if (children) {
+ for (var i = 0, l = children.length; i < l; i++)
+ children[i].transform(matrix, true);
+ return true;
+ }
+ },
+
+ globalToLocal: function() {
+ return this.getGlobalMatrix(true)._inverseTransform(
+ Point.read(arguments));
+ },
+
+ localToGlobal: function() {
+ return this.getGlobalMatrix(true)._transformPoint(
+ Point.read(arguments));
+ },
+
+ parentToLocal: function() {
+ return this._matrix._inverseTransform(Point.read(arguments));
+ },
+
+ localToParent: function() {
+ return this._matrix._transformPoint(Point.read(arguments));
+ },
+
+ fitBounds: function(rectangle, fill) {
+ rectangle = Rectangle.read(arguments);
+ var bounds = this.getBounds(),
+ itemRatio = bounds.height / bounds.width,
+ rectRatio = rectangle.height / rectangle.width,
+ scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
+ ? rectangle.width / bounds.width
+ : rectangle.height / bounds.height,
+ newBounds = new Rectangle(new Point(),
+ new Size(bounds.width * scale, bounds.height * scale));
+ newBounds.setCenter(rectangle.getCenter());
+ this.setBounds(newBounds);
+ },
+
+ _setStyles: function(ctx) {
+ var style = this._style,
+ fillColor = style.getFillColor(),
+ strokeColor = style.getStrokeColor(),
+ shadowColor = style.getShadowColor();
+ if (fillColor)
+ ctx.fillStyle = fillColor.toCanvasStyle(ctx);
+ if (strokeColor) {
+ var strokeWidth = style.getStrokeWidth();
+ if (strokeWidth > 0) {
+ ctx.strokeStyle = strokeColor.toCanvasStyle(ctx);
+ ctx.lineWidth = strokeWidth;
+ var strokeJoin = style.getStrokeJoin(),
+ strokeCap = style.getStrokeCap(),
+ miterLimit = style.getMiterLimit();
+ if (strokeJoin)
+ ctx.lineJoin = strokeJoin;
+ if (strokeCap)
+ ctx.lineCap = strokeCap;
+ if (miterLimit)
+ ctx.miterLimit = miterLimit;
+ if (paper.support.nativeDash) {
+ var dashArray = style.getDashArray(),
+ dashOffset = style.getDashOffset();
+ if (dashArray && dashArray.length) {
+ if ('setLineDash' in ctx) {
+ ctx.setLineDash(dashArray);
+ ctx.lineDashOffset = dashOffset;
+ } else {
+ ctx.mozDash = dashArray;
+ ctx.mozDashOffset = dashOffset;
+ }
+ }
+ }
+ }
+ }
+ if (shadowColor) {
+ var shadowBlur = style.getShadowBlur();
+ if (shadowBlur > 0) {
+ ctx.shadowColor = shadowColor.toCanvasStyle(ctx);
+ ctx.shadowBlur = shadowBlur;
+ var offset = this.getShadowOffset();
+ ctx.shadowOffsetX = offset.x;
+ ctx.shadowOffsetY = offset.y;
+ }
+ }
+ },
+
+ draw: function(ctx, param, parentStrokeMatrix) {
+ var updateVersion = this._updateVersion = this._project._updateVersion;
+ if (!this._visible || this._opacity === 0)
+ return;
+ var matrices = param.matrices,
+ viewMatrix = param.viewMatrix,
+ matrix = this._matrix,
+ globalMatrix = matrices[matrices.length - 1].chain(matrix);
+ if (!globalMatrix.isInvertible())
+ return;
+
+ function getViewMatrix(matrix) {
+ return viewMatrix ? viewMatrix.chain(matrix) : matrix;
+ }
+
+ matrices.push(globalMatrix);
+ if (param.updateMatrix) {
+ globalMatrix._updateVersion = updateVersion;
+ this._globalMatrix = globalMatrix;
+ }
+
+ var blendMode = this._blendMode,
+ opacity = this._opacity,
+ normalBlend = blendMode === 'normal',
+ nativeBlend = BlendMode.nativeModes[blendMode],
+ direct = normalBlend && opacity === 1
+ || param.dontStart
+ || param.clip
+ || (nativeBlend || normalBlend && opacity < 1)
+ && this._canComposite(),
+ pixelRatio = param.pixelRatio,
+ mainCtx, itemOffset, prevOffset;
+ if (!direct) {
+ var bounds = this.getStrokeBounds(getViewMatrix(globalMatrix));
+ if (!bounds.width || !bounds.height)
+ return;
+ prevOffset = param.offset;
+ itemOffset = param.offset = bounds.getTopLeft().floor();
+ mainCtx = ctx;
+ ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1)
+ .multiply(pixelRatio));
+ if (pixelRatio !== 1)
+ ctx.scale(pixelRatio, pixelRatio);
+ }
+ ctx.save();
+ var strokeMatrix = parentStrokeMatrix
+ ? parentStrokeMatrix.chain(matrix)
+ : !this.getStrokeScaling(true) && getViewMatrix(globalMatrix),
+ clip = !direct && param.clipItem,
+ transform = !strokeMatrix || clip;
+ if (direct) {
+ ctx.globalAlpha = opacity;
+ if (nativeBlend)
+ ctx.globalCompositeOperation = blendMode;
+ } else if (transform) {
+ ctx.translate(-itemOffset.x, -itemOffset.y);
+ }
+ if (transform)
+ (direct ? matrix : getViewMatrix(globalMatrix)).applyToContext(ctx);
+ if (clip)
+ param.clipItem.draw(ctx, param.extend({ clip: true }));
+ if (strokeMatrix) {
+ ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
+ var offset = param.offset;
+ if (offset)
+ ctx.translate(-offset.x, -offset.y);
+ }
+ this._draw(ctx, param, strokeMatrix);
+ ctx.restore();
+ matrices.pop();
+ if (param.clip && !param.dontFinish)
+ ctx.clip();
+ if (!direct) {
+ BlendMode.process(blendMode, ctx, mainCtx, opacity,
+ itemOffset.subtract(prevOffset).multiply(pixelRatio));
+ CanvasProvider.release(ctx);
+ param.offset = prevOffset;
+ }
+ },
+
+ _isUpdated: function(updateVersion) {
+ var parent = this._parent;
+ if (parent instanceof CompoundPath)
+ return parent._isUpdated(updateVersion);
+ var updated = this._updateVersion === updateVersion;
+ if (!updated && parent && parent._visible
+ && parent._isUpdated(updateVersion)) {
+ this._updateVersion = updateVersion;
+ updated = true;
+ }
+ return updated;
+ },
+
+ _drawSelection: function(ctx, matrix, size, selectedItems, updateVersion) {
+ if ((this._drawSelected || this._boundsSelected)
+ && this._isUpdated(updateVersion)) {
+ var color = this.getSelectedColor(true)
+ || this.getLayer().getSelectedColor(true),
+ mx = matrix.chain(this.getGlobalMatrix(true));
+ ctx.strokeStyle = ctx.fillStyle = color
+ ? color.toCanvasStyle(ctx) : '#009dec';
+ if (this._drawSelected)
+ this._drawSelected(ctx, mx, selectedItems);
+ if (this._boundsSelected) {
+ var half = size / 2;
+ coords = mx._transformCorners(this.getInternalBounds());
+ ctx.beginPath();
+ for (var i = 0; i < 8; i++)
+ ctx[i === 0 ? 'moveTo' : 'lineTo'](coords[i], coords[++i]);
+ ctx.closePath();
+ ctx.stroke();
+ for (var i = 0; i < 8; i++)
+ ctx.fillRect(coords[i] - half, coords[++i] - half,
+ size, size);
+ }
+ }
+ },
+
+ _canComposite: function() {
+ return false;
+ }
+}, Base.each(['down', 'drag', 'up', 'move'], function(name) {
+ this['removeOn' + Base.capitalize(name)] = function() {
+ var hash = {};
+ hash[name] = true;
+ return this.removeOn(hash);
+ };
+}, {
+
+ removeOn: function(obj) {
+ for (var name in obj) {
+ if (obj[name]) {
+ var key = 'mouse' + name,
+ project = this._project,
+ sets = project._removeSets = project._removeSets || {};
+ sets[key] = sets[key] || {};
+ sets[key][this._id] = this;
+ }
+ }
+ return this;
+ }
+}));
+
+var Group = Item.extend({
+ _class: 'Group',
+ _selectChildren: true,
+ _serializeFields: {
+ children: []
+ },
+
+ initialize: function Group(arg) {
+ this._children = [];
+ this._namedChildren = {};
+ if (!this._initialize(arg))
+ this.addChildren(Array.isArray(arg) ? arg : arguments);
+ },
+
+ _changed: function _changed(flags) {
+ _changed.base.call(this, flags);
+ if (flags & 1026) {
+ this._clipItem = undefined;
+ }
+ },
+
+ _getClipItem: function() {
+ var clipItem = this._clipItem;
+ if (clipItem === undefined) {
+ clipItem = null;
+ for (var i = 0, l = this._children.length; i < l; i++) {
+ var child = this._children[i];
+ if (child._clipMask) {
+ clipItem = child;
+ break;
+ }
+ }
+ this._clipItem = clipItem;
+ }
+ return clipItem;
+ },
+
+ isClipped: function() {
+ return !!this._getClipItem();
+ },
+
+ setClipped: function(clipped) {
+ var child = this.getFirstChild();
+ if (child)
+ child.setClipMask(clipped);
+ },
+
+ _draw: function(ctx, param) {
+ var clip = param.clip,
+ clipItem = !clip && this._getClipItem(),
+ draw = true;
+ param = param.extend({ clipItem: clipItem, clip: false });
+ if (clip) {
+ if (this._currentPath) {
+ ctx.currentPath = this._currentPath;
+ draw = false;
+ } else {
+ ctx.beginPath();
+ param.dontStart = param.dontFinish = true;
+ }
+ } else if (clipItem) {
+ clipItem.draw(ctx, param.extend({ clip: true }));
+ }
+ if (draw) {
+ for (var i = 0, l = this._children.length; i < l; i++) {
+ var item = this._children[i];
+ if (item !== clipItem)
+ item.draw(ctx, param);
+ }
+ }
+ if (clip) {
+ this._currentPath = ctx.currentPath;
+ }
+ }
+});
+
+var Layer = Group.extend({
+ _class: 'Layer',
+
+ initialize: function Layer(arg) {
+ var props = Base.isPlainObject(arg)
+ ? new Base(arg)
+ : { children: Array.isArray(arg) ? arg : arguments },
+ insert = props.insert;
+ props.insert = false;
+ Group.call(this, props);
+ if (insert || insert === undefined) {
+ this._project.addChild(this);
+ this.activate();
+ }
+ },
+
+ _remove: function _remove(notify) {
+ if (this._parent)
+ return _remove.base.call(this, notify);
+ if (this._index != null) {
+ var project = this._project;
+ if (project._activeLayer === this)
+ project._activeLayer = this.getNextSibling()
+ || this.getPreviousSibling();
+ Base.splice(project.layers, null, this._index, 1);
+ this._installEvents(false);
+ project._needsUpdate = true;
+ return true;
+ }
+ return false;
+ },
+
+ getNextSibling: function getNextSibling() {
+ return this._parent ? getNextSibling.base.call(this)
+ : this._project.layers[this._index + 1] || null;
+ },
+
+ getPreviousSibling: function getPreviousSibling() {
+ return this._parent ? getPreviousSibling.base.call(this)
+ : this._project.layers[this._index - 1] || null;
+ },
+
+ isInserted: function isInserted() {
+ return this._parent ? isInserted.base.call(this) : this._index != null;
+ },
+
+ activate: function() {
+ this._project._activeLayer = this;
+ },
+
+ _insert: function _insert(above, item, _preserve) {
+ if (item instanceof Layer && !item._parent) {
+ this._remove(true, true);
+ Base.splice(item._project.layers, [this],
+ item._index + (above ? 1 : 0), 0);
+ this._setProject(item._project, true);
+ return this;
+ }
+ return _insert.base.call(this, above, item, _preserve);
+ }
+});
+
+var Shape = Item.extend({
+ _class: 'Shape',
+ _applyMatrix: false,
+ _canApplyMatrix: false,
+ _boundsSelected: true,
+ _serializeFields: {
+ type: null,
+ size: null,
+ radius: null
+ },
+
+ initialize: function Shape(props) {
+ this._initialize(props);
+ },
+
+ _equals: function(item) {
+ return this._type === item._type
+ && this._size.equals(item._size)
+ && Base.equals(this._radius, item._radius);
+ },
+
+ clone: function(insert) {
+ var copy = new Shape(Item.NO_INSERT);
+ copy.setType(this._type);
+ copy.setSize(this._size);
+ copy.setRadius(this._radius);
+ return this._clone(copy, insert);
+ },
+
+ getType: function() {
+ return this._type;
+ },
+
+ setType: function(type) {
+ this._type = type;
+ },
+
+ getShape: '#getType',
+ setShape: '#setType',
+
+ getSize: function() {
+ var size = this._size;
+ return new LinkedSize(size.width, size.height, this, 'setSize');
+ },
+
+ setSize: function() {
+ var size = Size.read(arguments);
+ if (!this._size) {
+ this._size = size.clone();
+ } else if (!this._size.equals(size)) {
+ var type = this._type,
+ width = size.width,
+ height = size.height;
+ if (type === 'rectangle') {
+ var radius = Size.min(this._radius, size.divide(2));
+ this._radius.set(radius.width, radius.height);
+ } else if (type === 'circle') {
+ width = height = (width + height) / 2;
+ this._radius = width / 2;
+ } else if (type === 'ellipse') {
+ this._radius.set(width / 2, height / 2);
+ }
+ this._size.set(width, height);
+ this._changed(9);
+ }
+ },
+
+ getRadius: function() {
+ var rad = this._radius;
+ return this._type === 'circle'
+ ? rad
+ : new LinkedSize(rad.width, rad.height, this, 'setRadius');
+ },
+
+ setRadius: function(radius) {
+ var type = this._type;
+ if (type === 'circle') {
+ if (radius === this._radius)
+ return;
+ var size = radius * 2;
+ this._radius = radius;
+ this._size.set(size, size);
+ } else {
+ radius = Size.read(arguments);
+ if (!this._radius) {
+ this._radius = radius.clone();
+ } else {
+ if (this._radius.equals(radius))
+ return;
+ this._radius.set(radius.width, radius.height);
+ if (type === 'rectangle') {
+ var size = Size.max(this._size, radius.multiply(2));
+ this._size.set(size.width, size.height);
+ } else if (type === 'ellipse') {
+ this._size.set(radius.width * 2, radius.height * 2);
+ }
+ }
+ }
+ this._changed(9);
+ },
+
+ isEmpty: function() {
+ return false;
+ },
+
+ toPath: function(insert) {
+ var path = new Path[Base.capitalize(this._type)]({
+ center: new Point(),
+ size: this._size,
+ radius: this._radius,
+ insert: false
+ });
+ path.setStyle(this._style);
+ path.transform(this._matrix);
+ if (insert || insert === undefined)
+ path.insertAbove(this);
+ return path;
+ },
+
+ _draw: function(ctx, param, strokeMatrix) {
+ var style = this._style,
+ hasFill = style.hasFill(),
+ hasStroke = style.hasStroke(),
+ dontPaint = param.dontFinish || param.clip,
+ untransformed = !strokeMatrix;
+ if (hasFill || hasStroke || dontPaint) {
+ var type = this._type,
+ radius = this._radius,
+ isCircle = type === 'circle';
+ if (!param.dontStart)
+ ctx.beginPath();
+ if (untransformed && isCircle) {
+ ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
+ } else {
+ var rx = isCircle ? radius : radius.width,
+ ry = isCircle ? radius : radius.height,
+ size = this._size,
+ width = size.width,
+ height = size.height;
+ if (untransformed && type === 'rect' && rx === 0 && ry === 0) {
+ ctx.rect(-width / 2, -height / 2, width, height);
+ } else {
+ var x = width / 2,
+ y = height / 2,
+ kappa = 1 - 0.5522847498307936,
+ cx = rx * kappa,
+ cy = ry * kappa,
+ c = [
+ -x, -y + ry,
+ -x, -y + cy,
+ -x + cx, -y,
+ -x + rx, -y,
+ x - rx, -y,
+ x - cx, -y,
+ x, -y + cy,
+ x, -y + ry,
+ x, y - ry,
+ x, y - cy,
+ x - cx, y,
+ x - rx, y,
+ -x + rx, y,
+ -x + cx, y,
+ -x, y - cy,
+ -x, y - ry
+ ];
+ if (strokeMatrix)
+ strokeMatrix.transform(c, c, 32);
+ ctx.moveTo(c[0], c[1]);
+ ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]);
+ if (x !== rx)
+ ctx.lineTo(c[8], c[9]);
+ ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]);
+ if (y !== ry)
+ ctx.lineTo(c[16], c[17]);
+ ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]);
+ if (x !== rx)
+ ctx.lineTo(c[24], c[25]);
+ ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]);
+ }
+ }
+ ctx.closePath();
+ }
+ if (!dontPaint && (hasFill || hasStroke)) {
+ this._setStyles(ctx);
+ if (hasFill) {
+ ctx.fill(style.getWindingRule());
+ ctx.shadowColor = 'rgba(0,0,0,0)';
+ }
+ if (hasStroke)
+ ctx.stroke();
+ }
+ },
+
+ _canComposite: function() {
+ return !(this.hasFill() && this.hasStroke());
+ },
+
+ _getBounds: function(getter, matrix) {
+ var rect = new Rectangle(this._size).setCenter(0, 0);
+ if (getter !== 'getBounds' && this.hasStroke())
+ rect = rect.expand(this.getStrokeWidth());
+ return matrix ? matrix._transformBounds(rect) : rect;
+ }
+},
+new function() {
+
+ function getCornerCenter(that, point, expand) {
+ var radius = that._radius;
+ if (!radius.isZero()) {
+ var halfSize = that._size.divide(2);
+ for (var i = 0; i < 4; i++) {
+ var dir = new Point(i & 1 ? 1 : -1, i > 1 ? 1 : -1),
+ corner = dir.multiply(halfSize),
+ center = corner.subtract(dir.multiply(radius)),
+ rect = new Rectangle(corner, center);
+ if ((expand ? rect.expand(expand) : rect).contains(point))
+ return center;
+ }
+ }
+ }
+
+ function getEllipseRadius(point, radius) {
+ var angle = point.getAngleInRadians(),
+ width = radius.width * 2,
+ height = radius.height * 2,
+ x = width * Math.sin(angle),
+ y = height * Math.cos(angle);
+ return width * height / (2 * Math.sqrt(x * x + y * y));
+ }
+
+ return {
+ _contains: function _contains(point) {
+ if (this._type === 'rectangle') {
+ var center = getCornerCenter(this, point);
+ return center
+ ? point.subtract(center).divide(this._radius)
+ .getLength() <= 1
+ : _contains.base.call(this, point);
+ } else {
+ return point.divide(this.size).getLength() <= 0.5;
+ }
+ },
+
+ _hitTestSelf: function _hitTestSelf(point, options) {
+ var hit = false;
+ if (this.hasStroke()) {
+ var type = this._type,
+ radius = this._radius,
+ strokeWidth = this.getStrokeWidth() + 2 * options.tolerance;
+ if (type === 'rectangle') {
+ var center = getCornerCenter(this, point, strokeWidth);
+ if (center) {
+ var pt = point.subtract(center);
+ hit = 2 * Math.abs(pt.getLength()
+ - getEllipseRadius(pt, radius)) <= strokeWidth;
+ } else {
+ var rect = new Rectangle(this._size).setCenter(0, 0),
+ outer = rect.expand(strokeWidth),
+ inner = rect.expand(-strokeWidth);
+ hit = outer._containsPoint(point)
+ && !inner._containsPoint(point);
+ }
+ } else {
+ if (type === 'ellipse')
+ radius = getEllipseRadius(point, radius);
+ hit = 2 * Math.abs(point.getLength() - radius)
+ <= strokeWidth;
+ }
+ }
+ return hit
+ ? new HitResult('stroke', this)
+ : _hitTestSelf.base.apply(this, arguments);
+ }
+ };
+}, {
+
+statics: new function() {
+ function createShape(type, point, size, radius, args) {
+ var item = new Shape(Base.getNamed(args));
+ item._type = type;
+ item._size = size;
+ item._radius = radius;
+ return item.translate(point);
+ }
+
+ return {
+ Circle: function() {
+ var center = Point.readNamed(arguments, 'center'),
+ radius = Base.readNamed(arguments, 'radius');
+ return createShape('circle', center, new Size(radius * 2), radius,
+ arguments);
+ },
+
+ Rectangle: function() {
+ var rect = Rectangle.readNamed(arguments, 'rectangle'),
+ radius = Size.min(Size.readNamed(arguments, 'radius'),
+ rect.getSize(true).divide(2));
+ return createShape('rectangle', rect.getCenter(true),
+ rect.getSize(true), radius, arguments);
+ },
+
+ Ellipse: function() {
+ var ellipse = Shape._readEllipse(arguments),
+ radius = ellipse.radius;
+ return createShape('ellipse', ellipse.center, radius.multiply(2),
+ radius, arguments);
+ },
+
+ _readEllipse: function(args) {
+ var center,
+ radius;
+ if (Base.hasNamed(args, 'radius')) {
+ center = Point.readNamed(args, 'center');
+ radius = Size.readNamed(args, 'radius');
+ } else {
+ var rect = Rectangle.readNamed(args, 'rectangle');
+ center = rect.getCenter(true);
+ radius = rect.getSize(true).divide(2);
+ }
+ return { center: center, radius: radius };
+ }
+ };
+}});
+
+var Raster = Item.extend({
+ _class: 'Raster',
+ _applyMatrix: false,
+ _canApplyMatrix: false,
+ _boundsGetter: 'getBounds',
+ _boundsSelected: true,
+ _serializeFields: {
+ source: null
+ },
+
+ initialize: function Raster(object, position) {
+ if (!this._initialize(object,
+ position !== undefined && Point.read(arguments, 1))) {
+ if (typeof object === 'string') {
+ this.setSource(object);
+ } else {
+ this.setImage(object);
+ }
+ }
+ if (!this._size)
+ this._size = new Size();
+ },
+
+ _equals: function(item) {
+ return this.getSource() === item.getSource();
+ },
+
+ clone: function(insert) {
+ var copy = new Raster(Item.NO_INSERT),
+ image = this._image,
+ canvas = this._canvas;
+ if (image) {
+ copy.setImage(image);
+ } else if (canvas) {
+ var copyCanvas = CanvasProvider.getCanvas(this._size);
+ copyCanvas.getContext('2d').drawImage(canvas, 0, 0);
+ copy.setCanvas(copyCanvas);
+ }
+ return this._clone(copy, insert);
+ },
+
+ getSize: function() {
+ var size = this._size;
+ return new LinkedSize(size.width, size.height, this, 'setSize');
+ },
+
+ setSize: function() {
+ var size = Size.read(arguments);
+ if (!this._size.equals(size)) {
+ var element = this.getElement();
+ this.setCanvas(CanvasProvider.getCanvas(size));
+ if (element)
+ this.getContext(true).drawImage(element, 0, 0,
+ size.width, size.height);
+ }
+ },
+
+ getWidth: function() {
+ return this._size.width;
+ },
+
+ getHeight: function() {
+ return this._size.height;
+ },
+
+ isEmpty: function() {
+ return this._size.width === 0 && this._size.height === 0;
+ },
+
+ getResolution: function() {
+ var matrix = this._matrix,
+ orig = new Point(0, 0).transform(matrix),
+ u = new Point(1, 0).transform(matrix).subtract(orig),
+ v = new Point(0, 1).transform(matrix).subtract(orig);
+ return new Size(
+ 72 / u.getLength(),
+ 72 / v.getLength()
+ );
+ },
+
+ getPpi: '#getResolution',
+
+ getImage: function() {
+ return this._image;
+ },
+
+ setImage: function(image) {
+ if (this._canvas)
+ CanvasProvider.release(this._canvas);
+ if (image && image.getContext) {
+ this._image = null;
+ this._canvas = image;
+ } else {
+ this._image = image;
+ this._canvas = null;
+ }
+ this._size = new Size(
+ image ? image.naturalWidth || image.width : 0,
+ image ? image.naturalHeight || image.height : 0);
+ this._context = null;
+ this._changed(521);
+ },
+
+ getCanvas: function() {
+ if (!this._canvas) {
+ var ctx = CanvasProvider.getContext(this._size);
+ try {
+ if (this._image)
+ ctx.drawImage(this._image, 0, 0);
+ this._canvas = ctx.canvas;
+ } catch (e) {
+ CanvasProvider.release(ctx);
+ }
+ }
+ return this._canvas;
+ },
+
+ setCanvas: '#setImage',
+
+ getContext: function(modify) {
+ if (!this._context)
+ this._context = this.getCanvas().getContext('2d');
+ if (modify) {
+ this._image = null;
+ this._changed(513);
+ }
+ return this._context;
+ },
+
+ setContext: function(context) {
+ this._context = context;
+ },
+
+ getSource: function() {
+ return this._image && this._image.src || this.toDataURL();
+ },
+
+ setSource: function(src) {
+ var that = this,
+ image;
+
+ function loaded() {
+ var view = that.getView();
+ if (view) {
+ paper = view._scope;
+ that.setImage(image);
+ that.emit('load');
+ view.update();
+ }
+ }
+
+ image = document.getElementById(src) || new Image();
+
+ if (image.naturalWidth && image.naturalHeight) {
+ setTimeout(loaded, 0);
+ } else {
+ DomEvent.add(image, {
+ load: loaded
+ });
+ if (!image.src)
+ image.src = src;
+ }
+ this.setImage(image);
+ },
+
+ getElement: function() {
+ return this._canvas || this._image;
+ }
+}, {
+ beans: false,
+
+ getSubCanvas: function() {
+ var rect = Rectangle.read(arguments),
+ ctx = CanvasProvider.getContext(rect.getSize());
+ ctx.drawImage(this.getCanvas(), rect.x, rect.y,
+ rect.width, rect.height, 0, 0, rect.width, rect.height);
+ return ctx.canvas;
+ },
+
+ getSubRaster: function() {
+ var rect = Rectangle.read(arguments),
+ raster = new Raster(Item.NO_INSERT);
+ raster.setCanvas(this.getSubCanvas(rect));
+ raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
+ raster._matrix.preConcatenate(this._matrix);
+ raster.insertAbove(this);
+ return raster;
+ },
+
+ toDataURL: function() {
+ var src = this._image && this._image.src;
+ if (/^data:/.test(src))
+ return src;
+ var canvas = this.getCanvas();
+ return canvas ? canvas.toDataURL() : null;
+ },
+
+ drawImage: function(image ) {
+ var point = Point.read(arguments, 1);
+ this.getContext(true).drawImage(image, point.x, point.y);
+ },
+
+ getAverageColor: function(object) {
+ var bounds, path;
+ if (!object) {
+ bounds = this.getBounds();
+ } else if (object instanceof PathItem) {
+ path = object;
+ bounds = object.getBounds();
+ } else if (object.width) {
+ bounds = new Rectangle(object);
+ } else if (object.x) {
+ bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
+ }
+ var sampleSize = 32,
+ width = Math.min(bounds.width, sampleSize),
+ height = Math.min(bounds.height, sampleSize);
+ var ctx = Raster._sampleContext;
+ if (!ctx) {
+ ctx = Raster._sampleContext = CanvasProvider.getContext(
+ new Size(sampleSize));
+ } else {
+ ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
+ }
+ ctx.save();
+ var matrix = new Matrix()
+ .scale(width / bounds.width, height / bounds.height)
+ .translate(-bounds.x, -bounds.y);
+ matrix.applyToContext(ctx);
+ if (path)
+ path.draw(ctx, new Base({ clip: true, matrices: [matrix] }));
+ this._matrix.applyToContext(ctx);
+ ctx.drawImage(this.getElement(),
+ -this._size.width / 2, -this._size.height / 2);
+ ctx.restore();
+ var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
+ Math.ceil(height)).data,
+ channels = [0, 0, 0],
+ total = 0;
+ for (var i = 0, l = pixels.length; i < l; i += 4) {
+ var alpha = pixels[i + 3];
+ total += alpha;
+ alpha /= 255;
+ channels[0] += pixels[i] * alpha;
+ channels[1] += pixels[i + 1] * alpha;
+ channels[2] += pixels[i + 2] * alpha;
+ }
+ for (var i = 0; i < 3; i++)
+ channels[i] /= total;
+ return total ? Color.read(channels) : null;
+ },
+
+ getPixel: function() {
+ var point = Point.read(arguments);
+ var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
+ return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
+ data[3] / 255);
+ },
+
+ setPixel: function() {
+ var point = Point.read(arguments),
+ color = Color.read(arguments),
+ components = color._convert('rgb'),
+ alpha = color._alpha,
+ ctx = this.getContext(true),
+ imageData = ctx.createImageData(1, 1),
+ data = imageData.data;
+ data[0] = components[0] * 255;
+ data[1] = components[1] * 255;
+ data[2] = components[2] * 255;
+ data[3] = alpha != null ? alpha * 255 : 255;
+ ctx.putImageData(imageData, point.x, point.y);
+ },
+
+ createImageData: function() {
+ var size = Size.read(arguments);
+ return this.getContext().createImageData(size.width, size.height);
+ },
+
+ getImageData: function() {
+ var rect = Rectangle.read(arguments);
+ if (rect.isEmpty())
+ rect = new Rectangle(this._size);
+ return this.getContext().getImageData(rect.x, rect.y,
+ rect.width, rect.height);
+ },
+
+ setImageData: function(data ) {
+ var point = Point.read(arguments, 1);
+ this.getContext(true).putImageData(data, point.x, point.y);
+ },
+
+ _getBounds: function(getter, matrix) {
+ var rect = new Rectangle(this._size).setCenter(0, 0);
+ return matrix ? matrix._transformBounds(rect) : rect;
+ },
+
+ _hitTestSelf: function(point) {
+ if (this._contains(point)) {
+ var that = this;
+ return new HitResult('pixel', that, {
+ offset: point.add(that._size.divide(2)).round(),
+ color: {
+ get: function() {
+ return that.getPixel(this.offset);
+ }
+ }
+ });
+ }
+ },
+
+ _draw: function(ctx) {
+ var element = this.getElement();
+ if (element) {
+ ctx.globalAlpha = this._opacity;
+ ctx.drawImage(element,
+ -this._size.width / 2, -this._size.height / 2);
+ }
+ },
+
+ _canComposite: function() {
+ return true;
+ }
+});
+
+var PlacedSymbol = Item.extend({
+ _class: 'PlacedSymbol',
+ _applyMatrix: false,
+ _canApplyMatrix: false,
+ _boundsGetter: { getBounds: 'getStrokeBounds' },
+ _boundsSelected: true,
+ _serializeFields: {
+ symbol: null
+ },
+
+ initialize: function PlacedSymbol(arg0, arg1) {
+ if (!this._initialize(arg0,
+ arg1 !== undefined && Point.read(arguments, 1)))
+ this.setSymbol(arg0 instanceof Symbol ? arg0 : new Symbol(arg0));
+ },
+
+ _equals: function(item) {
+ return this._symbol === item._symbol;
+ },
+
+ getSymbol: function() {
+ return this._symbol;
+ },
+
+ setSymbol: function(symbol) {
+ this._symbol = symbol;
+ this._changed(9);
+ },
+
+ clone: function(insert) {
+ var copy = new PlacedSymbol(Item.NO_INSERT);
+ copy.setSymbol(this._symbol);
+ return this._clone(copy, insert);
+ },
+
+ isEmpty: function() {
+ return this._symbol._definition.isEmpty();
+ },
+
+ _getBounds: function(getter, matrix, cacheItem) {
+ var definition = this.symbol._definition;
+ return definition._getCachedBounds(getter,
+ matrix && matrix.chain(definition._matrix), cacheItem);
+ },
+
+ _hitTestSelf: function(point, options) {
+ var res = this._symbol._definition._hitTest(point, options);
+ if (res)
+ res.item = this;
+ return res;
+ },
+
+ _draw: function(ctx, param) {
+ this.symbol._definition.draw(ctx, param);
+ }
+
+});
+
+var HitResult = Base.extend({
+ _class: 'HitResult',
+
+ initialize: function HitResult(type, item, values) {
+ this.type = type;
+ this.item = item;
+ if (values) {
+ values.enumerable = true;
+ this.inject(values);
+ }
+ },
+
+ statics: {
+ getOptions: function(options) {
+ return new Base({
+ type: null,
+ tolerance: paper.settings.hitTolerance,
+ fill: !options,
+ stroke: !options,
+ segments: !options,
+ handles: false,
+ ends: false,
+ center: false,
+ bounds: false,
+ guides: false,
+ selected: false
+ }, options);
+ }
+ }
+});
+
+var Segment = Base.extend({
+ _class: 'Segment',
+ beans: true,
+
+ initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
+ var count = arguments.length,
+ point, handleIn, handleOut;
+ if (count === 0) {
+ } else if (count === 1) {
+ if (arg0.point) {
+ point = arg0.point;
+ handleIn = arg0.handleIn;
+ handleOut = arg0.handleOut;
+ } else {
+ point = arg0;
+ }
+ } else if (count === 2 && typeof arg0 === 'number') {
+ point = arguments;
+ } else if (count <= 3) {
+ point = arg0;
+ handleIn = arg1;
+ handleOut = arg2;
+ } else {
+ point = arg0 !== undefined ? [ arg0, arg1 ] : null;
+ handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
+ handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
+ }
+ new SegmentPoint(point, this, '_point');
+ new SegmentPoint(handleIn, this, '_handleIn');
+ new SegmentPoint(handleOut, this, '_handleOut');
+ },
+
+ _serialize: function(options) {
+ return Base.serialize(this.isLinear() ? this._point
+ : [this._point, this._handleIn, this._handleOut],
+ options, true);
+ },
+
+ _changed: function(point) {
+ var path = this._path;
+ if (!path)
+ return;
+ var curves = path._curves,
+ index = this._index,
+ curve;
+ if (curves) {
+ if ((!point || point === this._point || point === this._handleIn)
+ && (curve = index > 0 ? curves[index - 1] : path._closed
+ ? curves[curves.length - 1] : null))
+ curve._changed();
+ if ((!point || point === this._point || point === this._handleOut)
+ && (curve = curves[index]))
+ curve._changed();
+ }
+ path._changed(25);
+ },
+
+ getPoint: function() {
+ return this._point;
+ },
+
+ setPoint: function() {
+ var point = Point.read(arguments);
+ this._point.set(point.x, point.y);
+ },
+
+ getHandleIn: function() {
+ return this._handleIn;
+ },
+
+ setHandleIn: function() {
+ var point = Point.read(arguments);
+ this._handleIn.set(point.x, point.y);
+ },
+
+ getHandleOut: function() {
+ return this._handleOut;
+ },
+
+ setHandleOut: function() {
+ var point = Point.read(arguments);
+ this._handleOut.set(point.x, point.y);
+ },
+
+ isLinear: function() {
+ return this._handleIn.isZero() && this._handleOut.isZero();
+ },
+
+ setLinear: function(linear) {
+ if (linear) {
+ this._handleIn.set(0, 0);
+ this._handleOut.set(0, 0);
+ } else {
+ }
+ },
+
+ isColinear: function(segment) {
+ var next1 = this.getNext(),
+ next2 = segment.getNext();
+ return this._handleOut.isZero() && next1._handleIn.isZero()
+ && segment._handleOut.isZero() && next2._handleIn.isZero()
+ && next1._point.subtract(this._point).isColinear(
+ next2._point.subtract(segment._point));
+ },
+
+ isOrthogonal: function() {
+ var prev = this.getPrevious(),
+ next = this.getNext();
+ return prev._handleOut.isZero() && this._handleIn.isZero()
+ && this._handleOut.isZero() && next._handleIn.isZero()
+ && this._point.subtract(prev._point).isOrthogonal(
+ next._point.subtract(this._point));
+ },
+
+ isArc: function() {
+ var next = this.getNext(),
+ handle1 = this._handleOut,
+ handle2 = next._handleIn,
+ kappa = 0.5522847498307936;
+ if (handle1.isOrthogonal(handle2)) {
+ var from = this._point,
+ to = next._point,
+ corner = new Line(from, handle1, true).intersect(
+ new Line(to, handle2, true), true);
+ return corner && Numerical.isZero(handle1.getLength() /
+ corner.subtract(from).getLength() - kappa)
+ && Numerical.isZero(handle2.getLength() /
+ corner.subtract(to).getLength() - kappa);
+ }
+ return false;
+ },
+
+ _selectionState: 0,
+
+ isSelected: function(_point) {
+ var state = this._selectionState;
+ return !_point ? !!(state & 7)
+ : _point === this._point ? !!(state & 4)
+ : _point === this._handleIn ? !!(state & 1)
+ : _point === this._handleOut ? !!(state & 2)
+ : false;
+ },
+
+ setSelected: function(selected, _point) {
+ var path = this._path,
+ selected = !!selected,
+ state = this._selectionState,
+ oldState = state,
+ flag = !_point ? 7
+ : _point === this._point ? 4
+ : _point === this._handleIn ? 1
+ : _point === this._handleOut ? 2
+ : 0;
+ if (selected) {
+ state |= flag;
+ } else {
+ state &= ~flag;
+ }
+ this._selectionState = state;
+ if (path && state !== oldState) {
+ path._updateSelection(this, oldState, state);
+ path._changed(129);
+ }
+ },
+
+ getIndex: function() {
+ return this._index !== undefined ? this._index : null;
+ },
+
+ getPath: function() {
+ return this._path || null;
+ },
+
+ getCurve: function() {
+ var path = this._path,
+ index = this._index;
+ if (path) {
+ if (index > 0 && !path._closed
+ && index === path._segments.length - 1)
+ index--;
+ return path.getCurves()[index] || null;
+ }
+ return null;
+ },
+
+ getLocation: function() {
+ var curve = this.getCurve();
+ return curve
+ ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1)
+ : null;
+ },
+
+ getNext: function() {
+ var segments = this._path && this._path._segments;
+ return segments && (segments[this._index + 1]
+ || this._path._closed && segments[0]) || null;
+ },
+
+ getPrevious: function() {
+ var segments = this._path && this._path._segments;
+ return segments && (segments[this._index - 1]
+ || this._path._closed && segments[segments.length - 1]) || null;
+ },
+
+ reverse: function() {
+ return new Segment(this._point, this._handleOut, this._handleIn);
+ },
+
+ remove: function() {
+ return this._path ? !!this._path.removeSegment(this._index) : false;
+ },
+
+ clone: function() {
+ return new Segment(this._point, this._handleIn, this._handleOut);
+ },
+
+ equals: function(segment) {
+ return segment === this || segment && this._class === segment._class
+ && this._point.equals(segment._point)
+ && this._handleIn.equals(segment._handleIn)
+ && this._handleOut.equals(segment._handleOut)
+ || false;
+ },
+
+ toString: function() {
+ var parts = [ 'point: ' + this._point ];
+ if (!this._handleIn.isZero())
+ parts.push('handleIn: ' + this._handleIn);
+ if (!this._handleOut.isZero())
+ parts.push('handleOut: ' + this._handleOut);
+ return '{ ' + parts.join(', ') + ' }';
+ },
+
+ transform: function(matrix) {
+ this._transformCoordinates(matrix, new Array(6), true);
+ this._changed();
+ },
+
+ _transformCoordinates: function(matrix, coords, change) {
+ var point = this._point,
+ handleIn = !change || !this._handleIn.isZero()
+ ? this._handleIn : null,
+ handleOut = !change || !this._handleOut.isZero()
+ ? this._handleOut : null,
+ x = point._x,
+ y = point._y,
+ i = 2;
+ coords[0] = x;
+ coords[1] = y;
+ if (handleIn) {
+ coords[i++] = handleIn._x + x;
+ coords[i++] = handleIn._y + y;
+ }
+ if (handleOut) {
+ coords[i++] = handleOut._x + x;
+ coords[i++] = handleOut._y + y;
+ }
+ if (matrix) {
+ matrix._transformCoordinates(coords, coords, i / 2);
+ x = coords[0];
+ y = coords[1];
+ if (change) {
+ point._x = x;
+ point._y = y;
+ i = 2;
+ if (handleIn) {
+ handleIn._x = coords[i++] - x;
+ handleIn._y = coords[i++] - y;
+ }
+ if (handleOut) {
+ handleOut._x = coords[i++] - x;
+ handleOut._y = coords[i++] - y;
+ }
+ } else {
+ if (!handleIn) {
+ coords[i++] = x;
+ coords[i++] = y;
+ }
+ if (!handleOut) {
+ coords[i++] = x;
+ coords[i++] = y;
+ }
+ }
+ }
+ return coords;
+ }
+});
+
+var SegmentPoint = Point.extend({
+ initialize: function SegmentPoint(point, owner, key) {
+ var x, y, selected;
+ if (!point) {
+ x = y = 0;
+ } else if ((x = point[0]) !== undefined) {
+ y = point[1];
+ } else {
+ var pt = point;
+ if ((x = pt.x) === undefined) {
+ pt = Point.read(arguments);
+ x = pt.x;
+ }
+ y = pt.y;
+ selected = pt.selected;
+ }
+ this._x = x;
+ this._y = y;
+ this._owner = owner;
+ owner[key] = this;
+ if (selected)
+ this.setSelected(true);
+ },
+
+ set: function(x, y) {
+ this._x = x;
+ this._y = y;
+ this._owner._changed(this);
+ return this;
+ },
+
+ _serialize: function(options) {
+ var f = options.formatter,
+ x = f.number(this._x),
+ y = f.number(this._y);
+ return this.isSelected()
+ ? { x: x, y: y, selected: true }
+ : [x, y];
+ },
+
+ getX: function() {
+ return this._x;
+ },
+
+ setX: function(x) {
+ this._x = x;
+ this._owner._changed(this);
+ },
+
+ getY: function() {
+ return this._y;
+ },
+
+ setY: function(y) {
+ this._y = y;
+ this._owner._changed(this);
+ },
+
+ isZero: function() {
+ return Numerical.isZero(this._x) && Numerical.isZero(this._y);
+ },
+
+ setSelected: function(selected) {
+ this._owner.setSelected(selected, this);
+ },
+
+ isSelected: function() {
+ return this._owner.isSelected(this);
+ }
+});
+
+var Curve = Base.extend({
+ _class: 'Curve',
+ initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
+ var count = arguments.length;
+ if (count === 3) {
+ this._path = arg0;
+ this._segment1 = arg1;
+ this._segment2 = arg2;
+ } else if (count === 0) {
+ this._segment1 = new Segment();
+ this._segment2 = new Segment();
+ } else if (count === 1) {
+ this._segment1 = new Segment(arg0.segment1);
+ this._segment2 = new Segment(arg0.segment2);
+ } else if (count === 2) {
+ this._segment1 = new Segment(arg0);
+ this._segment2 = new Segment(arg1);
+ } else {
+ var point1, handle1, handle2, point2;
+ if (count === 4) {
+ point1 = arg0;
+ handle1 = arg1;
+ handle2 = arg2;
+ point2 = arg3;
+ } else if (count === 8) {
+ point1 = [arg0, arg1];
+ point2 = [arg6, arg7];
+ handle1 = [arg2 - arg0, arg3 - arg1];
+ handle2 = [arg4 - arg6, arg5 - arg7];
+ }
+ this._segment1 = new Segment(point1, null, handle1);
+ this._segment2 = new Segment(point2, handle2, null);
+ }
+ },
+
+ _changed: function() {
+ this._length = this._bounds = undefined;
+ },
+
+ getPoint1: function() {
+ return this._segment1._point;
+ },
+
+ setPoint1: function() {
+ var point = Point.read(arguments);
+ this._segment1._point.set(point.x, point.y);
+ },
+
+ getPoint2: function() {
+ return this._segment2._point;
+ },
+
+ setPoint2: function() {
+ var point = Point.read(arguments);
+ this._segment2._point.set(point.x, point.y);
+ },
+
+ getHandle1: function() {
+ return this._segment1._handleOut;
+ },
+
+ setHandle1: function() {
+ var point = Point.read(arguments);
+ this._segment1._handleOut.set(point.x, point.y);
+ },
+
+ getHandle2: function() {
+ return this._segment2._handleIn;
+ },
+
+ setHandle2: function() {
+ var point = Point.read(arguments);
+ this._segment2._handleIn.set(point.x, point.y);
+ },
+
+ getSegment1: function() {
+ return this._segment1;
+ },
+
+ getSegment2: function() {
+ return this._segment2;
+ },
+
+ getPath: function() {
+ return this._path;
+ },
+
+ getIndex: function() {
+ return this._segment1._index;
+ },
+
+ getNext: function() {
+ var curves = this._path && this._path._curves;
+ return curves && (curves[this._segment1._index + 1]
+ || this._path._closed && curves[0]) || null;
+ },
+
+ getPrevious: function() {
+ var curves = this._path && this._path._curves;
+ return curves && (curves[this._segment1._index - 1]
+ || this._path._closed && curves[curves.length - 1]) || null;
+ },
+
+ isSelected: function() {
+ return this.getPoint1().isSelected()
+ && this.getHandle2().isSelected()
+ && this.getHandle2().isSelected()
+ && this.getPoint2().isSelected();
+ },
+
+ setSelected: function(selected) {
+ this.getPoint1().setSelected(selected);
+ this.getHandle1().setSelected(selected);
+ this.getHandle2().setSelected(selected);
+ this.getPoint2().setSelected(selected);
+ },
+
+ getValues: function(matrix) {
+ return Curve.getValues(this._segment1, this._segment2, matrix);
+ },
+
+ getPoints: function() {
+ var coords = this.getValues(),
+ points = [];
+ for (var i = 0; i < 8; i += 2)
+ points.push(new Point(coords[i], coords[i + 1]));
+ return points;
+ },
+
+ getLength: function() {
+ if (this._length == null) {
+ this._length = this.isLinear()
+ ? this._segment2._point.getDistance(this._segment1._point)
+ : Curve.getLength(this.getValues(), 0, 1);
+ }
+ return this._length;
+ },
+
+ getArea: function() {
+ return Curve.getArea(this.getValues());
+ },
+
+ getPart: function(from, to) {
+ return new Curve(Curve.getPart(this.getValues(), from, to));
+ },
+
+ getPartLength: function(from, to) {
+ return Curve.getLength(this.getValues(), from, to);
+ },
+
+ isLinear: function() {
+ return this._segment1._handleOut.isZero()
+ && this._segment2._handleIn.isZero();
+ },
+
+ isHorizontal: function() {
+ return this.isLinear() && Numerical.isZero(
+ this._segment1._point._y - this._segment2._point._y);
+ },
+
+ getIntersections: function(curve) {
+ return Curve.getIntersections(this.getValues(), curve.getValues(),
+ this, curve, []);
+ },
+
+ _getParameter: function(offset, isParameter) {
+ return isParameter
+ ? offset
+ : offset && offset.curve === this
+ ? offset.parameter
+ : offset === undefined && isParameter === undefined
+ ? 0.5
+ : this.getParameterAt(offset, 0);
+ },
+
+ divide: function(offset, isParameter, ignoreLinear) {
+ var parameter = this._getParameter(offset, isParameter),
+ tolerance = 0.00001,
+ res = null;
+ if (parameter > tolerance && parameter < 1 - tolerance) {
+ var parts = Curve.subdivide(this.getValues(), parameter),
+ isLinear = ignoreLinear ? false : this.isLinear(),
+ left = parts[0],
+ right = parts[1];
+
+ if (!isLinear) {
+ this._segment1._handleOut.set(left[2] - left[0],
+ left[3] - left[1]);
+ this._segment2._handleIn.set(right[4] - right[6],
+ right[5] - right[7]);
+ }
+
+ var x = left[6], y = left[7],
+ segment = new Segment(new Point(x, y),
+ !isLinear && new Point(left[4] - x, left[5] - y),
+ !isLinear && new Point(right[2] - x, right[3] - y));
+
+ if (this._path) {
+ if (this._segment1._index > 0 && this._segment2._index === 0) {
+ this._path.add(segment);
+ } else {
+ this._path.insert(this._segment2._index, segment);
+ }
+ res = this;
+ } else {
+ var end = this._segment2;
+ this._segment2 = segment;
+ res = new Curve(segment, end);
+ }
+ }
+ return res;
+ },
+
+ split: function(offset, isParameter) {
+ return this._path
+ ? this._path.split(this._segment1._index,
+ this._getParameter(offset, isParameter))
+ : null;
+ },
+
+ reverse: function() {
+ return new Curve(this._segment2.reverse(), this._segment1.reverse());
+ },
+
+ remove: function() {
+ var removed = false;
+ if (this._path) {
+ var segment2 = this._segment2,
+ handleOut = segment2._handleOut;
+ removed = segment2.remove();
+ if (removed)
+ this._segment1._handleOut.set(handleOut.x, handleOut.y);
+ }
+ return removed;
+ },
+
+ clone: function() {
+ return new Curve(this._segment1, this._segment2);
+ },
+
+ toString: function() {
+ var parts = [ 'point1: ' + this._segment1._point ];
+ if (!this._segment1._handleOut.isZero())
+ parts.push('handle1: ' + this._segment1._handleOut);
+ if (!this._segment2._handleIn.isZero())
+ parts.push('handle2: ' + this._segment2._handleIn);
+ parts.push('point2: ' + this._segment2._point);
+ return '{ ' + parts.join(', ') + ' }';
+ },
+
+statics: {
+ getValues: function(segment1, segment2, matrix) {
+ var p1 = segment1._point,
+ h1 = segment1._handleOut,
+ h2 = segment2._handleIn,
+ p2 = segment2._point,
+ values = [
+ p1._x, p1._y,
+ p1._x + h1._x, p1._y + h1._y,
+ p2._x + h2._x, p2._y + h2._y,
+ p2._x, p2._y
+ ];
+ if (matrix)
+ matrix._transformCoordinates(values, values, 4);
+ return values;
+ },
+
+ evaluate: function(v, t, type) {
+ var p1x = v[0], p1y = v[1],
+ c1x = v[2], c1y = v[3],
+ c2x = v[4], c2y = v[5],
+ p2x = v[6], p2y = v[7],
+ tolerance = 0.00001,
+ x, y;
+
+ if (type === 0 && (t < tolerance || t > 1 - tolerance)) {
+ var isZero = t < tolerance;
+ x = isZero ? p1x : p2x;
+ y = isZero ? p1y : p2y;
+ } else {
+ var cx = 3 * (c1x - p1x),
+ bx = 3 * (c2x - c1x) - cx,
+ ax = p2x - p1x - cx - bx,
+
+ cy = 3 * (c1y - p1y),
+ by = 3 * (c2y - c1y) - cy,
+ ay = p2y - p1y - cy - by;
+ if (type === 0) {
+ x = ((ax * t + bx) * t + cx) * t + p1x;
+ y = ((ay * t + by) * t + cy) * t + p1y;
+ } else {
+ if (t < tolerance && c1x === p1x && c1y === p1y
+ || t > 1 - tolerance && c2x === p2x && c2y === p2y) {
+ x = c2x - c1x;
+ y = c2y - c1y;
+ } else if (t < tolerance) {
+ x = cx;
+ y = cy;
+ } else if (t > 1 - tolerance) {
+ x = 3 * (p2x - c2x);
+ y = 3 * (p2y - c2y);
+ } else {
+ x = (3 * ax * t + 2 * bx) * t + cx;
+ y = (3 * ay * t + 2 * by) * t + cy;
+ }
+ if (type === 3) {
+ var x2 = 6 * ax * t + 2 * bx,
+ y2 = 6 * ay * t + 2 * by;
+ return (x * y2 - y * x2) / Math.pow(x * x + y * y, 3 / 2);
+ }
+ }
+ }
+ return type === 2 ? new Point(y, -x) : new Point(x, y);
+ },
+
+ subdivide: function(v, t) {
+ var p1x = v[0], p1y = v[1],
+ c1x = v[2], c1y = v[3],
+ c2x = v[4], c2y = v[5],
+ p2x = v[6], p2y = v[7];
+ if (t === undefined)
+ t = 0.5;
+ var u = 1 - t,
+ p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y,
+ p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y,
+ p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y,
+ p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y,
+ p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y,
+ p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y;
+ return [
+ [p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y],
+ [p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y]
+ ];
+ },
+
+ solveCubic: function (v, coord, val, roots, min, max) {
+ var p1 = v[coord],
+ c1 = v[coord + 2],
+ c2 = v[coord + 4],
+ p2 = v[coord + 6],
+ c = 3 * (c1 - p1),
+ b = 3 * (c2 - c1) - c,
+ a = p2 - p1 - c - b;
+ return Numerical.solveCubic(a, b, c, p1 - val, roots, min, max);
+ },
+
+ getParameterOf: function(v, x, y) {
+ var tolerance = 0.00001;
+ if (Math.abs(v[0] - x) < tolerance && Math.abs(v[1] - y) < tolerance)
+ return 0;
+ if (Math.abs(v[6] - x) < tolerance && Math.abs(v[7] - y) < tolerance)
+ return 1;
+ var txs = [],
+ tys = [],
+ sx = Curve.solveCubic(v, 0, x, txs, 0, 1),
+ sy = Curve.solveCubic(v, 1, y, tys, 0, 1),
+ tx, ty;
+ for (var cx = 0; sx == -1 || cx < sx;) {
+ if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) {
+ for (var cy = 0; sy == -1 || cy < sy;) {
+ if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) {
+ if (sx == -1) tx = ty;
+ else if (sy == -1) ty = tx;
+ if (Math.abs(tx - ty) < tolerance)
+ return (tx + ty) * 0.5;
+ }
+ }
+ if (sx == -1)
+ break;
+ }
+ }
+ return null;
+ },
+
+ getPart: function(v, from, to) {
+ if (from > 0)
+ v = Curve.subdivide(v, from)[1];
+ if (to < 1)
+ v = Curve.subdivide(v, (to - from) / (1 - from))[0];
+ return v;
+ },
+
+ isLinear: function(v) {
+ var isZero = Numerical.isZero;
+ return isZero(v[0] - v[2]) && isZero(v[1] - v[3])
+ && isZero(v[4] - v[6]) && isZero(v[5] - v[7]);
+ },
+
+ isFlatEnough: function(v, tolerance) {
+ var p1x = v[0], p1y = v[1],
+ c1x = v[2], c1y = v[3],
+ c2x = v[4], c2y = v[5],
+ p2x = v[6], p2y = v[7],
+ ux = 3 * c1x - 2 * p1x - p2x,
+ uy = 3 * c1y - 2 * p1y - p2y,
+ vx = 3 * c2x - 2 * p2x - p1x,
+ vy = 3 * c2y - 2 * p2y - p1y;
+ return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
+ < 10 * tolerance * tolerance;
+ },
+
+ getArea: function(v) {
+ var p1x = v[0], p1y = v[1],
+ c1x = v[2], c1y = v[3],
+ c2x = v[4], c2y = v[5],
+ p2x = v[6], p2y = v[7];
+ return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x
+ - 1.5 * c1y * p2x - 3.0 * p1y * c1x
+ - 1.5 * p1y * c2x - 0.5 * p1y * p2x
+ + 1.5 * c2y * p1x + 1.5 * c2y * c1x
+ - 3.0 * c2y * p2x + 0.5 * p2y * p1x
+ + 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10;
+ },
+
+ getBounds: function(v) {
+ var min = v.slice(0, 2),
+ max = min.slice(),
+ roots = [0, 0];
+ for (var i = 0; i < 2; i++)
+ Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
+ i, 0, min, max, roots);
+ return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
+ },
+
+ _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
+ function add(value, padding) {
+ var left = value - padding,
+ right = value + padding;
+ if (left < min[coord])
+ min[coord] = left;
+ if (right > max[coord])
+ max[coord] = right;
+ }
+ var a = 3 * (v1 - v2) - v0 + v3,
+ b = 2 * (v0 + v2) - 4 * v1,
+ c = v1 - v0,
+ count = Numerical.solveQuadratic(a, b, c, roots),
+ tMin = 0.00001,
+ tMax = 1 - tMin;
+ add(v3, 0);
+ for (var i = 0; i < count; i++) {
+ var t = roots[i],
+ u = 1 - t;
+ if (tMin < t && t < tMax)
+ add(u * u * u * v0
+ + 3 * u * u * t * v1
+ + 3 * u * t * t * v2
+ + t * t * t * v3,
+ padding);
+ }
+ }
+}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
+ function(name) {
+ this[name] = function() {
+ if (!this._bounds)
+ this._bounds = {};
+ var bounds = this._bounds[name];
+ if (!bounds) {
+ bounds = this._bounds[name] = Path[name]([this._segment1,
+ this._segment2], false, this._path.getStyle());
+ }
+ return bounds.clone();
+ };
+ },
+{
+
+}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],
+ function(name, index) {
+ this[name + 'At'] = function(offset, isParameter) {
+ var values = this.getValues();
+ return Curve.evaluate(values, isParameter
+ ? offset : Curve.getParameterAt(values, offset, 0), index);
+ };
+ this[name] = function(parameter) {
+ return Curve.evaluate(this.getValues(), parameter, index);
+ };
+ },
+{
+ beans: false,
+
+ getParameterAt: function(offset, start) {
+ return Curve.getParameterAt(this.getValues(), offset, start);
+ },
+
+ getParameterOf: function() {
+ var point = Point.read(arguments);
+ return Curve.getParameterOf(this.getValues(), point.x, point.y);
+ },
+
+ getLocationAt: function(offset, isParameter) {
+ if (!isParameter)
+ offset = this.getParameterAt(offset);
+ return offset >= 0 && offset <= 1 && new CurveLocation(this, offset);
+ },
+
+ getLocationOf: function() {
+ return this.getLocationAt(this.getParameterOf(Point.read(arguments)),
+ true);
+ },
+
+ getOffsetOf: function() {
+ var loc = this.getLocationOf.apply(this, arguments);
+ return loc ? loc.getOffset() : null;
+ },
+
+ getNearestLocation: function() {
+ var point = Point.read(arguments),
+ values = this.getValues(),
+ count = 100,
+ minDist = Infinity,
+ minT = 0;
+
+ function refine(t) {
+ if (t >= 0 && t <= 1) {
+ var dist = point.getDistance(
+ Curve.evaluate(values, t, 0), true);
+ if (dist < minDist) {
+ minDist = dist;
+ minT = t;
+ return true;
+ }
+ }
+ }
+
+ for (var i = 0; i <= count; i++)
+ refine(i / count);
+
+ var step = 1 / (count * 2);
+ while (step > 0.00001) {
+ if (!refine(minT - step) && !refine(minT + step))
+ step /= 2;
+ }
+ var pt = Curve.evaluate(values, minT, 0);
+ return new CurveLocation(this, minT, pt, null, null, null,
+ point.getDistance(pt));
+ },
+
+ getNearestPoint: function() {
+ return this.getNearestLocation.apply(this, arguments).getPoint();
+ }
+
+}),
+new function() {
+
+ function getLengthIntegrand(v) {
+ var p1x = v[0], p1y = v[1],
+ c1x = v[2], c1y = v[3],
+ c2x = v[4], c2y = v[5],
+ p2x = v[6], p2y = v[7],
+
+ ax = 9 * (c1x - c2x) + 3 * (p2x - p1x),
+ bx = 6 * (p1x + c2x) - 12 * c1x,
+ cx = 3 * (c1x - p1x),
+
+ ay = 9 * (c1y - c2y) + 3 * (p2y - p1y),
+ by = 6 * (p1y + c2y) - 12 * c1y,
+ cy = 3 * (c1y - p1y);
+
+ return function(t) {
+ var dx = (ax * t + bx) * t + cx,
+ dy = (ay * t + by) * t + cy;
+ return Math.sqrt(dx * dx + dy * dy);
+ };
+ }
+
+ function getIterations(a, b) {
+ return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
+ }
+
+ return {
+ statics: true,
+
+ getLength: function(v, a, b) {
+ if (a === undefined)
+ a = 0;
+ if (b === undefined)
+ b = 1;
+ var isZero = Numerical.isZero;
+ if (a === 0 && b === 1
+ && isZero(v[0] - v[2]) && isZero(v[1] - v[3])
+ && isZero(v[6] - v[4]) && isZero(v[7] - v[5])) {
+ var dx = v[6] - v[0],
+ dy = v[7] - v[1];
+ return Math.sqrt(dx * dx + dy * dy);
+ }
+ var ds = getLengthIntegrand(v);
+ return Numerical.integrate(ds, a, b, getIterations(a, b));
+ },
+
+ getParameterAt: function(v, offset, start) {
+ if (start === undefined)
+ start = offset < 0 ? 1 : 0
+ if (offset === 0)
+ return start;
+ var forward = offset > 0,
+ a = forward ? start : 0,
+ b = forward ? 1 : start,
+ ds = getLengthIntegrand(v),
+ rangeLength = Numerical.integrate(ds, a, b,
+ getIterations(a, b));
+ if (Math.abs(offset) >= rangeLength)
+ return forward ? b : a;
+ var guess = offset / rangeLength,
+ length = 0;
+ function f(t) {
+ length += Numerical.integrate(ds, start, t,
+ getIterations(start, t));
+ start = t;
+ return length - offset;
+ }
+ return Numerical.findRoot(f, ds, start + guess, a, b, 16,
+ 0.00001);
+ }
+ };
+}, new function() {
+ function addLocation(locations, include, curve1, t1, point1, curve2, t2,
+ point2) {
+ var loc = new CurveLocation(curve1, t1, point1, curve2, t2, point2);
+ if (!include || include(loc))
+ locations.push(loc);
+ }
+
+ function addCurveIntersections(v1, v2, curve1, curve2, locations, include,
+ tMin, tMax, uMin, uMax, oldTDiff, reverse, recursion) {
+ if (recursion > 20)
+ return;
+ var q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7],
+ tolerance = 0.00001,
+ hullEpsilon = 1e-9,
+ getSignedDistance = Line.getSignedDistance,
+ d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]) || 0,
+ d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]) || 0,
+ factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
+ dMin = factor * Math.min(0, d1, d2),
+ dMax = factor * Math.max(0, d1, d2),
+ dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]),
+ dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]),
+ dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]),
+ dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]),
+ tMinNew, tMaxNew, tDiff;
+ if (q0x === q3x && uMax - uMin <= hullEpsilon && recursion > 3) {
+ tMinNew = (tMax + tMin) / 2;
+ tMaxNew = tMinNew;
+ tDiff = 0;
+ } else {
+ var hull = getConvexHull(dp0, dp1, dp2, dp3),
+ top = hull[0],
+ bottom = hull[1],
+ tMinClip, tMaxClip;
+ tMinClip = clipConvexHull(top, bottom, dMin, dMax);
+ top.reverse();
+ bottom.reverse();
+ tMaxClip = clipConvexHull(top, bottom, dMin, dMax);
+ if (tMinClip == null || tMaxClip == null)
+ return false;
+ v1 = Curve.getPart(v1, tMinClip, tMaxClip);
+ tDiff = tMaxClip - tMinClip;
+ tMinNew = tMax * tMinClip + tMin * (1 - tMinClip);
+ tMaxNew = tMax * tMaxClip + tMin * (1 - tMaxClip);
+ }
+ if (oldTDiff > 0.8 && tDiff > 0.8) {
+ if (tMaxNew - tMinNew > uMax - uMin) {
+ var parts = Curve.subdivide(v1, 0.5),
+ t = tMinNew + (tMaxNew - tMinNew) / 2;
+ addCurveIntersections(
+ v2, parts[0], curve2, curve1, locations, include,
+ uMin, uMax, tMinNew, t, tDiff, !reverse, ++recursion);
+ addCurveIntersections(
+ v2, parts[1], curve2, curve1, locations, include,
+ uMin, uMax, t, tMaxNew, tDiff, !reverse, recursion);
+ } else {
+ var parts = Curve.subdivide(v2, 0.5),
+ t = uMin + (uMax - uMin) / 2;
+ addCurveIntersections(
+ parts[0], v1, curve2, curve1, locations, include,
+ uMin, t, tMinNew, tMaxNew, tDiff, !reverse, ++recursion);
+ addCurveIntersections(
+ parts[1], v1, curve2, curve1, locations, include,
+ t, uMax, tMinNew, tMaxNew, tDiff, !reverse, recursion);
+ }
+ } else if (Math.max(uMax - uMin, tMaxNew - tMinNew) < tolerance) {
+ var t1 = tMinNew + (tMaxNew - tMinNew) / 2,
+ t2 = uMin + (uMax - uMin) / 2;
+ if (reverse) {
+ addLocation(locations, include,
+ curve2, t2, Curve.evaluate(v2, t2, 0),
+ curve1, t1, Curve.evaluate(v1, t1, 0));
+ } else {
+ addLocation(locations, include,
+ curve1, t1, Curve.evaluate(v1, t1, 0),
+ curve2, t2, Curve.evaluate(v2, t2, 0));
+ }
+ } else {
+ addCurveIntersections(v2, v1, curve2, curve1, locations, include,
+ uMin, uMax, tMinNew, tMaxNew, tDiff, !reverse, ++recursion);
+ }
+ }
+
+ function getConvexHull(dq0, dq1, dq2, dq3) {
+ var p0 = [ 0, dq0 ],
+ p1 = [ 1 / 3, dq1 ],
+ p2 = [ 2 / 3, dq2 ],
+ p3 = [ 1, dq3 ],
+ getSignedDistance = Line.getSignedDistance,
+ dist1 = getSignedDistance(0, dq0, 1, dq3, 1 / 3, dq1),
+ dist2 = getSignedDistance(0, dq0, 1, dq3, 2 / 3, dq2),
+ flip = false,
+ hull;
+ if (dist1 * dist2 < 0) {
+ hull = [[p0, p1, p3], [p0, p2, p3]];
+ flip = dist1 < 0;
+ } else {
+ var pmax, cross = 0,
+ distZero = dist1 === 0 || dist2 === 0;
+ if (Math.abs(dist1) > Math.abs(dist2)) {
+ pmax = p1;
+ cross = (dq3 - dq2 - (dq3 - dq0) / 3)
+ * (2 * (dq3 - dq2) - dq3 + dq1) / 3;
+ } else {
+ pmax = p2;
+ cross = (dq1 - dq0 + (dq0 - dq3) / 3)
+ * (-2 * (dq0 - dq1) + dq0 - dq2) / 3;
+ }
+ hull = cross < 0 || distZero
+ ? [[p0, pmax, p3], [p0, p3]]
+ : [[p0, p1, p2, p3], [p0, p3]];
+ flip = dist1 ? dist1 < 0 : dist2 < 0;
+ }
+ return flip ? hull.reverse() : hull;
+ }
+
+ function clipConvexHull(hullTop, hullBottom, dMin, dMax) {
+ var tProxy,
+ tVal = null,
+ px, py,
+ qx, qy;
+ for (var i = 0, l = hullBottom.length - 1; i < l; i++) {
+ py = hullBottom[i][1];
+ qy = hullBottom[i + 1][1];
+ if (py < qy) {
+ tProxy = null;
+ } else if (qy <= dMax) {
+ px = hullBottom[i][0];
+ qx = hullBottom[i + 1][0];
+ tProxy = px + (dMax - py) * (qx - px) / (qy - py);
+ } else {
+ continue;
+ }
+ break;
+ }
+ if (hullTop[0][1] <= dMax)
+ tProxy = hullTop[0][0];
+ for (var i = 0, l = hullTop.length - 1; i < l; i++) {
+ py = hullTop[i][1];
+ qy = hullTop[i + 1][1];
+ if (py >= dMin) {
+ tVal = tProxy;
+ } else if (py > qy) {
+ tVal = null;
+ } else if (qy >= dMin) {
+ px = hullTop[i][0];
+ qx = hullTop[i + 1][0];
+ tVal = px + (dMin - py) * (qx - px) / (qy - py);
+ } else {
+ continue;
+ }
+ break;
+ }
+ return tVal;
+ }
+
+ function addCurveLineIntersections(v1, v2, curve1, curve2, locations,
+ include) {
+ var flip = Curve.isLinear(v1),
+ vc = flip ? v2 : v1,
+ vl = flip ? v1 : v2,
+ lx1 = vl[0], ly1 = vl[1],
+ lx2 = vl[6], ly2 = vl[7],
+ ldx = lx2 - lx1,
+ ldy = ly2 - ly1,
+ angle = Math.atan2(-ldy, ldx),
+ sin = Math.sin(angle),
+ cos = Math.cos(angle),
+ rlx2 = ldx * cos - ldy * sin,
+ rvl = [0, 0, 0, 0, rlx2, 0, rlx2, 0],
+ rvc = [];
+ for(var i = 0; i < 8; i += 2) {
+ var x = vc[i] - lx1,
+ y = vc[i + 1] - ly1;
+ rvc.push(
+ x * cos - y * sin,
+ y * cos + x * sin);
+ }
+ var roots = [],
+ count = Curve.solveCubic(rvc, 1, 0, roots, 0, 1);
+ for (var i = 0; i < count; i++) {
+ var tc = roots[i],
+ x = Curve.evaluate(rvc, tc, 0).x;
+ if (x >= 0 && x <= rlx2) {
+ var tl = Curve.getParameterOf(rvl, x, 0),
+ t1 = flip ? tl : tc,
+ t2 = flip ? tc : tl;
+ addLocation(locations, include,
+ curve1, t1, Curve.evaluate(v1, t1, 0),
+ curve2, t2, Curve.evaluate(v2, t2, 0));
+ }
+ }
+ }
+
+ function addLineIntersection(v1, v2, curve1, curve2, locations, include) {
+ var point = Line.intersect(
+ v1[0], v1[1], v1[6], v1[7],
+ v2[0], v2[1], v2[6], v2[7]);
+ if (point) {
+ var x = point.x,
+ y = point.y;
+ addLocation(locations, include,
+ curve1, Curve.getParameterOf(v1, x, y), point,
+ curve2, Curve.getParameterOf(v2, x, y), point);
+ }
+ }
+
+ return { statics: {
+ getIntersections: function(v1, v2, curve1, curve2, locations, include) {
+ var linear1 = Curve.isLinear(v1),
+ linear2 = Curve.isLinear(v2);
+ (linear1 && linear2
+ ? addLineIntersection
+ : linear1 || linear2
+ ? addCurveLineIntersections
+ : addCurveIntersections)(
+ v1, v2, curve1, curve2, locations, include,
+ 0, 1, 0, 1, 0, false, 0);
+ return locations;
+ }
+ }};
+});
+
+var CurveLocation = Base.extend({
+ _class: 'CurveLocation',
+ beans: true,
+
+ initialize: function CurveLocation(curve, parameter, point, _curve2,
+ _parameter2, _point2, _distance) {
+ this._id = CurveLocation._id = (CurveLocation._id || 0) + 1;
+ this._curve = curve;
+ this._segment1 = curve._segment1;
+ this._segment2 = curve._segment2;
+ this._parameter = parameter;
+ this._point = point;
+ this._curve2 = _curve2;
+ this._parameter2 = _parameter2;
+ this._point2 = _point2;
+ this._distance = _distance;
+ },
+
+ getSegment: function(_preferFirst) {
+ if (!this._segment) {
+ var curve = this.getCurve(),
+ parameter = this.getParameter();
+ if (parameter === 1) {
+ this._segment = curve._segment2;
+ } else if (parameter === 0 || _preferFirst) {
+ this._segment = curve._segment1;
+ } else if (parameter == null) {
+ return null;
+ } else {
+ this._segment = curve.getPartLength(0, parameter)
+ < curve.getPartLength(parameter, 1)
+ ? curve._segment1
+ : curve._segment2;
+ }
+ }
+ return this._segment;
+ },
+
+ getCurve: function(_uncached) {
+ if (!this._curve || _uncached) {
+ this._curve = this._segment1.getCurve();
+ if (this._curve.getParameterOf(this._point) == null)
+ this._curve = this._segment2.getPrevious().getCurve();
+ }
+ return this._curve;
+ },
+
+ getIntersection: function() {
+ var intersection = this._intersection;
+ if (!intersection && this._curve2) {
+ var param = this._parameter2;
+ this._intersection = intersection = new CurveLocation(
+ this._curve2, param, this._point2 || this._point, this);
+ intersection._intersection = this;
+ }
+ return intersection;
+ },
+
+ getPath: function() {
+ var curve = this.getCurve();
+ return curve && curve._path;
+ },
+
+ getIndex: function() {
+ var curve = this.getCurve();
+ return curve && curve.getIndex();
+ },
+
+ getOffset: function() {
+ var path = this.getPath();
+ return path ? path._getOffset(this) : this.getCurveOffset();
+ },
+
+ getCurveOffset: function() {
+ var curve = this.getCurve(),
+ parameter = this.getParameter();
+ return parameter != null && curve && curve.getPartLength(0, parameter);
+ },
+
+ getParameter: function(_uncached) {
+ if ((this._parameter == null || _uncached) && this._point) {
+ var curve = this.getCurve(_uncached);
+ this._parameter = curve && curve.getParameterOf(this._point);
+ }
+ return this._parameter;
+ },
+
+ getPoint: function(_uncached) {
+ if ((!this._point || _uncached) && this._parameter != null) {
+ var curve = this.getCurve(_uncached);
+ this._point = curve && curve.getPointAt(this._parameter, true);
+ }
+ return this._point;
+ },
+
+ getDistance: function() {
+ return this._distance;
+ },
+
+ divide: function() {
+ var curve = this.getCurve(true);
+ return curve && curve.divide(this.getParameter(true), true);
+ },
+
+ split: function() {
+ var curve = this.getCurve(true);
+ return curve && curve.split(this.getParameter(true), true);
+ },
+
+ equals: function(loc) {
+ var isZero = Numerical.isZero;
+ return this === loc
+ || loc
+ && this._curve === loc._curve
+ && this._curve2 === loc._curve2
+ && isZero(this._parameter - loc._parameter)
+ && isZero(this._parameter2 - loc._parameter2)
+ || false;
+ },
+
+ toString: function() {
+ var parts = [],
+ point = this.getPoint(),
+ f = Formatter.instance;
+ if (point)
+ parts.push('point: ' + point);
+ var index = this.getIndex();
+ if (index != null)
+ parts.push('index: ' + index);
+ var parameter = this.getParameter();
+ if (parameter != null)
+ parts.push('parameter: ' + f.number(parameter));
+ if (this._distance != null)
+ parts.push('distance: ' + f.number(this._distance));
+ return '{ ' + parts.join(', ') + ' }';
+ }
+}, Base.each(['getTangent', 'getNormal', 'getCurvature'], function(name) {
+ var get = name + 'At';
+ this[name] = function() {
+ var parameter = this.getParameter(),
+ curve = this.getCurve();
+ return parameter != null && curve && curve[get](parameter, true);
+ };
+}, {}));
+
+var PathItem = Item.extend({
+ _class: 'PathItem',
+
+ initialize: function PathItem() {
+ },
+
+ getIntersections: function(path, _matrix, _expand) {
+ if (this === path)
+ path = null;
+ var locations = [],
+ curves1 = this.getCurves(),
+ curves2 = path ? path.getCurves() : curves1,
+ matrix1 = this._matrix.orNullIfIdentity(),
+ matrix2 = path ? (_matrix || path._matrix).orNullIfIdentity()
+ : matrix1,
+ length1 = curves1.length,
+ length2 = path ? curves2.length : length1,
+ values2 = [],
+ MIN = 1e-11,
+ MAX = 1 - 1e-11;
+ if (path && !this.getBounds(matrix1).touches(path.getBounds(matrix2)))
+ return [];
+ for (var i = 0; i < length2; i++)
+ values2[i] = curves2[i].getValues(matrix2);
+ for (var i = 0; i < length1; i++) {
+ var curve1 = curves1[i],
+ values1 = path ? curve1.getValues(matrix1) : values2[i];
+ if (!path) {
+ var seg1 = curve1.getSegment1(),
+ seg2 = curve1.getSegment2(),
+ h1 = seg1._handleOut,
+ h2 = seg2._handleIn;
+ if (new Line(seg1._point.subtract(h1), h1.multiply(2), true)
+ .intersect(new Line(seg2._point.subtract(h2),
+ h2.multiply(2), true), false)) {
+ var parts = Curve.subdivide(values1);
+ Curve.getIntersections(
+ parts[0], parts[1], curve1, curve1, locations,
+ function(loc) {
+ if (loc._parameter <= MAX) {
+ loc._parameter /= 2;
+ loc._parameter2 = 0.5 + loc._parameter2 / 2;
+ return true;
+ }
+ }
+ );
+ }
+ }
+ for (var j = path ? 0 : i + 1; j < length2; j++) {
+ Curve.getIntersections(
+ values1, values2[j], curve1, curves2[j], locations,
+ !path && (j === i + 1 || j === length2 - 1 && i === 0)
+ && function(loc) {
+ var t = loc._parameter;
+ return t >= MIN && t <= MAX;
+ }
+ );
+ }
+ }
+ var last = locations.length - 1;
+ for (var i = last; i >= 0; i--) {
+ var loc = locations[i],
+ next = loc._curve.getNext(),
+ next2 = loc._curve2.getNext();
+ if (next && loc._parameter >= MAX) {
+ loc._parameter = 0;
+ loc._curve = next;
+ }
+ if (next2 && loc._parameter2 >= MAX) {
+ loc._parameter2 = 0;
+ loc._curve2 = next2;
+ }
+ }
+
+ function compare(loc1, loc2) {
+ var path1 = loc1.getPath(),
+ path2 = loc2.getPath();
+ return path1 === path2
+ ? (loc1.getIndex() + loc1.getParameter())
+ - (loc2.getIndex() + loc2.getParameter())
+ : path1._id - path2._id;
+ }
+
+ if (last > 0) {
+ locations.sort(compare);
+ for (var i = last; i >= 1; i--) {
+ if (locations[i].equals(locations[i === 0 ? last : i - 1])) {
+ locations.splice(i, 1);
+ last--;
+ }
+ }
+ }
+ if (_expand) {
+ for (var i = last; i >= 0; i--)
+ locations.push(locations[i].getIntersection());
+ locations.sort(compare);
+ }
+ return locations;
+ },
+
+ _asPathItem: function() {
+ return this;
+ },
+
+ setPathData: function(data) {
+
+ var parts = data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
+ coords,
+ relative = false,
+ previous,
+ control,
+ current = new Point(),
+ start = new Point();
+
+ function getCoord(index, coord) {
+ var val = +coords[index];
+ if (relative)
+ val += current[coord];
+ return val;
+ }
+
+ function getPoint(index) {
+ return new Point(
+ getCoord(index, 'x'),
+ getCoord(index + 1, 'y')
+ );
+ }
+
+ this.clear();
+
+ for (var i = 0, l = parts.length; i < l; i++) {
+ var part = parts[i],
+ command = part[0],
+ lower = command.toLowerCase();
+ coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
+ var length = coords && coords.length;
+ relative = command === lower;
+ if (previous === 'z' && !/[mz]/.test(lower))
+ this.moveTo(current = start);
+ switch (lower) {
+ case 'm':
+ case 'l':
+ var move = lower === 'm';
+ if (move && previous && previous !== 'z')
+ this.closePath(true);
+ for (var j = 0; j < length; j += 2)
+ this[j === 0 && move ? 'moveTo' : 'lineTo'](
+ current = getPoint(j));
+ control = current;
+ if (move)
+ start = current;
+ break;
+ case 'h':
+ case 'v':
+ var coord = lower === 'h' ? 'x' : 'y';
+ for (var j = 0; j < length; j++) {
+ current[coord] = getCoord(j, coord);
+ this.lineTo(current);
+ }
+ control = current;
+ break;
+ case 'c':
+ for (var j = 0; j < length; j += 6) {
+ this.cubicCurveTo(
+ getPoint(j),
+ control = getPoint(j + 2),
+ current = getPoint(j + 4));
+ }
+ break;
+ case 's':
+ for (var j = 0; j < length; j += 4) {
+ this.cubicCurveTo(
+ /[cs]/.test(previous)
+ ? current.multiply(2).subtract(control)
+ : current,
+ control = getPoint(j),
+ current = getPoint(j + 2));
+ previous = lower;
+ }
+ break;
+ case 'q':
+ for (var j = 0; j < length; j += 4) {
+ this.quadraticCurveTo(
+ control = getPoint(j),
+ current = getPoint(j + 2));
+ }
+ break;
+ case 't':
+ for (var j = 0; j < length; j += 2) {
+ this.quadraticCurveTo(
+ control = (/[qt]/.test(previous)
+ ? current.multiply(2).subtract(control)
+ : current),
+ current = getPoint(j));
+ previous = lower;
+ }
+ break;
+ case 'a':
+ for (var j = 0; j < length; j += 7) {
+ this.arcTo(current = getPoint(j + 5),
+ new Size(+coords[0], +coords[1]),
+ +coords[2], +coords[4], +coords[3]);
+ }
+ break;
+ case 'z':
+ this.closePath(true);
+ break;
+ }
+ previous = lower;
+ }
+ },
+
+ _canComposite: function() {
+ return !(this.hasFill() && this.hasStroke());
+ },
+
+ _contains: function(point) {
+ var winding = this._getWinding(point, false, true);
+ return !!(this.getWindingRule() === 'evenodd' ? winding & 1 : winding);
+ }
+
+});
+
+var Path = PathItem.extend({
+ _class: 'Path',
+ _serializeFields: {
+ segments: [],
+ closed: false
+ },
+
+ initialize: function Path(arg) {
+ this._closed = false;
+ this._segments = [];
+ var segments = Array.isArray(arg)
+ ? typeof arg[0] === 'object'
+ ? arg
+ : arguments
+ : arg && (arg.size === undefined && (arg.x !== undefined
+ || arg.point !== undefined))
+ ? arguments
+ : null;
+ if (segments && segments.length > 0) {
+ this.setSegments(segments);
+ } else {
+ this._curves = undefined;
+ this._selectedSegmentState = 0;
+ if (!segments && typeof arg === 'string') {
+ this.setPathData(arg);
+ arg = null;
+ }
+ }
+ this._initialize(!segments && arg);
+ },
+
+ _equals: function(item) {
+ return Base.equals(this._segments, item._segments);
+ },
+
+ clone: function(insert) {
+ var copy = new Path(Item.NO_INSERT);
+ copy.setSegments(this._segments);
+ copy._closed = this._closed;
+ if (this._clockwise !== undefined)
+ copy._clockwise = this._clockwise;
+ return this._clone(copy, insert);
+ },
+
+ _changed: function _changed(flags) {
+ _changed.base.call(this, flags);
+ if (flags & 8) {
+ var parent = this._parent;
+ if (parent)
+ parent._currentPath = undefined;
+ this._length = this._clockwise = undefined;
+ if (this._curves && !(flags & 16)) {
+ for (var i = 0, l = this._curves.length; i < l; i++)
+ this._curves[i]._changed();
+ }
+ this._monoCurves = undefined;
+ } else if (flags & 32) {
+ this._bounds = undefined;
+ }
+ },
+
+ getStyle: function() {
+ var parent = this._parent;
+ return (parent instanceof CompoundPath ? parent : this)._style;
+ },
+
+ getSegments: function() {
+ return this._segments;
+ },
+
+ setSegments: function(segments) {
+ var fullySelected = this.isFullySelected();
+ this._segments.length = 0;
+ this._selectedSegmentState = 0;
+ this._curves = undefined;
+ if (segments && segments.length > 0)
+ this._add(Segment.readAll(segments));
+ if (fullySelected)
+ this.setFullySelected(true);
+ },
+
+ getFirstSegment: function() {
+ return this._segments[0];
+ },
+
+ getLastSegment: function() {
+ return this._segments[this._segments.length - 1];
+ },
+
+ getCurves: function() {
+ var curves = this._curves,
+ segments = this._segments;
+ if (!curves) {
+ var length = this._countCurves();
+ curves = this._curves = new Array(length);
+ for (var i = 0; i < length; i++)
+ curves[i] = new Curve(this, segments[i],
+ segments[i + 1] || segments[0]);
+ }
+ return curves;
+ },
+
+ getFirstCurve: function() {
+ return this.getCurves()[0];
+ },
+
+ getLastCurve: function() {
+ var curves = this.getCurves();
+ return curves[curves.length - 1];
+ },
+
+ isClosed: function() {
+ return this._closed;
+ },
+
+ setClosed: function(closed) {
+ if (this._closed != (closed = !!closed)) {
+ this._closed = closed;
+ if (this._curves) {
+ var length = this._curves.length = this._countCurves();
+ if (closed)
+ this._curves[length - 1] = new Curve(this,
+ this._segments[length - 1], this._segments[0]);
+ }
+ this._changed(25);
+ }
+ }
+}, {
+ beans: true,
+
+ getPathData: function(_matrix, _precision) {
+ var segments = this._segments,
+ length = segments.length,
+ f = new Formatter(_precision),
+ coords = new Array(6),
+ first = true,
+ curX, curY,
+ prevX, prevY,
+ inX, inY,
+ outX, outY,
+ parts = [];
+
+ function addSegment(segment, skipLine) {
+ segment._transformCoordinates(_matrix, coords, false);
+ curX = coords[0];
+ curY = coords[1];
+ if (first) {
+ parts.push('M' + f.pair(curX, curY));
+ first = false;
+ } else {
+ inX = coords[2];
+ inY = coords[3];
+ if (inX === curX && inY === curY
+ && outX === prevX && outY === prevY) {
+ if (!skipLine)
+ parts.push('l' + f.pair(curX - prevX, curY - prevY));
+ } else {
+ parts.push('c' + f.pair(outX - prevX, outY - prevY)
+ + ' ' + f.pair(inX - prevX, inY - prevY)
+ + ' ' + f.pair(curX - prevX, curY - prevY));
+ }
+ }
+ prevX = curX;
+ prevY = curY;
+ outX = coords[4];
+ outY = coords[5];
+ }
+
+ if (length === 0)
+ return '';
+
+ for (var i = 0; i < length; i++)
+ addSegment(segments[i]);
+ if (this._closed && length > 0) {
+ addSegment(segments[0], true);
+ parts.push('z');
+ }
+ return parts.join('');
+ }
+}, {
+
+ isEmpty: function() {
+ return this._segments.length === 0;
+ },
+
+ isPolygon: function() {
+ for (var i = 0, l = this._segments.length; i < l; i++) {
+ if (!this._segments[i].isLinear())
+ return false;
+ }
+ return true;
+ },
+
+ _transformContent: function(matrix) {
+ var coords = new Array(6);
+ for (var i = 0, l = this._segments.length; i < l; i++)
+ this._segments[i]._transformCoordinates(matrix, coords, true);
+ return true;
+ },
+
+ _add: function(segs, index) {
+ var segments = this._segments,
+ curves = this._curves,
+ amount = segs.length,
+ append = index == null,
+ index = append ? segments.length : index;
+ for (var i = 0; i < amount; i++) {
+ var segment = segs[i];
+ if (segment._path)
+ segment = segs[i] = segment.clone();
+ segment._path = this;
+ segment._index = index + i;
+ if (segment._selectionState)
+ this._updateSelection(segment, 0, segment._selectionState);
+ }
+ if (append) {
+ segments.push.apply(segments, segs);
+ } else {
+ segments.splice.apply(segments, [index, 0].concat(segs));
+ for (var i = index + amount, l = segments.length; i < l; i++)
+ segments[i]._index = i;
+ }
+ if (curves || segs._curves) {
+ if (!curves)
+ curves = this._curves = [];
+ var from = index > 0 ? index - 1 : index,
+ start = from,
+ to = Math.min(from + amount, this._countCurves());
+ if (segs._curves) {
+ curves.splice.apply(curves, [from, 0].concat(segs._curves));
+ start += segs._curves.length;
+ }
+ for (var i = start; i < to; i++)
+ curves.splice(i, 0, new Curve(this, null, null));
+ this._adjustCurves(from, to);
+ }
+ this._changed(25);
+ return segs;
+ },
+
+ _adjustCurves: function(from, to) {
+ var segments = this._segments,
+ curves = this._curves,
+ curve;
+ for (var i = from; i < to; i++) {
+ curve = curves[i];
+ curve._path = this;
+ curve._segment1 = segments[i];
+ curve._segment2 = segments[i + 1] || segments[0];
+ curve._changed();
+ }
+ if (curve = curves[this._closed && from === 0 ? segments.length - 1
+ : from - 1]) {
+ curve._segment2 = segments[from] || segments[0];
+ curve._changed();
+ }
+ if (curve = curves[to]) {
+ curve._segment1 = segments[to];
+ curve._changed();
+ }
+ },
+
+ _countCurves: function() {
+ var length = this._segments.length;
+ return !this._closed && length > 0 ? length - 1 : length;
+ },
+
+ add: function(segment1 ) {
+ return arguments.length > 1 && typeof segment1 !== 'number'
+ ? this._add(Segment.readAll(arguments))
+ : this._add([ Segment.read(arguments) ])[0];
+ },
+
+ insert: function(index, segment1 ) {
+ return arguments.length > 2 && typeof segment1 !== 'number'
+ ? this._add(Segment.readAll(arguments, 1), index)
+ : this._add([ Segment.read(arguments, 1) ], index)[0];
+ },
+
+ addSegment: function() {
+ return this._add([ Segment.read(arguments) ])[0];
+ },
+
+ insertSegment: function(index ) {
+ return this._add([ Segment.read(arguments, 1) ], index)[0];
+ },
+
+ addSegments: function(segments) {
+ return this._add(Segment.readAll(segments));
+ },
+
+ insertSegments: function(index, segments) {
+ return this._add(Segment.readAll(segments), index);
+ },
+
+ removeSegment: function(index) {
+ return this.removeSegments(index, index + 1)[0] || null;
+ },
+
+ removeSegments: function(from, to, _includeCurves) {
+ from = from || 0;
+ to = Base.pick(to, this._segments.length);
+ var segments = this._segments,
+ curves = this._curves,
+ count = segments.length,
+ removed = segments.splice(from, to - from),
+ amount = removed.length;
+ if (!amount)
+ return removed;
+ for (var i = 0; i < amount; i++) {
+ var segment = removed[i];
+ if (segment._selectionState)
+ this._updateSelection(segment, segment._selectionState, 0);
+ segment._index = segment._path = null;
+ }
+ for (var i = from, l = segments.length; i < l; i++)
+ segments[i]._index = i;
+ if (curves) {
+ var index = from > 0 && to === count + (this._closed ? 1 : 0)
+ ? from - 1
+ : from,
+ curves = curves.splice(index, amount);
+ if (_includeCurves)
+ removed._curves = curves.slice(1);
+ this._adjustCurves(index, index);
+ }
+ this._changed(25);
+ return removed;
+ },
+
+ clear: '#removeSegments',
+
+ getLength: function() {
+ if (this._length == null) {
+ var curves = this.getCurves();
+ this._length = 0;
+ for (var i = 0, l = curves.length; i < l; i++)
+ this._length += curves[i].getLength();
+ }
+ return this._length;
+ },
+
+ getArea: function() {
+ var curves = this.getCurves();
+ var area = 0;
+ for (var i = 0, l = curves.length; i < l; i++)
+ area += curves[i].getArea();
+ return area;
+ },
+
+ isFullySelected: function() {
+ var length = this._segments.length;
+ return this._selected && length > 0 && this._selectedSegmentState
+ === length * 7;
+ },
+
+ setFullySelected: function(selected) {
+ if (selected)
+ this._selectSegments(true);
+ this.setSelected(selected);
+ },
+
+ setSelected: function setSelected(selected) {
+ if (!selected)
+ this._selectSegments(false);
+ setSelected.base.call(this, selected);
+ },
+
+ _selectSegments: function(selected) {
+ var length = this._segments.length;
+ this._selectedSegmentState = selected
+ ? length * 7 : 0;
+ for (var i = 0; i < length; i++)
+ this._segments[i]._selectionState = selected
+ ? 7 : 0;
+ },
+
+ _updateSelection: function(segment, oldState, newState) {
+ segment._selectionState = newState;
+ var total = this._selectedSegmentState += newState - oldState;
+ if (total > 0)
+ this.setSelected(true);
+ },
+
+ flatten: function(maxDistance) {
+ var iterator = new PathIterator(this, 64, 0.1),
+ pos = 0,
+ step = iterator.length / Math.ceil(iterator.length / maxDistance),
+ end = iterator.length + (this._closed ? -step : step) / 2;
+ var segments = [];
+ while (pos <= end) {
+ segments.push(new Segment(iterator.evaluate(pos, 0)));
+ pos += step;
+ }
+ this.setSegments(segments);
+ },
+
+ reduce: function() {
+ var curves = this.getCurves();
+ for (var i = curves.length - 1; i >= 0; i--) {
+ var curve = curves[i];
+ if (curve.isLinear() && curve.getLength() === 0)
+ curve.remove();
+ }
+ return this;
+ },
+
+ simplify: function(tolerance) {
+ if (this._segments.length > 2) {
+ var fitter = new PathFitter(this, tolerance || 2.5);
+ this.setSegments(fitter.fit());
+ }
+ },
+
+ split: function(index, parameter) {
+ if (parameter === null)
+ return;
+ if (arguments.length === 1) {
+ var arg = index;
+ if (typeof arg === 'number')
+ arg = this.getLocationAt(arg);
+ index = arg.index;
+ parameter = arg.parameter;
+ }
+ var tolerance = 0.00001;
+ if (parameter >= 1 - tolerance) {
+ index++;
+ parameter--;
+ }
+ var curves = this.getCurves();
+ if (index >= 0 && index < curves.length) {
+ if (parameter > tolerance) {
+ curves[index++].divide(parameter, true);
+ }
+ var segs = this.removeSegments(index, this._segments.length, true),
+ path;
+ if (this._closed) {
+ this.setClosed(false);
+ path = this;
+ } else if (index > 0) {
+ path = this._clone(new Path().insertAbove(this, true));
+ }
+ path._add(segs, 0);
+ this.addSegment(segs[0]);
+ return path;
+ }
+ return null;
+ },
+
+ isClockwise: function() {
+ if (this._clockwise !== undefined)
+ return this._clockwise;
+ return Path.isClockwise(this._segments);
+ },
+
+ setClockwise: function(clockwise) {
+ if (this.isClockwise() != (clockwise = !!clockwise))
+ this.reverse();
+ this._clockwise = clockwise;
+ },
+
+ reverse: function() {
+ this._segments.reverse();
+ for (var i = 0, l = this._segments.length; i < l; i++) {
+ var segment = this._segments[i];
+ var handleIn = segment._handleIn;
+ segment._handleIn = segment._handleOut;
+ segment._handleOut = handleIn;
+ segment._index = i;
+ }
+ this._curves = null;
+ if (this._clockwise !== undefined)
+ this._clockwise = !this._clockwise;
+ this._changed(9);
+ },
+
+ join: function(path) {
+ if (path) {
+ var segments = path._segments,
+ last1 = this.getLastSegment(),
+ last2 = path.getLastSegment();
+ if (last1._point.equals(last2._point))
+ path.reverse();
+ var first1,
+ first2 = path.getFirstSegment();
+ if (last1._point.equals(first2._point)) {
+ last1.setHandleOut(first2._handleOut);
+ this._add(segments.slice(1));
+ } else {
+ first1 = this.getFirstSegment();
+ if (first1._point.equals(first2._point))
+ path.reverse();
+ last2 = path.getLastSegment();
+ if (first1._point.equals(last2._point)) {
+ first1.setHandleIn(last2._handleIn);
+ this._add(segments.slice(0, segments.length - 1), 0);
+ } else {
+ this._add(segments.slice());
+ }
+ }
+ if (path.closed)
+ this._add([segments[0]]);
+ path.remove();
+ }
+ var first = this.getFirstSegment(),
+ last = this.getLastSegment();
+ if (first !== last && first._point.equals(last._point)) {
+ first.setHandleIn(last._handleIn);
+ last.remove();
+ this.setClosed(true);
+ }
+ },
+
+ toShape: function(insert) {
+ if (!this._closed)
+ return null;
+
+ var segments = this._segments,
+ type,
+ size,
+ radius,
+ topCenter;
+
+ function isColinear(i, j) {
+ return segments[i].isColinear(segments[j]);
+ }
+
+ function isOrthogonal(i) {
+ return segments[i].isOrthogonal();
+ }
+
+ function isArc(i) {
+ return segments[i].isArc();
+ }
+
+ function getDistance(i, j) {
+ return segments[i]._point.getDistance(segments[j]._point);
+ }
+
+ if (this.isPolygon() && segments.length === 4
+ && isColinear(0, 2) && isColinear(1, 3) && isOrthogonal(1)) {
+ type = Shape.Rectangle;
+ size = new Size(getDistance(0, 3), getDistance(0, 1));
+ topCenter = segments[1]._point.add(segments[2]._point).divide(2);
+ } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
+ && isArc(6) && isColinear(1, 5) && isColinear(3, 7)) {
+ type = Shape.Rectangle;
+ size = new Size(getDistance(1, 6), getDistance(0, 3));
+ radius = size.subtract(new Size(getDistance(0, 7),
+ getDistance(1, 2))).divide(2);
+ topCenter = segments[3]._point.add(segments[4]._point).divide(2);
+ } else if (segments.length === 4
+ && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
+ if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
+ type = Shape.Circle;
+ radius = getDistance(0, 2) / 2;
+ } else {
+ type = Shape.Ellipse;
+ radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
+ }
+ topCenter = segments[1]._point;
+ }
+
+ if (type) {
+ var center = this.getPosition(true),
+ shape = new type({
+ center: center,
+ size: size,
+ radius: radius,
+ insert: false
+ });
+ shape.rotate(topCenter.subtract(center).getAngle() + 90);
+ shape.setStyle(this._style);
+ if (insert || insert === undefined)
+ shape.insertAbove(this);
+ return shape;
+ }
+ return null;
+ },
+
+ _hitTestSelf: function(point, options) {
+ var that = this,
+ style = this.getStyle(),
+ segments = this._segments,
+ numSegments = segments.length,
+ closed = this._closed,
+ tolerancePadding = options._tolerancePadding,
+ strokePadding = tolerancePadding,
+ join, cap, miterLimit,
+ area, loc, res,
+ hitStroke = options.stroke && style.hasStroke(),
+ hitFill = options.fill && style.hasFill(),
+ hitCurves = options.curves,
+ radius = hitStroke
+ ? style.getStrokeWidth() / 2
+ : hitFill && options.tolerance > 0 || hitCurves
+ ? 0 : null;
+ if (radius !== null) {
+ if (radius > 0) {
+ join = style.getStrokeJoin();
+ cap = style.getStrokeCap();
+ miterLimit = radius * style.getMiterLimit();
+ strokePadding = tolerancePadding.add(new Point(radius, radius));
+ } else {
+ join = cap = 'round';
+ }
+ }
+
+ function isCloseEnough(pt, padding) {
+ return point.subtract(pt).divide(padding).length <= 1;
+ }
+
+ function checkSegmentPoint(seg, pt, name) {
+ if (!options.selected || pt.isSelected()) {
+ var anchor = seg._point;
+ if (pt !== anchor)
+ pt = pt.add(anchor);
+ if (isCloseEnough(pt, strokePadding)) {
+ return new HitResult(name, that, {
+ segment: seg,
+ point: pt
+ });
+ }
+ }
+ }
+
+ function checkSegmentPoints(seg, ends) {
+ return (ends || options.segments)
+ && checkSegmentPoint(seg, seg._point, 'segment')
+ || (!ends && options.handles) && (
+ checkSegmentPoint(seg, seg._handleIn, 'handle-in') ||
+ checkSegmentPoint(seg, seg._handleOut, 'handle-out'));
+ }
+
+ function addToArea(point) {
+ area.add(point);
+ }
+
+ function checkSegmentStroke(segment) {
+ if (join !== 'round' || cap !== 'round') {
+ area = new Path({ internal: true, closed: true });
+ if (closed || segment._index > 0
+ && segment._index < numSegments - 1) {
+ if (join !== 'round' && (segment._handleIn.isZero()
+ || segment._handleOut.isZero()))
+ Path._addBevelJoin(segment, join, radius, miterLimit,
+ addToArea, true);
+ } else if (cap !== 'round') {
+ Path._addSquareCap(segment, cap, radius, addToArea, true);
+ }
+ if (!area.isEmpty()) {
+ var loc;
+ return area.contains(point)
+ || (loc = area.getNearestLocation(point))
+ && isCloseEnough(loc.getPoint(), tolerancePadding);
+ }
+ }
+ return isCloseEnough(segment._point, strokePadding);
+ }
+
+ if (options.ends && !options.segments && !closed) {
+ if (res = checkSegmentPoints(segments[0], true)
+ || checkSegmentPoints(segments[numSegments - 1], true))
+ return res;
+ } else if (options.segments || options.handles) {
+ for (var i = 0; i < numSegments; i++)
+ if (res = checkSegmentPoints(segments[i]))
+ return res;
+ }
+ if (radius !== null) {
+ loc = this.getNearestLocation(point);
+ if (loc) {
+ var parameter = loc.getParameter();
+ if (parameter === 0 || parameter === 1 && numSegments > 1) {
+ if (!checkSegmentStroke(loc.getSegment()))
+ loc = null;
+ } else if (!isCloseEnough(loc.getPoint(), strokePadding)) {
+ loc = null;
+ }
+ }
+ if (!loc && join === 'miter' && numSegments > 1) {
+ for (var i = 0; i < numSegments; i++) {
+ var segment = segments[i];
+ if (point.getDistance(segment._point) <= miterLimit
+ && checkSegmentStroke(segment)) {
+ loc = segment.getLocation();
+ break;
+ }
+ }
+ }
+ }
+ return !loc && hitFill && this._contains(point)
+ || loc && !hitStroke && !hitCurves
+ ? new HitResult('fill', this)
+ : loc
+ ? new HitResult(hitStroke ? 'stroke' : 'curve', this, {
+ location: loc,
+ point: loc.getPoint()
+ })
+ : null;
+ }
+
+}, Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],
+ function(name) {
+ this[name + 'At'] = function(offset, isParameter) {
+ var loc = this.getLocationAt(offset, isParameter);
+ return loc && loc[name]();
+ };
+ },
+{
+ beans: false,
+
+ _getOffset: function(location) {
+ var index = location && location.getIndex();
+ if (index != null) {
+ var curves = this.getCurves(),
+ offset = 0;
+ for (var i = 0; i < index; i++)
+ offset += curves[i].getLength();
+ var curve = curves[index],
+ parameter = location.getParameter();
+ if (parameter > 0)
+ offset += curve.getPartLength(0, parameter);
+ return offset;
+ }
+ return null;
+ },
+
+ getLocationOf: function() {
+ var point = Point.read(arguments),
+ curves = this.getCurves();
+ for (var i = 0, l = curves.length; i < l; i++) {
+ var loc = curves[i].getLocationOf(point);
+ if (loc)
+ return loc;
+ }
+ return null;
+ },
+
+ getOffsetOf: function() {
+ var loc = this.getLocationOf.apply(this, arguments);
+ return loc ? loc.getOffset() : null;
+ },
+
+ getLocationAt: function(offset, isParameter) {
+ var curves = this.getCurves(),
+ length = 0;
+ if (isParameter) {
+ var index = ~~offset;
+ return curves[index].getLocationAt(offset - index, true);
+ }
+ for (var i = 0, l = curves.length; i < l; i++) {
+ var start = length,
+ curve = curves[i];
+ length += curve.getLength();
+ if (length > offset) {
+ return curve.getLocationAt(offset - start);
+ }
+ }
+ if (offset <= this.getLength())
+ return new CurveLocation(curves[curves.length - 1], 1);
+ return null;
+ },
+
+ getNearestLocation: function() {
+ var point = Point.read(arguments),
+ curves = this.getCurves(),
+ minDist = Infinity,
+ minLoc = null;
+ for (var i = 0, l = curves.length; i < l; i++) {
+ var loc = curves[i].getNearestLocation(point);
+ if (loc._distance < minDist) {
+ minDist = loc._distance;
+ minLoc = loc;
+ }
+ }
+ return minLoc;
+ },
+
+ getNearestPoint: function() {
+ return this.getNearestLocation.apply(this, arguments).getPoint();
+ }
+}), new function() {
+
+ function drawHandles(ctx, segments, matrix, size) {
+ var half = size / 2;
+
+ function drawHandle(index) {
+ var hX = coords[index],
+ hY = coords[index + 1];
+ if (pX != hX || pY != hY) {
+ ctx.beginPath();
+ ctx.moveTo(pX, pY);
+ ctx.lineTo(hX, hY);
+ ctx.stroke();
+ ctx.beginPath();
+ ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
+ ctx.fill();
+ }
+ }
+
+ var coords = new Array(6);
+ for (var i = 0, l = segments.length; i < l; i++) {
+ var segment = segments[i];
+ segment._transformCoordinates(matrix, coords, false);
+ var state = segment._selectionState,
+ pX = coords[0],
+ pY = coords[1];
+ if (state & 1)
+ drawHandle(2);
+ if (state & 2)
+ drawHandle(4);
+ ctx.fillRect(pX - half, pY - half, size, size);
+ if (!(state & 4)) {
+ var fillStyle = ctx.fillStyle;
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(pX - half + 1, pY - half + 1, size - 2, size - 2);
+ ctx.fillStyle = fillStyle;
+ }
+ }
+ }
+
+ function drawSegments(ctx, path, matrix) {
+ var segments = path._segments,
+ length = segments.length,
+ coords = new Array(6),
+ first = true,
+ curX, curY,
+ prevX, prevY,
+ inX, inY,
+ outX, outY;
+
+ function drawSegment(segment) {
+ if (matrix) {
+ segment._transformCoordinates(matrix, coords, false);
+ curX = coords[0];
+ curY = coords[1];
+ } else {
+ var point = segment._point;
+ curX = point._x;
+ curY = point._y;
+ }
+ if (first) {
+ ctx.moveTo(curX, curY);
+ first = false;
+ } else {
+ if (matrix) {
+ inX = coords[2];
+ inY = coords[3];
+ } else {
+ var handle = segment._handleIn;
+ inX = curX + handle._x;
+ inY = curY + handle._y;
+ }
+ if (inX === curX && inY === curY
+ && outX === prevX && outY === prevY) {
+ ctx.lineTo(curX, curY);
+ } else {
+ ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
+ }
+ }
+ prevX = curX;
+ prevY = curY;
+ if (matrix) {
+ outX = coords[4];
+ outY = coords[5];
+ } else {
+ var handle = segment._handleOut;
+ outX = prevX + handle._x;
+ outY = prevY + handle._y;
+ }
+ }
+
+ for (var i = 0; i < length; i++)
+ drawSegment(segments[i]);
+ if (path._closed && length > 0)
+ drawSegment(segments[0]);
+ }
+
+ return {
+ _draw: function(ctx, param, strokeMatrix) {
+ var dontStart = param.dontStart,
+ dontPaint = param.dontFinish || param.clip,
+ style = this.getStyle(),
+ hasFill = style.hasFill(),
+ hasStroke = style.hasStroke(),
+ dashArray = style.getDashArray(),
+ dashLength = !paper.support.nativeDash && hasStroke
+ && dashArray && dashArray.length;
+
+ if (!dontStart)
+ ctx.beginPath();
+
+ if (!dontStart && this._currentPath) {
+ ctx.currentPath = this._currentPath;
+ } else if (hasFill || hasStroke && !dashLength || dontPaint) {
+ drawSegments(ctx, this, strokeMatrix);
+ if (this._closed)
+ ctx.closePath();
+ if (!dontStart)
+ this._currentPath = ctx.currentPath;
+ }
+
+ function getOffset(i) {
+ return dashArray[((i % dashLength) + dashLength) % dashLength];
+ }
+
+ if (!dontPaint && (hasFill || hasStroke)) {
+ this._setStyles(ctx);
+ if (hasFill) {
+ ctx.fill(style.getWindingRule());
+ ctx.shadowColor = 'rgba(0,0,0,0)';
+ }
+ if (hasStroke) {
+ if (dashLength) {
+ if (!dontStart)
+ ctx.beginPath();
+ var iterator = new PathIterator(this, 32, 0.25,
+ strokeMatrix),
+ length = iterator.length,
+ from = -style.getDashOffset(), to,
+ i = 0;
+ from = from % length;
+ while (from > 0) {
+ from -= getOffset(i--) + getOffset(i--);
+ }
+ while (from < length) {
+ to = from + getOffset(i++);
+ if (from > 0 || to > 0)
+ iterator.drawPart(ctx,
+ Math.max(from, 0), Math.max(to, 0));
+ from = to + getOffset(i++);
+ }
+ }
+ ctx.stroke();
+ }
+ }
+ },
+
+ _drawSelected: function(ctx, matrix) {
+ ctx.beginPath();
+ drawSegments(ctx, this, matrix);
+ ctx.stroke();
+ drawHandles(ctx, this._segments, matrix, paper.settings.handleSize);
+ }
+ };
+}, new function() {
+
+ function getFirstControlPoints(rhs) {
+ var n = rhs.length,
+ x = [],
+ tmp = [],
+ b = 2;
+ x[0] = rhs[0] / b;
+ for (var i = 1; i < n; i++) {
+ tmp[i] = 1 / b;
+ b = (i < n - 1 ? 4 : 2) - tmp[i];
+ x[i] = (rhs[i] - x[i - 1]) / b;
+ }
+ for (var i = 1; i < n; i++) {
+ x[n - i - 1] -= tmp[n - i] * x[n - i];
+ }
+ return x;
+ }
+
+ return {
+ smooth: function() {
+ var segments = this._segments,
+ size = segments.length,
+ closed = this._closed,
+ n = size,
+ overlap = 0;
+ if (size <= 2)
+ return;
+ if (closed) {
+ overlap = Math.min(size, 4);
+ n += Math.min(size, overlap) * 2;
+ }
+ var knots = [];
+ for (var i = 0; i < size; i++)
+ knots[i + overlap] = segments[i]._point;
+ if (closed) {
+ for (var i = 0; i < overlap; i++) {
+ knots[i] = segments[i + size - overlap]._point;
+ knots[i + size + overlap] = segments[i]._point;
+ }
+ } else {
+ n--;
+ }
+ var rhs = [];
+
+ for (var 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] = 3 * knots[n - 1]._x;
+ var x = getFirstControlPoints(rhs);
+
+ for (var 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] = 3 * knots[n - 1]._y;
+ var y = getFirstControlPoints(rhs);
+
+ if (closed) {
+ for (var i = 0, j = size; i < overlap; i++, j++) {
+ var f1 = i / overlap,
+ f2 = 1 - f1,
+ ie = i + overlap,
+ je = j + overlap;
+ x[j] = x[i] * f1 + x[j] * f2;
+ y[j] = y[i] * f1 + y[j] * f2;
+ x[je] = x[ie] * f2 + x[je] * f1;
+ y[je] = y[ie] * f2 + y[je] * f1;
+ }
+ n--;
+ }
+ var handleIn = null;
+ for (var i = overlap; i <= n - overlap; i++) {
+ var segment = segments[i - overlap];
+ if (handleIn)
+ segment.setHandleIn(handleIn.subtract(segment._point));
+ if (i < n) {
+ segment.setHandleOut(
+ new Point(x[i], y[i]).subtract(segment._point));
+ handleIn = i < n - 1
+ ? new Point(
+ 2 * knots[i + 1]._x - x[i + 1],
+ 2 * knots[i + 1]._y - y[i + 1])
+ : new Point(
+ (knots[n]._x + x[n - 1]) / 2,
+ (knots[n]._y + y[n - 1]) / 2);
+ }
+ }
+ if (closed && handleIn) {
+ var segment = this._segments[0];
+ segment.setHandleIn(handleIn.subtract(segment._point));
+ }
+ }
+ };
+}, new function() {
+ function getCurrentSegment(that) {
+ var segments = that._segments;
+ if (segments.length === 0)
+ throw new Error('Use a moveTo() command first');
+ return segments[segments.length - 1];
+ }
+
+ return {
+ moveTo: function() {
+ var segments = this._segments;
+ if (segments.length === 1)
+ this.removeSegment(0);
+ if (!segments.length)
+ this._add([ new Segment(Point.read(arguments)) ]);
+ },
+
+ moveBy: function() {
+ throw new Error('moveBy() is unsupported on Path items.');
+ },
+
+ lineTo: function() {
+ this._add([ new Segment(Point.read(arguments)) ]);
+ },
+
+ cubicCurveTo: function() {
+ var handle1 = Point.read(arguments),
+ handle2 = Point.read(arguments),
+ to = Point.read(arguments),
+ current = getCurrentSegment(this);
+ current.setHandleOut(handle1.subtract(current._point));
+ this._add([ new Segment(to, handle2.subtract(to)) ]);
+ },
+
+ quadraticCurveTo: function() {
+ var handle = Point.read(arguments),
+ to = Point.read(arguments),
+ current = getCurrentSegment(this)._point;
+ this.cubicCurveTo(
+ handle.add(current.subtract(handle).multiply(1 / 3)),
+ handle.add(to.subtract(handle).multiply(1 / 3)),
+ to
+ );
+ },
+
+ curveTo: function() {
+ var through = Point.read(arguments),
+ to = Point.read(arguments),
+ t = Base.pick(Base.read(arguments), 0.5),
+ t1 = 1 - t,
+ current = getCurrentSegment(this)._point,
+ handle = through.subtract(current.multiply(t1 * t1))
+ .subtract(to.multiply(t * t)).divide(2 * t * t1);
+ if (handle.isNaN())
+ throw new Error(
+ 'Cannot put a curve through points with parameter = ' + t);
+ this.quadraticCurveTo(handle, to);
+ },
+
+ arcTo: function() {
+ var current = getCurrentSegment(this),
+ from = current._point,
+ to = Point.read(arguments),
+ through,
+ peek = Base.peek(arguments),
+ clockwise = Base.pick(peek, true),
+ center, extent, vector, matrix;
+ if (typeof clockwise === 'boolean') {
+ var middle = from.add(to).divide(2),
+ through = middle.add(middle.subtract(from).rotate(
+ clockwise ? -90 : 90));
+ } else if (Base.remain(arguments) <= 2) {
+ through = to;
+ to = Point.read(arguments);
+ } else {
+ var radius = Size.read(arguments);
+ if (radius.isZero())
+ return this.lineTo(to);
+ var rotation = Base.read(arguments),
+ clockwise = !!Base.read(arguments),
+ large = !!Base.read(arguments),
+ middle = from.add(to).divide(2),
+ pt = from.subtract(middle).rotate(-rotation),
+ x = pt.x,
+ y = pt.y,
+ abs = Math.abs,
+ EPSILON = 1e-11,
+ rx = abs(radius.width),
+ ry = abs(radius.height),
+ rxSq = rx * rx,
+ rySq = ry * ry,
+ xSq = x * x,
+ ySq = y * y;
+ var factor = Math.sqrt(xSq / rxSq + ySq / rySq);
+ if (factor > 1) {
+ rx *= factor;
+ ry *= factor;
+ rxSq = rx * rx;
+ rySq = ry * ry;
+ }
+ factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) /
+ (rxSq * ySq + rySq * xSq);
+ if (abs(factor) < EPSILON)
+ factor = 0;
+ if (factor < 0)
+ throw new Error(
+ 'Cannot create an arc with the given arguments');
+ center = new Point(rx * y / ry, -ry * x / rx)
+ .multiply((large === clockwise ? -1 : 1)
+ * Math.sqrt(factor))
+ .rotate(rotation).add(middle);
+ matrix = new Matrix().translate(center).rotate(rotation)
+ .scale(rx, ry);
+ vector = matrix._inverseTransform(from);
+ extent = vector.getDirectedAngle(matrix._inverseTransform(to));
+ if (!clockwise && extent > 0)
+ extent -= 360;
+ else if (clockwise && extent < 0)
+ extent += 360;
+ }
+ if (through) {
+ var l1 = new Line(from.add(through).divide(2),
+ through.subtract(from).rotate(90), true),
+ l2 = new Line(through.add(to).divide(2),
+ to.subtract(through).rotate(90), true),
+ line = new Line(from, to),
+ throughSide = line.getSide(through);
+ center = l1.intersect(l2, true);
+ if (!center) {
+ if (!throughSide)
+ return this.lineTo(to);
+ throw new Error(
+ 'Cannot create an arc with the given arguments');
+ }
+ vector = from.subtract(center);
+ extent = vector.getDirectedAngle(to.subtract(center));
+ var centerSide = line.getSide(center);
+ if (centerSide === 0) {
+ extent = throughSide * Math.abs(extent);
+ } else if (throughSide === centerSide) {
+ extent += extent < 0 ? 360 : -360;
+ }
+ }
+ var ext = Math.abs(extent),
+ count = ext >= 360 ? 4 : Math.ceil(ext / 90),
+ inc = extent / count,
+ half = inc * Math.PI / 360,
+ z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
+ segments = [];
+ for (var i = 0; i <= count; i++) {
+ var pt = to,
+ out = null;
+ if (i < count) {
+ out = vector.rotate(90).multiply(z);
+ if (matrix) {
+ pt = matrix._transformPoint(vector);
+ out = matrix._transformPoint(vector.add(out))
+ .subtract(pt);
+ } else {
+ pt = center.add(vector);
+ }
+ }
+ if (i === 0) {
+ current.setHandleOut(out);
+ } else {
+ var _in = vector.rotate(-90).multiply(z);
+ if (matrix) {
+ _in = matrix._transformPoint(vector.add(_in))
+ .subtract(pt);
+ }
+ segments.push(new Segment(pt, _in, out));
+ }
+ vector = vector.rotate(inc);
+ }
+ this._add(segments);
+ },
+
+ lineBy: function() {
+ var to = Point.read(arguments),
+ current = getCurrentSegment(this)._point;
+ this.lineTo(current.add(to));
+ },
+
+ curveBy: function() {
+ var through = Point.read(arguments),
+ to = Point.read(arguments),
+ parameter = Base.read(arguments),
+ current = getCurrentSegment(this)._point;
+ this.curveTo(current.add(through), current.add(to), parameter);
+ },
+
+ cubicCurveBy: function() {
+ var handle1 = Point.read(arguments),
+ handle2 = Point.read(arguments),
+ to = Point.read(arguments),
+ current = getCurrentSegment(this)._point;
+ this.cubicCurveTo(current.add(handle1), current.add(handle2),
+ current.add(to));
+ },
+
+ quadraticCurveBy: function() {
+ var handle = Point.read(arguments),
+ to = Point.read(arguments),
+ current = getCurrentSegment(this)._point;
+ this.quadraticCurveTo(current.add(handle), current.add(to));
+ },
+
+ arcBy: function() {
+ var current = getCurrentSegment(this)._point,
+ point = current.add(Point.read(arguments)),
+ clockwise = Base.pick(Base.peek(arguments), true);
+ if (typeof clockwise === 'boolean') {
+ this.arcTo(point, clockwise);
+ } else {
+ this.arcTo(point, current.add(Point.read(arguments)));
+ }
+ },
+
+ closePath: function(join) {
+ this.setClosed(true);
+ if (join)
+ this.join();
+ }
+ };
+}, {
+
+ _getBounds: function(getter, matrix) {
+ return Path[getter](this._segments, this._closed, this.getStyle(),
+ matrix);
+ },
+
+statics: {
+ isClockwise: function(segments) {
+ var sum = 0;
+ for (var i = 0, l = segments.length; i < l; i++) {
+ var v = Curve.getValues(
+ segments[i], segments[i + 1 < l ? i + 1 : 0]);
+ for (var j = 2; j < 8; j += 2)
+ sum += (v[j - 2] - v[j]) * (v[j + 1] + v[j - 1]);
+ }
+ return sum > 0;
+ },
+
+ getBounds: function(segments, closed, style, matrix, strokePadding) {
+ var first = segments[0];
+ if (!first)
+ return new Rectangle();
+ var coords = new Array(6),
+ prevCoords = first._transformCoordinates(matrix, new Array(6), false),
+ min = prevCoords.slice(0, 2),
+ max = min.slice(),
+ roots = new Array(2);
+
+ function processSegment(segment) {
+ segment._transformCoordinates(matrix, coords, false);
+ for (var i = 0; i < 2; i++) {
+ Curve._addBounds(
+ prevCoords[i],
+ prevCoords[i + 4],
+ coords[i + 2],
+ coords[i],
+ i, strokePadding ? strokePadding[i] : 0, min, max, roots);
+ }
+ var tmp = prevCoords;
+ prevCoords = coords;
+ coords = tmp;
+ }
+
+ for (var i = 1, l = segments.length; i < l; i++)
+ processSegment(segments[i]);
+ if (closed)
+ processSegment(first);
+ return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
+ },
+
+ getStrokeBounds: function(segments, closed, style, matrix) {
+ if (!style.hasStroke())
+ return Path.getBounds(segments, closed, style, matrix);
+ var length = segments.length - (closed ? 0 : 1),
+ radius = style.getStrokeWidth() / 2,
+ padding = Path._getPenPadding(radius, matrix),
+ bounds = Path.getBounds(segments, closed, style, matrix, padding),
+ join = style.getStrokeJoin(),
+ cap = style.getStrokeCap(),
+ miterLimit = radius * style.getMiterLimit();
+ var joinBounds = new Rectangle(new Size(padding).multiply(2));
+
+ function add(point) {
+ bounds = bounds.include(matrix
+ ? matrix._transformPoint(point, point) : point);
+ }
+
+ function addRound(segment) {
+ bounds = bounds.unite(joinBounds.setCenter(matrix
+ ? matrix._transformPoint(segment._point) : segment._point));
+ }
+
+ function addJoin(segment, join) {
+ var handleIn = segment._handleIn,
+ handleOut = segment._handleOut;
+ if (join === 'round' || !handleIn.isZero() && !handleOut.isZero()
+ && handleIn.isColinear(handleOut)) {
+ addRound(segment);
+ } else {
+ Path._addBevelJoin(segment, join, radius, miterLimit, add);
+ }
+ }
+
+ function addCap(segment, cap) {
+ if (cap === 'round') {
+ addRound(segment);
+ } else {
+ Path._addSquareCap(segment, cap, radius, add);
+ }
+ }
+
+ for (var i = 1; i < length; i++)
+ addJoin(segments[i], join);
+ if (closed) {
+ addJoin(segments[0], join);
+ } else if (length > 0) {
+ addCap(segments[0], cap);
+ addCap(segments[segments.length - 1], cap);
+ }
+ return bounds;
+ },
+
+ _getPenPadding: function(radius, matrix) {
+ if (!matrix)
+ return [radius, radius];
+ var mx = matrix.shiftless(),
+ hor = mx.transform(new Point(radius, 0)),
+ ver = mx.transform(new Point(0, radius)),
+ phi = hor.getAngleInRadians(),
+ a = hor.getLength(),
+ b = ver.getLength();
+ var sin = Math.sin(phi),
+ cos = Math.cos(phi),
+ tan = Math.tan(phi),
+ tx = -Math.atan(b * tan / a),
+ ty = Math.atan(b / (tan * a));
+ return [Math.abs(a * Math.cos(tx) * cos - b * Math.sin(tx) * sin),
+ Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
+ },
+
+ _addBevelJoin: function(segment, join, radius, miterLimit, addPoint, area) {
+ var curve2 = segment.getCurve(),
+ curve1 = curve2.getPrevious(),
+ point = curve2.getPointAt(0, true),
+ normal1 = curve1.getNormalAt(1, true),
+ normal2 = curve2.getNormalAt(0, true),
+ step = normal1.getDirectedAngle(normal2) < 0 ? -radius : radius;
+ normal1.setLength(step);
+ normal2.setLength(step);
+ if (area) {
+ addPoint(point);
+ addPoint(point.add(normal1));
+ }
+ if (join === 'miter') {
+ var corner = new Line(
+ point.add(normal1),
+ new Point(-normal1.y, normal1.x), true
+ ).intersect(new Line(
+ point.add(normal2),
+ new Point(-normal2.y, normal2.x), true
+ ), true);
+ if (corner && point.getDistance(corner) <= miterLimit) {
+ addPoint(corner);
+ if (!area)
+ return;
+ }
+ }
+ if (!area)
+ addPoint(point.add(normal1));
+ addPoint(point.add(normal2));
+ },
+
+ _addSquareCap: function(segment, cap, radius, addPoint, area) {
+ var point = segment._point,
+ loc = segment.getLocation(),
+ normal = loc.getNormal().normalize(radius);
+ if (area) {
+ addPoint(point.subtract(normal));
+ addPoint(point.add(normal));
+ }
+ if (cap === 'square')
+ point = point.add(normal.rotate(loc.getParameter() === 0 ? -90 : 90));
+ addPoint(point.add(normal));
+ addPoint(point.subtract(normal));
+ },
+
+ getHandleBounds: function(segments, closed, style, matrix, strokePadding,
+ joinPadding) {
+ var coords = new Array(6),
+ x1 = Infinity,
+ x2 = -x1,
+ y1 = x1,
+ y2 = x2;
+ for (var i = 0, l = segments.length; i < l; i++) {
+ var segment = segments[i];
+ segment._transformCoordinates(matrix, coords, false);
+ for (var j = 0; j < 6; j += 2) {
+ var padding = j === 0 ? joinPadding : strokePadding,
+ paddingX = padding ? padding[0] : 0,
+ paddingY = padding ? padding[1] : 0,
+ x = coords[j],
+ y = coords[j + 1],
+ xn = x - paddingX,
+ xx = x + paddingX,
+ yn = y - paddingY,
+ yx = y + paddingY;
+ if (xn < x1) x1 = xn;
+ if (xx > x2) x2 = xx;
+ if (yn < y1) y1 = yn;
+ if (yx > y2) y2 = yx;
+ }
+ }
+ return new Rectangle(x1, y1, x2 - x1, y2 - y1);
+ },
+
+ getRoughBounds: function(segments, closed, style, matrix) {
+ var strokeRadius = style.hasStroke() ? style.getStrokeWidth() / 2 : 0,
+ joinRadius = strokeRadius;
+ if (strokeRadius > 0) {
+ if (style.getStrokeJoin() === 'miter')
+ joinRadius = strokeRadius * style.getMiterLimit();
+ if (style.getStrokeCap() === 'square')
+ joinRadius = Math.max(joinRadius, strokeRadius * Math.sqrt(2));
+ }
+ return Path.getHandleBounds(segments, closed, style, matrix,
+ Path._getPenPadding(strokeRadius, matrix),
+ Path._getPenPadding(joinRadius, matrix));
+ }
+}});
+
+Path.inject({ statics: new function() {
+
+ var kappa = 0.5522847498307936,
+ ellipseSegments = [
+ new Segment([-1, 0], [0, kappa ], [0, -kappa]),
+ new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
+ new Segment([1, 0], [0, -kappa], [0, kappa ]),
+ new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
+ ];
+
+ function createPath(segments, closed, args) {
+ var props = Base.getNamed(args),
+ path = new Path(props && props.insert === false && Item.NO_INSERT);
+ path._add(segments);
+ path._closed = closed;
+ return path.set(props);
+ }
+
+ function createEllipse(center, radius, args) {
+ var segments = new Array(4);
+ for (var i = 0; i < 4; i++) {
+ var segment = ellipseSegments[i];
+ segments[i] = new Segment(
+ segment._point.multiply(radius).add(center),
+ segment._handleIn.multiply(radius),
+ segment._handleOut.multiply(radius)
+ );
+ }
+ return createPath(segments, true, args);
+ }
+
+ return {
+ Line: function() {
+ return createPath([
+ new Segment(Point.readNamed(arguments, 'from')),
+ new Segment(Point.readNamed(arguments, 'to'))
+ ], false, arguments);
+ },
+
+ Circle: function() {
+ var center = Point.readNamed(arguments, 'center'),
+ radius = Base.readNamed(arguments, 'radius');
+ return createEllipse(center, new Size(radius), arguments);
+ },
+
+ Rectangle: function() {
+ var rect = Rectangle.readNamed(arguments, 'rectangle'),
+ radius = Size.readNamed(arguments, 'radius', 0,
+ { readNull: true }),
+ bl = rect.getBottomLeft(true),
+ tl = rect.getTopLeft(true),
+ tr = rect.getTopRight(true),
+ br = rect.getBottomRight(true),
+ segments;
+ if (!radius || radius.isZero()) {
+ segments = [
+ new Segment(bl),
+ new Segment(tl),
+ new Segment(tr),
+ new Segment(br)
+ ];
+ } else {
+ radius = Size.min(radius, rect.getSize(true).divide(2));
+ var rx = radius.width,
+ ry = radius.height,
+ hx = rx * kappa,
+ hy = ry * kappa;
+ segments = [
+ new Segment(bl.add(rx, 0), null, [-hx, 0]),
+ new Segment(bl.subtract(0, ry), [0, hy]),
+ new Segment(tl.add(0, ry), null, [0, -hy]),
+ new Segment(tl.add(rx, 0), [-hx, 0], null),
+ new Segment(tr.subtract(rx, 0), null, [hx, 0]),
+ new Segment(tr.add(0, ry), [0, -hy], null),
+ new Segment(br.subtract(0, ry), null, [0, hy]),
+ new Segment(br.subtract(rx, 0), [hx, 0])
+ ];
+ }
+ return createPath(segments, true, arguments);
+ },
+
+ RoundRectangle: '#Rectangle',
+
+ Ellipse: function() {
+ var ellipse = Shape._readEllipse(arguments);
+ return createEllipse(ellipse.center, ellipse.radius, arguments);
+ },
+
+ Oval: '#Ellipse',
+
+ Arc: function() {
+ var from = Point.readNamed(arguments, 'from'),
+ through = Point.readNamed(arguments, 'through'),
+ to = Point.readNamed(arguments, 'to'),
+ props = Base.getNamed(arguments),
+ path = new Path(props && props.insert === false
+ && Item.NO_INSERT);
+ path.moveTo(from);
+ path.arcTo(through, to);
+ return path.set(props);
+ },
+
+ RegularPolygon: function() {
+ var center = Point.readNamed(arguments, 'center'),
+ sides = Base.readNamed(arguments, 'sides'),
+ radius = Base.readNamed(arguments, 'radius'),
+ step = 360 / sides,
+ three = !(sides % 3),
+ vector = new Point(0, three ? -radius : radius),
+ offset = three ? -1 : 0.5,
+ segments = new Array(sides);
+ for (var i = 0; i < sides; i++)
+ segments[i] = new Segment(center.add(
+ vector.rotate((i + offset) * step)));
+ return createPath(segments, true, arguments);
+ },
+
+ Star: function() {
+ var center = Point.readNamed(arguments, 'center'),
+ points = Base.readNamed(arguments, 'points') * 2,
+ radius1 = Base.readNamed(arguments, 'radius1'),
+ radius2 = Base.readNamed(arguments, 'radius2'),
+ step = 360 / points,
+ vector = new Point(0, -1),
+ segments = new Array(points);
+ for (var i = 0; i < points; i++)
+ segments[i] = new Segment(center.add(vector.rotate(step * i)
+ .multiply(i % 2 ? radius2 : radius1)));
+ return createPath(segments, true, arguments);
+ }
+ };
+}});
+
+var CompoundPath = PathItem.extend({
+ _class: 'CompoundPath',
+ _serializeFields: {
+ children: []
+ },
+
+ initialize: function CompoundPath(arg) {
+ this._children = [];
+ this._namedChildren = {};
+ if (!this._initialize(arg)) {
+ if (typeof arg === 'string') {
+ this.setPathData(arg);
+ } else {
+ this.addChildren(Array.isArray(arg) ? arg : arguments);
+ }
+ }
+ },
+
+ insertChildren: function insertChildren(index, items, _preserve) {
+ items = insertChildren.base.call(this, index, items, _preserve, Path);
+ for (var i = 0, l = !_preserve && items && items.length; i < l; i++) {
+ var item = items[i];
+ if (item._clockwise === undefined)
+ item.setClockwise(item._index === 0);
+ }
+ return items;
+ },
+
+ reverse: function() {
+ var children = this._children;
+ for (var i = 0, l = children.length; i < l; i++)
+ children[i].reverse();
+ },
+
+ smooth: function() {
+ for (var i = 0, l = this._children.length; i < l; i++)
+ this._children[i].smooth();
+ },
+
+ isClockwise: function() {
+ var child = this.getFirstChild();
+ return child && child.isClockwise();
+ },
+
+ setClockwise: function(clockwise) {
+ if (this.isClockwise() !== !!clockwise)
+ this.reverse();
+ },
+
+ getFirstSegment: function() {
+ var first = this.getFirstChild();
+ return first && first.getFirstSegment();
+ },
+
+ getLastSegment: function() {
+ var last = this.getLastChild();
+ return last && last.getLastSegment();
+ },
+
+ getCurves: function() {
+ var children = this._children,
+ curves = [];
+ for (var i = 0, l = children.length; i < l; i++)
+ curves.push.apply(curves, children[i].getCurves());
+ return curves;
+ },
+
+ getFirstCurve: function() {
+ var first = this.getFirstChild();
+ return first && first.getFirstCurve();
+ },
+
+ getLastCurve: function() {
+ var last = this.getLastChild();
+ return last && last.getFirstCurve();
+ },
+
+ getArea: function() {
+ var children = this._children,
+ area = 0;
+ for (var i = 0, l = children.length; i < l; i++)
+ area += children[i].getArea();
+ return area;
+ }
+}, {
+ beans: true,
+
+ getPathData: function(_matrix, _precision) {
+ var children = this._children,
+ paths = [];
+ for (var i = 0, l = children.length; i < l; i++) {
+ var child = children[i],
+ mx = child._matrix;
+ paths.push(child.getPathData(_matrix && !mx.isIdentity()
+ ? _matrix.chain(mx) : mx, _precision));
+ }
+ return paths.join(' ');
+ }
+}, {
+ _getChildHitTestOptions: function(options) {
+ return options.class === Path || options.type === 'path'
+ ? options
+ : new Base(options, { fill: false });
+ },
+
+ _draw: function(ctx, param, strokeMatrix) {
+ var children = this._children;
+ if (children.length === 0)
+ return;
+
+ if (this._currentPath) {
+ ctx.currentPath = this._currentPath;
+ } else {
+ param = param.extend({ dontStart: true, dontFinish: true });
+ ctx.beginPath();
+ for (var i = 0, l = children.length; i < l; i++)
+ children[i].draw(ctx, param, strokeMatrix);
+ this._currentPath = ctx.currentPath;
+ }
+
+ if (!param.clip) {
+ this._setStyles(ctx);
+ var style = this._style;
+ if (style.hasFill()) {
+ ctx.fill(style.getWindingRule());
+ ctx.shadowColor = 'rgba(0,0,0,0)';
+ }
+ if (style.hasStroke())
+ ctx.stroke();
+ }
+ },
+
+ _drawSelected: function(ctx, matrix, selectedItems) {
+ var children = this._children;
+ for (var i = 0, l = children.length; i < l; i++) {
+ var child = children[i],
+ mx = child._matrix;
+ if (!selectedItems[child._id])
+ child._drawSelected(ctx, mx.isIdentity() ? matrix
+ : matrix.chain(mx));
+ }
+ }
+}, new function() {
+ function getCurrentPath(that, check) {
+ var children = that._children;
+ if (check && children.length === 0)
+ throw new Error('Use a moveTo() command first');
+ return children[children.length - 1];
+ }
+
+ var fields = {
+ moveTo: function() {
+ var current = getCurrentPath(this),
+ path = current && current.isEmpty() ? current : new Path();
+ if (path !== current)
+ this.addChild(path);
+ path.moveTo.apply(path, arguments);
+ },
+
+ moveBy: function() {
+ var current = getCurrentPath(this, true),
+ last = current && current.getLastSegment(),
+ point = Point.read(arguments);
+ this.moveTo(last ? point.add(last._point) : point);
+ },
+
+ closePath: function(join) {
+ getCurrentPath(this, true).closePath(join);
+ }
+ };
+
+ Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo',
+ 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy', 'arcBy'],
+ function(key) {
+ fields[key] = function() {
+ var path = getCurrentPath(this, true);
+ path[key].apply(path, arguments);
+ };
+ }
+ );
+
+ return fields;
+});
+
+PathItem.inject(new function() {
+ function computeBoolean(path1, path2, operator, subtract) {
+ function preparePath(path) {
+ return path.clone(false).reduce().reorient().transform(null, true);
+ }
+
+ var _path1 = preparePath(path1),
+ _path2 = path2 && path1 !== path2 && preparePath(path2);
+ if (!_path1.isClockwise())
+ _path1.reverse();
+ if (_path2 && !(subtract ^ _path2.isClockwise()))
+ _path2.reverse();
+ splitPath(_path1.getIntersections(_path2, null, true));
+
+ var chain = [],
+ windings = [],
+ lengths = [],
+ segments = [],
+ monoCurves = [];
+
+ function collect(paths) {
+ for (var i = 0, l = paths.length; i < l; i++) {
+ var path = paths[i];
+ segments.push.apply(segments, path._segments);
+ monoCurves.push.apply(monoCurves, path._getMonoCurves());
+ }
+ }
+
+ collect(_path1._children || [_path1]);
+ if (_path2)
+ collect(_path2._children || [_path2]);
+ segments.sort(function(a, b) {
+ var _a = a._intersection,
+ _b = b._intersection;
+ return !_a && !_b || _a && _b ? 0 : _a ? -1 : 1;
+ });
+ for (var i = 0, l = segments.length; i < l; i++) {
+ var segment = segments[i];
+ if (segment._winding != null)
+ continue;
+ chain.length = windings.length = lengths.length = 0;
+ var totalLength = 0,
+ startSeg = segment;
+ do {
+ chain.push(segment);
+ lengths.push(totalLength += segment.getCurve().getLength());
+ segment = segment.getNext();
+ } while (segment && !segment._intersection && segment !== startSeg);
+ for (var j = 0; j < 3; j++) {
+ var length = totalLength * Math.random(),
+ amount = lengths.length,
+ k = 0;
+ do {
+ if (lengths[k] >= length) {
+ if (k > 0)
+ length -= lengths[k - 1];
+ break;
+ }
+ } while (++k < amount);
+ var curve = chain[k].getCurve(),
+ point = curve.getPointAt(length),
+ hor = curve.isHorizontal(),
+ path = curve._path;
+ if (path._parent instanceof CompoundPath)
+ path = path._parent;
+ windings[j] = subtract && _path2
+ && (path === _path1 && _path2._getWinding(point, hor)
+ || path === _path2 && !_path1._getWinding(point, hor))
+ ? 0
+ : getWinding(point, monoCurves, hor);
+ }
+ windings.sort();
+ var winding = windings[1];
+ for (var j = chain.length - 1; j >= 0; j--)
+ chain[j]._winding = winding;
+ }
+ var result = new CompoundPath();
+ result.addChildren(tracePaths(segments, operator), true);
+ _path1.remove();
+ if (_path2)
+ _path2.remove();
+ result = result.reduce();
+ result.setStyle(path1._style);
+ return result;
+ }
+
+ function splitPath(intersections) {
+ var TOLERANCE = 0.00001,
+ linearSegments;
+
+ function resetLinear() {
+ for (var i = 0, l = linearSegments.length; i < l; i++) {
+ var segment = linearSegments[i];
+ segment._handleOut.set(0, 0);
+ segment._handleIn.set(0, 0);
+ }
+ }
+
+ for (var i = intersections.length - 1, curve, prevLoc; i >= 0; i--) {
+ var loc = intersections[i],
+ t = loc._parameter;
+ if (prevLoc && prevLoc._curve === loc._curve
+ && prevLoc._parameter > 0) {
+ t /= prevLoc._parameter;
+ } else {
+ if (linearSegments)
+ resetLinear();
+ curve = loc._curve;
+ linearSegments = curve.isLinear() && [];
+ }
+ var newCurve,
+ segment;
+ if (newCurve = curve.divide(t, true, true)) {
+ segment = newCurve._segment1;
+ curve = newCurve.getPrevious();
+ } else {
+ segment = t < TOLERANCE
+ ? curve._segment1
+ : t > 1 - TOLERANCE
+ ? curve._segment2
+ : curve.getPartLength(0, t) < curve.getPartLength(t, 1)
+ ? curve._segment1
+ : curve._segment2;
+ }
+ segment._intersection = loc.getIntersection();
+ loc._segment = segment;
+ if (linearSegments)
+ linearSegments.push(segment);
+ prevLoc = loc;
+ }
+ if (linearSegments)
+ resetLinear();
+ }
+
+ function getWinding(point, curves, horizontal, testContains) {
+ var TOLERANCE = 0.00001,
+ x = point.x,
+ y = point.y,
+ windLeft = 0,
+ windRight = 0,
+ roots = [],
+ abs = Math.abs,
+ MAX = 1 - TOLERANCE;
+ if (horizontal) {
+ var yTop = -Infinity,
+ yBottom = Infinity,
+ yBefore = y - TOLERANCE,
+ yAfter = y + TOLERANCE;
+ for (var i = 0, l = curves.length; i < l; i++) {
+ var values = curves[i].values;
+ if (Curve.solveCubic(values, 0, x, roots, 0, 1) > 0) {
+ for (var j = roots.length - 1; j >= 0; j--) {
+ var y0 = Curve.evaluate(values, roots[j], 0).y;
+ if (y0 < yBefore && y0 > yTop) {
+ yTop = y0;
+ } else if (y0 > yAfter && y0 < yBottom) {
+ yBottom = y0;
+ }
+ }
+ }
+ }
+ yTop = (yTop + y) / 2;
+ yBottom = (yBottom + y) / 2;
+ if (yTop > -Infinity)
+ windLeft = getWinding(new Point(x, yTop), curves);
+ if (yBottom < Infinity)
+ windRight = getWinding(new Point(x, yBottom), curves);
+ } else {
+ var xBefore = x - TOLERANCE,
+ xAfter = x + TOLERANCE;
+ for (var i = 0, l = curves.length; i < l; i++) {
+ var curve = curves[i],
+ values = curve.values,
+ winding = curve.winding,
+ next = curve.next;
+ if (winding && (winding === 1
+ && y >= values[1] && y <= values[7]
+ || y >= values[7] && y <= values[1])
+ && Curve.solveCubic(values, 1, y, roots, 0,
+ !next.winding && next.values[1] === y ? 1 : MAX) === 1){
+ var t = roots[0],
+ x0 = Curve.evaluate(values, t, 0).x,
+ slope = Curve.evaluate(values, t, 1).y;
+ if (abs(slope) < TOLERANCE && !Curve.isLinear(values)
+ || t < TOLERANCE && slope * Curve.evaluate(
+ curve.previous.values, t, 1).y < 0) {
+ if (testContains && x0 >= xBefore && x0 <= xAfter) {
+ ++windLeft;
+ ++windRight;
+ }
+ } else if (x0 <= xBefore) {
+ windLeft += winding;
+ } else if (x0 >= xAfter) {
+ windRight += winding;
+ }
+ }
+ }
+ }
+ return Math.max(abs(windLeft), abs(windRight));
+ }
+
+ function tracePaths(segments, operator, selfOp) {
+ operator = operator || function() {
+ return true;
+ };
+ var paths = [],
+ ZERO = 1e-3,
+ ONE = 1 - 1e-3;
+ for (var i = 0, seg, startSeg, l = segments.length; i < l; i++) {
+ seg = startSeg = segments[i];
+ if (seg._visited || !operator(seg._winding))
+ continue;
+ var path = new Path(Item.NO_INSERT),
+ inter = seg._intersection,
+ startInterSeg = inter && inter._segment,
+ added = false,
+ dir = 1;
+ do {
+ var handleIn = dir > 0 ? seg._handleIn : seg._handleOut,
+ handleOut = dir > 0 ? seg._handleOut : seg._handleIn,
+ interSeg;
+ if (added && (!operator(seg._winding) || selfOp)
+ && (inter = seg._intersection)
+ && (interSeg = inter._segment)
+ && interSeg !== startSeg) {
+ if (selfOp) {
+ seg._visited = interSeg._visited;
+ seg = interSeg;
+ dir = 1;
+ } else {
+ var c1 = seg.getCurve();
+ if (dir > 0)
+ c1 = c1.getPrevious();
+ var t1 = c1.getTangentAt(dir < 1 ? ZERO : ONE, true),
+ c4 = interSeg.getCurve(),
+ c3 = c4.getPrevious(),
+ t3 = c3.getTangentAt(ONE, true),
+ t4 = c4.getTangentAt(ZERO, true),
+ w3 = t1.cross(t3),
+ w4 = t1.cross(t4);
+ if (w3 * w4 !== 0) {
+ var curve = w3 < w4 ? c3 : c4,
+ nextCurve = operator(curve._segment1._winding)
+ ? curve
+ : w3 < w4 ? c4 : c3,
+ nextSeg = nextCurve._segment1;
+ dir = nextCurve === c3 ? -1 : 1;
+ if (nextSeg._visited && seg._path !== nextSeg._path
+ || !operator(nextSeg._winding)) {
+ dir = 1;
+ } else {
+ seg._visited = interSeg._visited;
+ seg = interSeg;
+ if (nextSeg._visited)
+ dir = 1;
+ }
+ } else {
+ dir = 1;
+ }
+ }
+ handleOut = dir > 0 ? seg._handleOut : seg._handleIn;
+ }
+ path.add(new Segment(seg._point, added && handleIn, handleOut));
+ added = true;
+ seg._visited = true;
+ seg = dir > 0 ? seg.getNext() : seg. getPrevious();
+ } while (seg && !seg._visited
+ && seg !== startSeg && seg !== startInterSeg
+ && (seg._intersection || operator(seg._winding)));
+ if (seg && (seg === startSeg || seg === startInterSeg)) {
+ path.firstSegment.setHandleIn((seg === startInterSeg
+ ? startInterSeg : seg)._handleIn);
+ path.setClosed(true);
+ } else {
+ path.lastSegment._handleOut.set(0, 0);
+ }
+ if (path._segments.length >
+ (path._closed ? path.isPolygon() ? 2 : 0 : 1))
+ paths.push(path);
+ }
+ return paths;
+ }
+
+ return {
+ _getWinding: function(point, horizontal, testContains) {
+ return getWinding(point, this._getMonoCurves(),
+ horizontal, testContains);
+ },
+
+ unite: function(path) {
+ return computeBoolean(this, path, function(w) {
+ return w === 1 || w === 0;
+ }, false);
+ },
+
+ intersect: function(path) {
+ return computeBoolean(this, path, function(w) {
+ return w === 2;
+ }, false);
+ },
+
+ subtract: function(path) {
+ return computeBoolean(this, path, function(w) {
+ return w === 1;
+ }, true);
+ },
+
+ exclude: function(path) {
+ return new Group([this.subtract(path), path.subtract(this)]);
+ },
+
+ divide: function(path) {
+ return new Group([this.subtract(path), this.intersect(path)]);
+ }
+ };
+});
+
+Path.inject({
+ _getMonoCurves: function() {
+ var monoCurves = this._monoCurves,
+ prevCurve;
+
+ function insertCurve(v) {
+ var y0 = v[1],
+ y1 = v[7],
+ curve = {
+ values: v,
+ winding: y0 === y1
+ ? 0
+ : y0 > y1
+ ? -1
+ : 1,
+ previous: prevCurve,
+ next: null
+ };
+ if (prevCurve)
+ prevCurve.next = curve;
+ monoCurves.push(curve);
+ prevCurve = curve;
+ }
+
+ function handleCurve(v) {
+ if (Curve.getLength(v) === 0)
+ return;
+ var y0 = v[1],
+ y1 = v[3],
+ y2 = v[5],
+ y3 = v[7];
+ if (Curve.isLinear(v)) {
+ insertCurve(v);
+ } else {
+ var a = 3 * (y1 - y2) - y0 + y3,
+ b = 2 * (y0 + y2) - 4 * y1,
+ c = y1 - y0,
+ TOLERANCE = 0.00001,
+ roots = [];
+ var count = Numerical.solveQuadratic(a, b, c, roots, TOLERANCE,
+ 1 - TOLERANCE);
+ if (count === 0) {
+ insertCurve(v);
+ } else {
+ roots.sort();
+ var t = roots[0],
+ parts = Curve.subdivide(v, t);
+ insertCurve(parts[0]);
+ if (count > 1) {
+ t = (roots[1] - t) / (1 - t);
+ parts = Curve.subdivide(parts[1], t);
+ insertCurve(parts[0]);
+ }
+ insertCurve(parts[1]);
+ }
+ }
+ }
+
+ if (!monoCurves) {
+ monoCurves = this._monoCurves = [];
+ var curves = this.getCurves(),
+ segments = this._segments;
+ for (var i = 0, l = curves.length; i < l; i++)
+ handleCurve(curves[i].getValues());
+ if (!this._closed && segments.length > 1) {
+ var p1 = segments[segments.length - 1]._point,
+ p2 = segments[0]._point,
+ p1x = p1._x, p1y = p1._y,
+ p2x = p2._x, p2y = p2._y;
+ handleCurve([p1x, p1y, p1x, p1y, p2x, p2y, p2x, p2y]);
+ }
+ if (monoCurves.length > 0) {
+ var first = monoCurves[0],
+ last = monoCurves[monoCurves.length - 1];
+ first.previous = last;
+ last.next = first;
+ }
+ }
+ return monoCurves;
+ },
+
+ getInteriorPoint: function() {
+ var bounds = this.getBounds(),
+ point = bounds.getCenter(true);
+ if (!this.contains(point)) {
+ var curves = this._getMonoCurves(),
+ roots = [],
+ y = point.y,
+ xIntercepts = [];
+ for (var i = 0, l = curves.length; i < l; i++) {
+ var values = curves[i].values;
+ if ((curves[i].winding === 1
+ && y >= values[1] && y <= values[7]
+ || y >= values[7] && y <= values[1])
+ && Curve.solveCubic(values, 1, y, roots, 0, 1) > 0) {
+ for (var j = roots.length - 1; j >= 0; j--)
+ xIntercepts.push(Curve.evaluate(values, roots[j], 0).x);
+ }
+ if (xIntercepts.length > 1)
+ break;
+ }
+ point.x = (xIntercepts[0] + xIntercepts[1]) / 2;
+ }
+ return point;
+ },
+
+ reorient: function() {
+ this.setClockwise(true);
+ return this;
+ }
+});
+
+CompoundPath.inject({
+ _getMonoCurves: function() {
+ var children = this._children,
+ monoCurves = [];
+ for (var i = 0, l = children.length; i < l; i++)
+ monoCurves.push.apply(monoCurves, children[i]._getMonoCurves());
+ return monoCurves;
+ },
+
+ reorient: function() {
+ var children = this.removeChildren().sort(function(a, b) {
+ return b.getBounds().getArea() - a.getBounds().getArea();
+ });
+ this.addChildren(children);
+ var clockwise = children[0].isClockwise();
+ for (var i = 1, l = children.length; i < l; i++) {
+ var point = children[i].getInteriorPoint(),
+ counters = 0;
+ for (var j = i - 1; j >= 0; j--) {
+ if (children[j].contains(point))
+ counters++;
+ }
+ children[i].setClockwise(counters % 2 === 0 && clockwise);
+ }
+ return this;
+ }
+});
+
+var PathIterator = Base.extend({
+ _class: 'PathIterator',
+
+ initialize: function(path, maxRecursion, tolerance, matrix) {
+ var curves = [],
+ parts = [],
+ length = 0,
+ minDifference = 1 / (maxRecursion || 32),
+ segments = path._segments,
+ segment1 = segments[0],
+ segment2;
+
+ function addCurve(segment1, segment2) {
+ var curve = Curve.getValues(segment1, segment2, matrix);
+ curves.push(curve);
+ computeParts(curve, segment1._index, 0, 1);
+ }
+
+ function computeParts(curve, index, minT, maxT) {
+ if ((maxT - minT) > minDifference
+ && !Curve.isFlatEnough(curve, tolerance || 0.25)) {
+ var split = Curve.subdivide(curve),
+ halfT = (minT + maxT) / 2;
+ computeParts(split[0], index, minT, halfT);
+ computeParts(split[1], index, halfT, maxT);
+ } else {
+ var x = curve[6] - curve[0],
+ y = curve[7] - curve[1],
+ dist = Math.sqrt(x * x + y * y);
+ if (dist > 0.00001) {
+ length += dist;
+ parts.push({
+ offset: length,
+ value: maxT,
+ index: index
+ });
+ }
+ }
+ }
+
+ for (var i = 1, l = segments.length; i < l; i++) {
+ segment2 = segments[i];
+ addCurve(segment1, segment2);
+ segment1 = segment2;
+ }
+ if (path._closed)
+ addCurve(segment2, segments[0]);
+
+ this.curves = curves;
+ this.parts = parts;
+ this.length = length;
+ this.index = 0;
+ },
+
+ getParameterAt: function(offset) {
+ var i, j = this.index;
+ for (;;) {
+ i = j;
+ if (j == 0 || this.parts[--j].offset < offset)
+ break;
+ }
+ for (var l = this.parts.length; i < l; i++) {
+ var part = this.parts[i];
+ if (part.offset >= offset) {
+ this.index = i;
+ var prev = this.parts[i - 1];
+ var prevVal = prev && prev.index == part.index ? prev.value : 0,
+ prevLen = prev ? prev.offset : 0;
+ return {
+ value: prevVal + (part.value - prevVal)
+ * (offset - prevLen) / (part.offset - prevLen),
+ index: part.index
+ };
+ }
+ }
+ var part = this.parts[this.parts.length - 1];
+ return {
+ value: 1,
+ index: part.index
+ };
+ },
+
+ evaluate: function(offset, type) {
+ var param = this.getParameterAt(offset);
+ return Curve.evaluate(this.curves[param.index], param.value, type);
+ },
+
+ drawPart: function(ctx, from, to) {
+ from = this.getParameterAt(from);
+ to = this.getParameterAt(to);
+ for (var i = from.index; i <= to.index; i++) {
+ var curve = Curve.getPart(this.curves[i],
+ i == from.index ? from.value : 0,
+ i == to.index ? to.value : 1);
+ if (i == from.index)
+ ctx.moveTo(curve[0], curve[1]);
+ ctx.bezierCurveTo.apply(ctx, curve.slice(2));
+ }
+ }
+}, Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],
+ function(name, index) {
+ this[name + 'At'] = function(offset) {
+ return this.evaluate(offset, index);
+ };
+ }, {})
+);
+
+var PathFitter = Base.extend({
+ initialize: function(path, error) {
+ this.points = [];
+ var segments = path._segments,
+ prev;
+ for (var i = 0, l = segments.length; i < l; i++) {
+ var point = segments[i].point.clone();
+ if (!prev || !prev.equals(point)) {
+ this.points.push(point);
+ prev = point;
+ }
+ }
+ this.error = error;
+ },
+
+ fit: function() {
+ var points = this.points,
+ length = points.length;
+ this.segments = length > 0 ? [new Segment(points[0])] : [];
+ if (length > 1)
+ this.fitCubic(0, length - 1,
+ points[1].subtract(points[0]).normalize(),
+ points[length - 2].subtract(points[length - 1]).normalize());
+ return this.segments;
+ },
+
+ fitCubic: function(first, last, tan1, tan2) {
+ if (last - first == 1) {
+ var pt1 = this.points[first],
+ pt2 = this.points[last],
+ dist = pt1.getDistance(pt2) / 3;
+ this.addCurve([pt1, pt1.add(tan1.normalize(dist)),
+ pt2.add(tan2.normalize(dist)), pt2]);
+ return;
+ }
+ var uPrime = this.chordLengthParameterize(first, last),
+ maxError = Math.max(this.error, this.error * this.error),
+ split;
+ for (var i = 0; i <= 4; i++) {
+ var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
+ var max = this.findMaxError(first, last, curve, uPrime);
+ if (max.error < this.error) {
+ this.addCurve(curve);
+ return;
+ }
+ split = max.index;
+ if (max.error >= maxError)
+ break;
+ this.reparameterize(first, last, uPrime, curve);
+ maxError = max.error;
+ }
+ var V1 = this.points[split - 1].subtract(this.points[split]),
+ V2 = this.points[split].subtract(this.points[split + 1]),
+ tanCenter = V1.add(V2).divide(2).normalize();
+ this.fitCubic(first, split, tan1, tanCenter);
+ this.fitCubic(split, last, tanCenter.negate(), tan2);
+ },
+
+ addCurve: function(curve) {
+ var prev = this.segments[this.segments.length - 1];
+ prev.setHandleOut(curve[1].subtract(curve[0]));
+ this.segments.push(
+ new Segment(curve[3], curve[2].subtract(curve[3])));
+ },
+
+ generateBezier: function(first, last, uPrime, tan1, tan2) {
+ var epsilon = 1e-11,
+ pt1 = this.points[first],
+ pt2 = this.points[last],
+ C = [[0, 0], [0, 0]],
+ X = [0, 0];
+
+ for (var i = 0, l = last - first + 1; i < l; i++) {
+ var u = uPrime[i],
+ t = 1 - u,
+ b = 3 * u * t,
+ b0 = t * t * t,
+ b1 = b * t,
+ b2 = b * u,
+ b3 = u * u * u,
+ a1 = tan1.normalize(b1),
+ a2 = tan2.normalize(b2),
+ tmp = this.points[first + i]
+ .subtract(pt1.multiply(b0 + b1))
+ .subtract(pt2.multiply(b2 + b3));
+ C[0][0] += a1.dot(a1);
+ C[0][1] += a1.dot(a2);
+ C[1][0] = C[0][1];
+ C[1][1] += a2.dot(a2);
+ X[0] += a1.dot(tmp);
+ X[1] += a2.dot(tmp);
+ }
+
+ var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
+ alpha1, alpha2;
+ if (Math.abs(detC0C1) > epsilon) {
+ var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
+ detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
+ alpha1 = detXC1 / detC0C1;
+ alpha2 = detC0X / detC0C1;
+ } else {
+ var c0 = C[0][0] + C[0][1],
+ c1 = C[1][0] + C[1][1];
+ if (Math.abs(c0) > epsilon) {
+ alpha1 = alpha2 = X[0] / c0;
+ } else if (Math.abs(c1) > epsilon) {
+ alpha1 = alpha2 = X[1] / c1;
+ } else {
+ alpha1 = alpha2 = 0;
+ }
+ }
+
+ var segLength = pt2.getDistance(pt1);
+ epsilon *= segLength;
+ if (alpha1 < epsilon || alpha2 < epsilon) {
+ alpha1 = alpha2 = segLength / 3;
+ }
+
+ return [pt1, pt1.add(tan1.normalize(alpha1)),
+ pt2.add(tan2.normalize(alpha2)), pt2];
+ },
+
+ reparameterize: function(first, last, u, curve) {
+ for (var i = first; i <= last; i++) {
+ u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
+ }
+ },
+
+ findRoot: function(curve, point, u) {
+ var curve1 = [],
+ curve2 = [];
+ for (var i = 0; i <= 2; i++) {
+ curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
+ }
+ for (var i = 0; i <= 1; i++) {
+ curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
+ }
+ var pt = this.evaluate(3, curve, u),
+ pt1 = this.evaluate(2, curve1, u),
+ pt2 = this.evaluate(1, curve2, u),
+ diff = pt.subtract(point),
+ df = pt1.dot(pt1) + diff.dot(pt2);
+ if (Math.abs(df) < 0.00001)
+ return u;
+ return u - diff.dot(pt1) / df;
+ },
+
+ evaluate: function(degree, curve, t) {
+ var tmp = curve.slice();
+ for (var i = 1; i <= degree; i++) {
+ for (var j = 0; j <= degree - i; j++) {
+ tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
+ }
+ }
+ return tmp[0];
+ },
+
+ chordLengthParameterize: function(first, last) {
+ var u = [0];
+ for (var i = first + 1; i <= last; i++) {
+ u[i - first] = u[i - first - 1]
+ + this.points[i].getDistance(this.points[i - 1]);
+ }
+ for (var i = 1, m = last - first; i <= m; i++) {
+ u[i] /= u[m];
+ }
+ return u;
+ },
+
+ findMaxError: function(first, last, curve, u) {
+ var index = Math.floor((last - first + 1) / 2),
+ maxDist = 0;
+ for (var i = first + 1; i < last; i++) {
+ var P = this.evaluate(3, curve, u[i - first]);
+ var v = P.subtract(this.points[i]);
+ var dist = v.x * v.x + v.y * v.y;
+ if (dist >= maxDist) {
+ maxDist = dist;
+ index = i;
+ }
+ }
+ return {
+ error: maxDist,
+ index: index
+ };
+ }
+});
+
+var TextItem = Item.extend({
+ _class: 'TextItem',
+ _boundsSelected: true,
+ _applyMatrix: false,
+ _canApplyMatrix: false,
+ _serializeFields: {
+ content: null
+ },
+ _boundsGetter: 'getBounds',
+
+ initialize: function TextItem(arg) {
+ this._content = '';
+ this._lines = [];
+ var hasProps = arg && Base.isPlainObject(arg)
+ && arg.x === undefined && arg.y === undefined;
+ this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
+ },
+
+ _equals: function(item) {
+ return this._content === item._content;
+ },
+
+ _clone: function _clone(copy) {
+ copy.setContent(this._content);
+ return _clone.base.call(this, copy);
+ },
+
+ getContent: function() {
+ return this._content;
+ },
+
+ setContent: function(content) {
+ this._content = '' + content;
+ this._lines = this._content.split(/\r\n|\n|\r/mg);
+ this._changed(265);
+ },
+
+ isEmpty: function() {
+ return !this._content;
+ },
+
+ getCharacterStyle: '#getStyle',
+ setCharacterStyle: '#setStyle',
+
+ getParagraphStyle: '#getStyle',
+ setParagraphStyle: '#setStyle'
+});
+
+var PointText = TextItem.extend({
+ _class: 'PointText',
+
+ initialize: function PointText() {
+ TextItem.apply(this, arguments);
+ },
+
+ clone: function(insert) {
+ return this._clone(new PointText(Item.NO_INSERT), insert);
+ },
+
+ getPoint: function() {
+ var point = this._matrix.getTranslation();
+ return new LinkedPoint(point.x, point.y, this, 'setPoint');
+ },
+
+ setPoint: function() {
+ var point = Point.read(arguments);
+ this.translate(point.subtract(this._matrix.getTranslation()));
+ },
+
+ _draw: function(ctx) {
+ if (!this._content)
+ return;
+ this._setStyles(ctx);
+ var style = this._style,
+ lines = this._lines,
+ leading = style.getLeading(),
+ shadowColor = ctx.shadowColor;
+ ctx.font = style.getFontStyle();
+ ctx.textAlign = style.getJustification();
+ for (var i = 0, l = lines.length; i < l; i++) {
+ ctx.shadowColor = shadowColor;
+ var line = lines[i];
+ if (style.hasFill()) {
+ ctx.fillText(line, 0, 0);
+ ctx.shadowColor = 'rgba(0,0,0,0)';
+ }
+ if (style.hasStroke())
+ ctx.strokeText(line, 0, 0);
+ ctx.translate(0, leading);
+ }
+ },
+
+ _getBounds: function(getter, matrix) {
+ var style = this._style,
+ lines = this._lines,
+ numLines = lines.length,
+ justification = style.getJustification(),
+ leading = style.getLeading(),
+ width = this.getView().getTextWidth(style.getFontStyle(), lines),
+ x = 0;
+ if (justification !== 'left')
+ x -= width / (justification === 'center' ? 2: 1);
+ var bounds = new Rectangle(x,
+ numLines ? - 0.75 * leading : 0,
+ width, numLines * leading);
+ return matrix ? matrix._transformBounds(bounds, bounds) : bounds;
+ }
+});
+
+var Color = Base.extend(new function() {
+ var types = {
+ gray: ['gray'],
+ rgb: ['red', 'green', 'blue'],
+ hsb: ['hue', 'saturation', 'brightness'],
+ hsl: ['hue', 'saturation', 'lightness'],
+ gradient: ['gradient', 'origin', 'destination', 'highlight']
+ };
+
+ var componentParsers = {},
+ colorCache = {},
+ colorCtx;
+
+ function fromCSS(string) {
+ var match = string.match(/^#(\w{1,2})(\w{1,2})(\w{1,2})$/),
+ components;
+ if (match) {
+ components = [0, 0, 0];
+ for (var i = 0; i < 3; i++) {
+ var value = match[i + 1];
+ components[i] = parseInt(value.length == 1
+ ? value + value : value, 16) / 255;
+ }
+ } else if (match = string.match(/^rgba?\((.*)\)$/)) {
+ components = match[1].split(',');
+ for (var i = 0, l = components.length; i < l; i++) {
+ var value = +components[i];
+ components[i] = i < 3 ? value / 255 : value;
+ }
+ } else {
+ var cached = colorCache[string];
+ if (!cached) {
+ if (!colorCtx) {
+ colorCtx = CanvasProvider.getContext(1, 1);
+ colorCtx.globalCompositeOperation = 'copy';
+ }
+ colorCtx.fillStyle = 'rgba(0,0,0,0)';
+ colorCtx.fillStyle = string;
+ colorCtx.fillRect(0, 0, 1, 1);
+ var data = colorCtx.getImageData(0, 0, 1, 1).data;
+ cached = colorCache[string] = [
+ data[0] / 255,
+ data[1] / 255,
+ data[2] / 255
+ ];
+ }
+ components = cached.slice();
+ }
+ return components;
+ }
+
+ var hsbIndices = [
+ [0, 3, 1],
+ [2, 0, 1],
+ [1, 0, 3],
+ [1, 2, 0],
+ [3, 1, 0],
+ [0, 1, 2]
+ ];
+
+ var converters = {
+ 'rgb-hsb': function(r, g, b) {
+ var max = Math.max(r, g, b),
+ min = Math.min(r, g, b),
+ delta = max - min,
+ h = delta === 0 ? 0
+ : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
+ : max == g ? (b - r) / delta + 2
+ : (r - g) / delta + 4) * 60;
+ return [h, max === 0 ? 0 : delta / max, max];
+ },
+
+ 'hsb-rgb': function(h, s, b) {
+ h = (((h / 60) % 6) + 6) % 6;
+ var i = Math.floor(h),
+ f = h - i,
+ i = hsbIndices[i],
+ v = [
+ b,
+ b * (1 - s),
+ b * (1 - s * f),
+ b * (1 - s * (1 - f))
+ ];
+ return [v[i[0]], v[i[1]], v[i[2]]];
+ },
+
+ 'rgb-hsl': function(r, g, b) {
+ var max = Math.max(r, g, b),
+ min = Math.min(r, g, b),
+ delta = max - min,
+ achromatic = delta === 0,
+ h = achromatic ? 0
+ : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
+ : max == g ? (b - r) / delta + 2
+ : (r - g) / delta + 4) * 60,
+ l = (max + min) / 2,
+ s = achromatic ? 0 : l < 0.5
+ ? delta / (max + min)
+ : delta / (2 - max - min);
+ return [h, s, l];
+ },
+
+ 'hsl-rgb': function(h, s, l) {
+ h = (((h / 360) % 1) + 1) % 1;
+ if (s === 0)
+ return [l, l, l];
+ var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
+ t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
+ t1 = 2 * l - t2,
+ c = [];
+ for (var i = 0; i < 3; i++) {
+ var t3 = t3s[i];
+ if (t3 < 0) t3 += 1;
+ if (t3 > 1) t3 -= 1;
+ c[i] = 6 * t3 < 1
+ ? t1 + (t2 - t1) * 6 * t3
+ : 2 * t3 < 1
+ ? t2
+ : 3 * t3 < 2
+ ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
+ : t1;
+ }
+ return c;
+ },
+
+ 'rgb-gray': function(r, g, b) {
+ return [r * 0.2989 + g * 0.587 + b * 0.114];
+ },
+
+ 'gray-rgb': function(g) {
+ return [g, g, g];
+ },
+
+ 'gray-hsb': function(g) {
+ return [0, 0, g];
+ },
+
+ 'gray-hsl': function(g) {
+ return [0, 0, g];
+ },
+
+ 'gradient-rgb': function() {
+ return [];
+ },
+
+ 'rgb-gradient': function() {
+ return [];
+ }
+
+ };
+
+ return Base.each(types, function(properties, type) {
+ componentParsers[type] = [];
+ Base.each(properties, function(name, index) {
+ var part = Base.capitalize(name),
+ hasOverlap = /^(hue|saturation)$/.test(name),
+ parser = componentParsers[type][index] = name === 'gradient'
+ ? function(value) {
+ var current = this._components[0];
+ value = Gradient.read(Array.isArray(value) ? value
+ : arguments, 0, { readNull: true });
+ if (current !== value) {
+ if (current)
+ current._removeOwner(this);
+ if (value)
+ value._addOwner(this);
+ }
+ return value;
+ }
+ : type === 'gradient'
+ ? function() {
+ return Point.read(arguments, 0, {
+ readNull: name === 'highlight',
+ clone: true
+ });
+ }
+ : function(value) {
+ return value == null || isNaN(value) ? 0 : value;
+ };
+
+ this['get' + part] = function() {
+ return this._type === type
+ || hasOverlap && /^hs[bl]$/.test(this._type)
+ ? this._components[index]
+ : this._convert(type)[index];
+ };
+
+ this['set' + part] = function(value) {
+ if (this._type !== type
+ && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
+ this._components = this._convert(type);
+ this._properties = types[type];
+ this._type = type;
+ }
+ value = parser.call(this, value);
+ if (value != null) {
+ this._components[index] = value;
+ this._changed();
+ }
+ };
+ }, this);
+ }, {
+ _class: 'Color',
+ _readIndex: true,
+
+ initialize: function Color(arg) {
+ var slice = Array.prototype.slice,
+ args = arguments,
+ read = 0,
+ type,
+ components,
+ alpha,
+ values;
+ if (Array.isArray(arg)) {
+ args = arg;
+ arg = args[0];
+ }
+ var argType = arg != null && typeof arg;
+ if (argType === 'string' && arg in types) {
+ type = arg;
+ arg = args[1];
+ if (Array.isArray(arg)) {
+ components = arg;
+ alpha = args[2];
+ } else {
+ if (this.__read)
+ read = 1;
+ args = slice.call(args, 1);
+ argType = typeof arg;
+ }
+ }
+ if (!components) {
+ values = argType === 'number'
+ ? args
+ : argType === 'object' && arg.length != null
+ ? arg
+ : null;
+ if (values) {
+ if (!type)
+ type = values.length >= 3
+ ? 'rgb'
+ : 'gray';
+ var length = types[type].length;
+ alpha = values[length];
+ if (this.__read)
+ read += values === arguments
+ ? length + (alpha != null ? 1 : 0)
+ : 1;
+ if (values.length > length)
+ values = slice.call(values, 0, length);
+ } else if (argType === 'string') {
+ type = 'rgb';
+ components = fromCSS(arg);
+ if (components.length === 4) {
+ alpha = components[3];
+ components.length--;
+ }
+ } else if (argType === 'object') {
+ if (arg.constructor === Color) {
+ type = arg._type;
+ components = arg._components.slice();
+ alpha = arg._alpha;
+ if (type === 'gradient') {
+ for (var i = 1, l = components.length; i < l; i++) {
+ var point = components[i];
+ if (point)
+ components[i] = point.clone();
+ }
+ }
+ } else if (arg.constructor === Gradient) {
+ type = 'gradient';
+ values = args;
+ } else {
+ type = 'hue' in arg
+ ? 'lightness' in arg
+ ? 'hsl'
+ : 'hsb'
+ : 'gradient' in arg || 'stops' in arg
+ || 'radial' in arg
+ ? 'gradient'
+ : 'gray' in arg
+ ? 'gray'
+ : 'rgb';
+ var properties = types[type];
+ parsers = componentParsers[type];
+ this._components = components = [];
+ for (var i = 0, l = properties.length; i < l; i++) {
+ var value = arg[properties[i]];
+ if (value == null && i === 0 && type === 'gradient'
+ && 'stops' in arg) {
+ value = {
+ stops: arg.stops,
+ radial: arg.radial
+ };
+ }
+ value = parsers[i].call(this, value);
+ if (value != null)
+ components[i] = value;
+ }
+ alpha = arg.alpha;
+ }
+ }
+ if (this.__read && type)
+ read = 1;
+ }
+ this._type = type || 'rgb';
+ if (type === 'gradient')
+ this._id = Color._id = (Color._id || 0) + 1;
+ if (!components) {
+ this._components = components = [];
+ var parsers = componentParsers[this._type];
+ for (var i = 0, l = parsers.length; i < l; i++) {
+ var value = parsers[i].call(this, values && values[i]);
+ if (value != null)
+ components[i] = value;
+ }
+ }
+ this._components = components;
+ this._properties = types[this._type];
+ this._alpha = alpha;
+ if (this.__read)
+ this.__read = read;
+ },
+
+ _serialize: function(options, dictionary) {
+ var components = this.getComponents();
+ return Base.serialize(
+ /^(gray|rgb)$/.test(this._type)
+ ? components
+ : [this._type].concat(components),
+ options, true, dictionary);
+ },
+
+ _changed: function() {
+ this._canvasStyle = null;
+ if (this._owner)
+ this._owner._changed(65);
+ },
+
+ _convert: function(type) {
+ var converter;
+ return this._type === type
+ ? this._components.slice()
+ : (converter = converters[this._type + '-' + type])
+ ? converter.apply(this, this._components)
+ : converters['rgb-' + type].apply(this,
+ converters[this._type + '-rgb'].apply(this,
+ this._components));
+ },
+
+ convert: function(type) {
+ return new Color(type, this._convert(type), this._alpha);
+ },
+
+ getType: function() {
+ return this._type;
+ },
+
+ setType: function(type) {
+ this._components = this._convert(type);
+ this._properties = types[type];
+ this._type = type;
+ },
+
+ getComponents: function() {
+ var components = this._components.slice();
+ if (this._alpha != null)
+ components.push(this._alpha);
+ return components;
+ },
+
+ getAlpha: function() {
+ return this._alpha != null ? this._alpha : 1;
+ },
+
+ setAlpha: function(alpha) {
+ this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
+ this._changed();
+ },
+
+ hasAlpha: function() {
+ return this._alpha != null;
+ },
+
+ equals: function(color) {
+ var col = Base.isPlainValue(color, true)
+ ? Color.read(arguments)
+ : color;
+ return col === this || col && this._class === col._class
+ && this._type === col._type
+ && this._alpha === col._alpha
+ && Base.equals(this._components, col._components)
+ || false;
+ },
+
+ toString: function() {
+ var properties = this._properties,
+ parts = [],
+ isGradient = this._type === 'gradient',
+ f = Formatter.instance;
+ for (var i = 0, l = properties.length; i < l; i++) {
+ var value = this._components[i];
+ if (value != null)
+ parts.push(properties[i] + ': '
+ + (isGradient ? value : f.number(value)));
+ }
+ if (this._alpha != null)
+ parts.push('alpha: ' + f.number(this._alpha));
+ return '{ ' + parts.join(', ') + ' }';
+ },
+
+ toCSS: function(hex) {
+ var components = this._convert('rgb'),
+ alpha = hex || this._alpha == null ? 1 : this._alpha;
+ function convert(val) {
+ return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255);
+ }
+ components = [
+ convert(components[0]),
+ convert(components[1]),
+ convert(components[2])
+ ];
+ if (alpha < 1)
+ components.push(alpha < 0 ? 0 : alpha);
+ return hex
+ ? '#' + ((1 << 24) + (components[0] << 16)
+ + (components[1] << 8)
+ + components[2]).toString(16).slice(1)
+ : (components.length == 4 ? 'rgba(' : 'rgb(')
+ + components.join(',') + ')';
+ },
+
+ toCanvasStyle: function(ctx) {
+ if (this._canvasStyle)
+ return this._canvasStyle;
+ if (this._type !== 'gradient')
+ return this._canvasStyle = this.toCSS();
+ var components = this._components,
+ gradient = components[0],
+ stops = gradient._stops,
+ origin = components[1],
+ destination = components[2],
+ canvasGradient;
+ if (gradient._radial) {
+ var radius = destination.getDistance(origin),
+ highlight = components[3];
+ if (highlight) {
+ var vector = highlight.subtract(origin);
+ if (vector.getLength() > radius)
+ highlight = origin.add(vector.normalize(radius - 0.1));
+ }
+ var start = highlight || origin;
+ canvasGradient = ctx.createRadialGradient(start.x, start.y,
+ 0, origin.x, origin.y, radius);
+ } else {
+ canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
+ destination.x, destination.y);
+ }
+ for (var i = 0, l = stops.length; i < l; i++) {
+ var stop = stops[i];
+ canvasGradient.addColorStop(stop._rampPoint,
+ stop._color.toCanvasStyle());
+ }
+ return this._canvasStyle = canvasGradient;
+ },
+
+ transform: function(matrix) {
+ if (this._type === 'gradient') {
+ var components = this._components;
+ for (var i = 1, l = components.length; i < l; i++) {
+ var point = components[i];
+ matrix._transformPoint(point, point, true);
+ }
+ this._changed();
+ }
+ },
+
+ statics: {
+ _types: types,
+
+ random: function() {
+ var random = Math.random;
+ return new Color(random(), random(), random());
+ }
+ }
+ });
+}, new function() {
+ var operators = {
+ add: function(a, b) {
+ return a + b;
+ },
+
+ subtract: function(a, b) {
+ return a - b;
+ },
+
+ multiply: function(a, b) {
+ return a * b;
+ },
+
+ divide: function(a, b) {
+ return a / b;
+ }
+ };
+
+ return Base.each(operators, function(operator, name) {
+ this[name] = function(color) {
+ color = Color.read(arguments);
+ var type = this._type,
+ components1 = this._components,
+ components2 = color._convert(type);
+ for (var i = 0, l = components1.length; i < l; i++)
+ components2[i] = operator(components1[i], components2[i]);
+ return new Color(type, components2,
+ this._alpha != null
+ ? operator(this._alpha, color.getAlpha())
+ : null);
+ };
+ }, {
+ });
+});
+
+Base.each(Color._types, function(properties, type) {
+ var ctor = this[Base.capitalize(type) + 'Color'] = function(arg) {
+ var argType = arg != null && typeof arg,
+ components = argType === 'object' && arg.length != null
+ ? arg
+ : argType === 'string'
+ ? null
+ : arguments;
+ return components
+ ? new Color(type, components)
+ : new Color(arg);
+ };
+ if (type.length == 3) {
+ var acronym = type.toUpperCase();
+ Color[acronym] = this[acronym + 'Color'] = ctor;
+ }
+}, Base.exports);
+
+var Gradient = Base.extend({
+ _class: 'Gradient',
+
+ initialize: function Gradient(stops, radial) {
+ this._id = Gradient._id = (Gradient._id || 0) + 1;
+ if (stops && this._set(stops))
+ stops = radial = null;
+ if (!this._stops)
+ this.setStops(stops || ['white', 'black']);
+ if (this._radial == null)
+ this.setRadial(typeof radial === 'string' && radial === 'radial'
+ || radial || false);
+ },
+
+ _serialize: function(options, dictionary) {
+ return dictionary.add(this, function() {
+ return Base.serialize([this._stops, this._radial],
+ options, true, dictionary);
+ });
+ },
+
+ _changed: function() {
+ for (var i = 0, l = this._owners && this._owners.length; i < l; i++)
+ this._owners[i]._changed();
+ },
+
+ _addOwner: function(color) {
+ if (!this._owners)
+ this._owners = [];
+ this._owners.push(color);
+ },
+
+ _removeOwner: function(color) {
+ var index = this._owners ? this._owners.indexOf(color) : -1;
+ if (index != -1) {
+ this._owners.splice(index, 1);
+ if (this._owners.length === 0)
+ this._owners = undefined;
+ }
+ },
+
+ clone: function() {
+ var stops = [];
+ for (var i = 0, l = this._stops.length; i < l; i++)
+ stops[i] = this._stops[i].clone();
+ return new Gradient(stops);
+ },
+
+ getStops: function() {
+ return this._stops;
+ },
+
+ setStops: function(stops) {
+ if (this.stops) {
+ for (var i = 0, l = this._stops.length; i < l; i++)
+ this._stops[i]._owner = undefined;
+ }
+ if (stops.length < 2)
+ throw new Error(
+ 'Gradient stop list needs to contain at least two stops.');
+ this._stops = GradientStop.readAll(stops, 0, { clone: true });
+ for (var i = 0, l = this._stops.length; i < l; i++) {
+ var stop = this._stops[i];
+ stop._owner = this;
+ if (stop._defaultRamp)
+ stop.setRampPoint(i / (l - 1));
+ }
+ this._changed();
+ },
+
+ getRadial: function() {
+ return this._radial;
+ },
+
+ setRadial: function(radial) {
+ this._radial = radial;
+ this._changed();
+ },
+
+ equals: function(gradient) {
+ if (gradient === this)
+ return true;
+ if (gradient && this._class === gradient._class
+ && this._stops.length === gradient._stops.length) {
+ for (var i = 0, l = this._stops.length; i < l; i++) {
+ if (!this._stops[i].equals(gradient._stops[i]))
+ return false;
+ }
+ return true;
+ }
+ return false;
+ }
+});
+
+var GradientStop = Base.extend({
+ _class: 'GradientStop',
+
+ initialize: function GradientStop(arg0, arg1) {
+ if (arg0) {
+ var color, rampPoint;
+ if (arg1 === undefined && Array.isArray(arg0)) {
+ color = arg0[0];
+ rampPoint = arg0[1];
+ } else if (arg0.color) {
+ color = arg0.color;
+ rampPoint = arg0.rampPoint;
+ } else {
+ color = arg0;
+ rampPoint = arg1;
+ }
+ this.setColor(color);
+ this.setRampPoint(rampPoint);
+ }
+ },
+
+ clone: function() {
+ return new GradientStop(this._color.clone(), this._rampPoint);
+ },
+
+ _serialize: function(options, dictionary) {
+ return Base.serialize([this._color, this._rampPoint], options, true,
+ dictionary);
+ },
+
+ _changed: function() {
+ if (this._owner)
+ this._owner._changed(65);
+ },
+
+ getRampPoint: function() {
+ return this._rampPoint;
+ },
+
+ setRampPoint: function(rampPoint) {
+ this._defaultRamp = rampPoint == null;
+ this._rampPoint = rampPoint || 0;
+ this._changed();
+ },
+
+ getColor: function() {
+ return this._color;
+ },
+
+ setColor: function(color) {
+ this._color = Color.read(arguments);
+ if (this._color === color)
+ this._color = color.clone();
+ this._color._owner = this;
+ this._changed();
+ },
+
+ equals: function(stop) {
+ return stop === this || stop && this._class === stop._class
+ && this._color.equals(stop._color)
+ && this._rampPoint == stop._rampPoint
+ || false;
+ }
+});
+
+var Style = Base.extend(new function() {
+ var defaults = {
+ fillColor: undefined,
+ strokeColor: undefined,
+ strokeWidth: 1,
+ strokeCap: 'butt',
+ strokeJoin: 'miter',
+ strokeScaling: true,
+ miterLimit: 10,
+ dashOffset: 0,
+ dashArray: [],
+ windingRule: 'nonzero',
+ shadowColor: undefined,
+ shadowBlur: 0,
+ shadowOffset: new Point(),
+ selectedColor: undefined,
+ fontFamily: 'sans-serif',
+ fontWeight: 'normal',
+ fontSize: 12,
+ font: 'sans-serif',
+ leading: null,
+ justification: 'left'
+ };
+
+ var flags = {
+ strokeWidth: 97,
+ strokeCap: 97,
+ strokeJoin: 97,
+ strokeScaling: 105,
+ miterLimit: 97,
+ fontFamily: 9,
+ fontWeight: 9,
+ fontSize: 9,
+ font: 9,
+ leading: 9,
+ justification: 9
+ };
+
+ var item = { beans: true },
+ fields = {
+ _defaults: defaults,
+ _textDefaults: new Base(defaults, {
+ fillColor: new Color()
+ }),
+ beans: true
+ };
+
+ Base.each(defaults, function(value, key) {
+ var isColor = /Color$/.test(key),
+ isPoint = key === 'shadowOffset',
+ part = Base.capitalize(key),
+ flag = flags[key],
+ set = 'set' + part,
+ get = 'get' + part;
+
+ fields[set] = function(value) {
+ var owner = this._owner,
+ children = owner && owner._children;
+ if (children && children.length > 0
+ && !(owner instanceof CompoundPath)) {
+ for (var i = 0, l = children.length; i < l; i++)
+ children[i]._style[set](value);
+ } else {
+ var old = this._values[key];
+ if (old != value) {
+ if (isColor) {
+ if (old)
+ old._owner = undefined;
+ if (value && value.constructor === Color) {
+ if (value._owner)
+ value = value.clone();
+ value._owner = owner;
+ }
+ }
+ this._values[key] = value;
+ if (owner)
+ owner._changed(flag || 65);
+ }
+ }
+ };
+
+ fields[get] = function(_dontMerge) {
+ var owner = this._owner,
+ children = owner && owner._children,
+ value;
+ if (!children || children.length === 0 || _dontMerge
+ || owner instanceof CompoundPath) {
+ var value = this._values[key];
+ if (value === undefined) {
+ value = this._defaults[key];
+ if (value && value.clone)
+ value = value.clone();
+ this._values[key] = value;
+ } else {
+ var ctor = isColor ? Color : isPoint ? Point : null;
+ if (ctor && !(value && value.constructor === ctor)) {
+ this._values[key] = value = ctor.read([value], 0,
+ { readNull: true, clone: true });
+ if (value && isColor)
+ value._owner = owner;
+ }
+ }
+ return value;
+ }
+ for (var i = 0, l = children.length; i < l; i++) {
+ var childValue = children[i]._style[get]();
+ if (i === 0) {
+ value = childValue;
+ } else if (!Base.equals(value, childValue)) {
+ return undefined;
+ }
+ }
+ return value;
+ };
+
+ item[get] = function(_dontMerge) {
+ return this._style[get](_dontMerge);
+ };
+
+ item[set] = function(value) {
+ this._style[set](value);
+ };
+ });
+
+ Item.inject(item);
+ return fields;
+}, {
+ _class: 'Style',
+
+ initialize: function Style(style, _owner, _project) {
+ this._values = {};
+ this._owner = _owner;
+ this._project = _owner && _owner._project || _project || paper.project;
+ if (_owner instanceof TextItem)
+ this._defaults = this._textDefaults;
+ if (style)
+ this.set(style);
+ },
+
+ set: function(style) {
+ var isStyle = style instanceof Style,
+ values = isStyle ? style._values : style;
+ if (values) {
+ for (var key in values) {
+ if (key in this._defaults) {
+ var value = values[key];
+ this[key] = value && isStyle && value.clone
+ ? value.clone() : value;
+ }
+ }
+ }
+ },
+
+ equals: function(style) {
+ return style === this || style && this._class === style._class
+ && Base.equals(this._values, style._values)
+ || false;
+ },
+
+ hasFill: function() {
+ return !!this.getFillColor();
+ },
+
+ hasStroke: function() {
+ return !!this.getStrokeColor() && this.getStrokeWidth() > 0;
+ },
+
+ hasShadow: function() {
+ return !!this.getShadowColor() && this.getShadowBlur() > 0;
+ },
+
+ getView: function() {
+ return this._project.getView();
+ },
+
+ getFontStyle: function() {
+ var fontSize = this.getFontSize();
+ return this.getFontWeight()
+ + ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ')
+ + this.getFontFamily();
+ },
+
+ getFont: '#getFontFamily',
+ setFont: '#setFontFamily',
+
+ getLeading: function getLeading() {
+ var leading = getLeading.base.call(this),
+ fontSize = this.getFontSize();
+ if (/pt|em|%|px/.test(fontSize))
+ fontSize = this.getView().getPixelSize(fontSize);
+ return leading != null ? leading : fontSize * 1.2;
+ }
+
+});
+
+var DomElement = new function() {
+ function handlePrefix(el, name, set, value) {
+ var prefixes = ['', 'webkit', 'moz', 'Moz', 'ms', 'o'],
+ suffix = name[0].toUpperCase() + name.substring(1);
+ for (var i = 0; i < 6; i++) {
+ var prefix = prefixes[i],
+ key = prefix ? prefix + suffix : name;
+ if (key in el) {
+ if (set) {
+ el[key] = value;
+ } else {
+ return el[key];
+ }
+ break;
+ }
+ }
+ }
+
+ return {
+ getStyles: function(el) {
+ var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
+ view = doc && doc.defaultView;
+ return view && view.getComputedStyle(el, '');
+ },
+
+ getBounds: function(el, viewport) {
+ var doc = el.ownerDocument,
+ body = doc.body,
+ html = doc.documentElement,
+ rect;
+ try {
+ rect = el.getBoundingClientRect();
+ } catch (e) {
+ rect = { left: 0, top: 0, width: 0, height: 0 };
+ }
+ var x = rect.left - (html.clientLeft || body.clientLeft || 0),
+ y = rect.top - (html.clientTop || body.clientTop || 0);
+ if (!viewport) {
+ var view = doc.defaultView;
+ x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
+ y += view.pageYOffset || html.scrollTop || body.scrollTop;
+ }
+ return new Rectangle(x, y, rect.width, rect.height);
+ },
+
+ getViewportBounds: function(el) {
+ var doc = el.ownerDocument,
+ view = doc.defaultView,
+ html = doc.documentElement;
+ return new Rectangle(0, 0,
+ view.innerWidth || html.clientWidth,
+ view.innerHeight || html.clientHeight
+ );
+ },
+
+ getOffset: function(el, viewport) {
+ return DomElement.getBounds(el, viewport).getPoint();
+ },
+
+ getSize: function(el) {
+ return DomElement.getBounds(el, true).getSize();
+ },
+
+ isInvisible: function(el) {
+ return DomElement.getSize(el).equals(new Size(0, 0));
+ },
+
+ isInView: function(el) {
+ return !DomElement.isInvisible(el)
+ && DomElement.getViewportBounds(el).intersects(
+ DomElement.getBounds(el, true));
+ },
+
+ getPrefixed: function(el, name) {
+ return handlePrefix(el, name);
+ },
+
+ setPrefixed: function(el, name, value) {
+ if (typeof name === 'object') {
+ for (var key in name)
+ handlePrefix(el, key, true, name[key]);
+ } else {
+ handlePrefix(el, name, true, value);
+ }
+ }
+ };
+};
+
+var DomEvent = {
+ add: function(el, events) {
+ for (var type in events) {
+ var func = events[type],
+ parts = type.split(/[\s,]+/g);
+ for (var i = 0, l = parts.length; i < l; i++)
+ el.addEventListener(parts[i], func, false);
+ }
+ },
+
+ remove: function(el, events) {
+ for (var type in events) {
+ var func = events[type],
+ parts = type.split(/[\s,]+/g);
+ for (var i = 0, l = parts.length; i < l; i++)
+ el.removeEventListener(parts[i], func, false);
+ }
+ },
+
+ getPoint: function(event) {
+ var pos = event.targetTouches
+ ? event.targetTouches.length
+ ? event.targetTouches[0]
+ : event.changedTouches[0]
+ : event;
+ return new Point(
+ pos.pageX || pos.clientX + document.documentElement.scrollLeft,
+ pos.pageY || pos.clientY + document.documentElement.scrollTop
+ );
+ },
+
+ getTarget: function(event) {
+ return event.target || event.srcElement;
+ },
+
+ getRelatedTarget: function(event) {
+ return event.relatedTarget || event.toElement;
+ },
+
+ getOffset: function(event, target) {
+ return DomEvent.getPoint(event).subtract(DomElement.getOffset(
+ target || DomEvent.getTarget(event)));
+ },
+
+ stop: function(event) {
+ event.stopPropagation();
+ event.preventDefault();
+ }
+};
+
+DomEvent.requestAnimationFrame = new function() {
+ var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'),
+ requested = false,
+ callbacks = [],
+ focused = true,
+ timer;
+
+ DomEvent.add(window, {
+ focus: function() {
+ focused = true;
+ },
+ blur: function() {
+ focused = false;
+ }
+ });
+
+ function handleCallbacks() {
+ for (var i = callbacks.length - 1; i >= 0; i--) {
+ var entry = callbacks[i],
+ func = entry[0],
+ el = entry[1];
+ if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true'
+ || focused) && DomElement.isInView(el)) {
+ callbacks.splice(i, 1);
+ func();
+ }
+ }
+ if (nativeRequest) {
+ if (callbacks.length) {
+ nativeRequest(handleCallbacks);
+ } else {
+ requested = false;
+ }
+ }
+ }
+
+ return function(callback, element) {
+ callbacks.push([callback, element]);
+ if (nativeRequest) {
+ if (!requested) {
+ nativeRequest(handleCallbacks);
+ requested = true;
+ }
+ } else if (!timer) {
+ timer = setInterval(handleCallbacks, 1000 / 60);
+ }
+ };
+};
+
+var View = Base.extend(Emitter, {
+ _class: 'View',
+
+ initialize: function View(project, element) {
+ this._project = project;
+ this._scope = project._scope;
+ this._element = element;
+ var size;
+ if (!this._pixelRatio)
+ this._pixelRatio = window.devicePixelRatio || 1;
+ this._id = element.getAttribute('id');
+ if (this._id == null)
+ element.setAttribute('id', this._id = 'view-' + View._id++);
+ DomEvent.add(element, this._viewEvents);
+ var none = 'none';
+ DomElement.setPrefixed(element.style, {
+ userSelect: none,
+ touchAction: none,
+ touchCallout: none,
+ contentZooming: none,
+ userDrag: none,
+ tapHighlightColor: 'rgba(0,0,0,0)'
+ });
+ if (PaperScope.hasAttribute(element, 'resize')) {
+ var offset = DomElement.getOffset(element, true),
+ that = this;
+ size = DomElement.getViewportBounds(element)
+ .getSize().subtract(offset);
+ this._windowEvents = {
+ resize: function() {
+ if (!DomElement.isInvisible(element))
+ offset = DomElement.getOffset(element, true);
+ that.setViewSize(DomElement.getViewportBounds(element)
+ .getSize().subtract(offset));
+ }
+ };
+ DomEvent.add(window, this._windowEvents);
+ } else {
+ size = DomElement.getSize(element);
+ if (size.isNaN() || size.isZero()) {
+ var getSize = function(name) {
+ return element[name]
+ || parseInt(element.getAttribute(name), 10);
+ };
+ size = new Size(getSize('width'), getSize('height'));
+ }
+ }
+ this._setViewSize(size);
+ if (PaperScope.hasAttribute(element, 'stats')
+ && typeof Stats !== 'undefined') {
+ this._stats = new Stats();
+ var stats = this._stats.domElement,
+ style = stats.style,
+ offset = DomElement.getOffset(element);
+ style.position = 'absolute';
+ style.left = offset.x + 'px';
+ style.top = offset.y + 'px';
+ document.body.appendChild(stats);
+ }
+ View._views.push(this);
+ View._viewsById[this._id] = this;
+ this._viewSize = size;
+ (this._matrix = new Matrix())._owner = this;
+ this._zoom = 1;
+ if (!View._focused)
+ View._focused = this;
+ this._frameItems = {};
+ this._frameItemCount = 0;
+ },
+
+ remove: function() {
+ if (!this._project)
+ return false;
+ if (View._focused === this)
+ View._focused = null;
+ View._views.splice(View._views.indexOf(this), 1);
+ delete View._viewsById[this._id];
+ if (this._project._view === this)
+ this._project._view = null;
+ DomEvent.remove(this._element, this._viewEvents);
+ DomEvent.remove(window, this._windowEvents);
+ this._element = this._project = null;
+ this.off('frame');
+ this._animate = false;
+ this._frameItems = {};
+ return true;
+ },
+
+ _events: {
+ onFrame: {
+ install: function() {
+ this.play();
+ },
+
+ uninstall: function() {
+ this.pause();
+ }
+ },
+
+ onResize: {}
+ },
+
+ _animate: false,
+ _time: 0,
+ _count: 0,
+
+ _requestFrame: function() {
+ var that = this;
+ DomEvent.requestAnimationFrame(function() {
+ that._requested = false;
+ if (!that._animate)
+ return;
+ that._requestFrame();
+ that._handleFrame();
+ }, this._element);
+ this._requested = true;
+ },
+
+ _handleFrame: function() {
+ paper = this._scope;
+ var now = Date.now() / 1000,
+ delta = this._before ? now - this._before : 0;
+ this._before = now;
+ this._handlingFrame = true;
+ this.emit('frame', new Base({
+ delta: delta,
+ time: this._time += delta,
+ count: this._count++
+ }));
+ if (this._stats)
+ this._stats.update();
+ this._handlingFrame = false;
+ this.update();
+ },
+
+ _animateItem: function(item, animate) {
+ var items = this._frameItems;
+ if (animate) {
+ items[item._id] = {
+ item: item,
+ time: 0,
+ count: 0
+ };
+ if (++this._frameItemCount === 1)
+ this.on('frame', this._handleFrameItems);
+ } else {
+ delete items[item._id];
+ if (--this._frameItemCount === 0) {
+ this.off('frame', this._handleFrameItems);
+ }
+ }
+ },
+
+ _handleFrameItems: function(event) {
+ for (var i in this._frameItems) {
+ var entry = this._frameItems[i];
+ entry.item.emit('frame', new Base(event, {
+ time: entry.time += event.delta,
+ count: entry.count++
+ }));
+ }
+ },
+
+ _update: function() {
+ this._project._needsUpdate = true;
+ if (this._handlingFrame)
+ return;
+ if (this._animate) {
+ this._handleFrame();
+ } else {
+ this.update();
+ }
+ },
+
+ _changed: function(flags) {
+ if (flags & 1)
+ this._project._needsUpdate = true;
+ },
+
+ _transform: function(matrix) {
+ this._matrix.concatenate(matrix);
+ this._bounds = null;
+ this._update();
+ },
+
+ getElement: function() {
+ return this._element;
+ },
+
+ getPixelRatio: function() {
+ return this._pixelRatio;
+ },
+
+ getResolution: function() {
+ return this._pixelRatio * 72;
+ },
+
+ getViewSize: function() {
+ var size = this._viewSize;
+ return new LinkedSize(size.width, size.height, this, 'setViewSize');
+ },
+
+ setViewSize: function() {
+ var size = Size.read(arguments),
+ delta = size.subtract(this._viewSize);
+ if (delta.isZero())
+ return;
+ this._viewSize.set(size.width, size.height);
+ this._setViewSize(size);
+ this._bounds = null;
+ this.emit('resize', {
+ size: size,
+ delta: delta
+ });
+ this._update();
+ },
+
+ _setViewSize: function(size) {
+ var element = this._element;
+ element.width = size.width;
+ element.height = size.height;
+ },
+
+ getBounds: function() {
+ if (!this._bounds)
+ this._bounds = this._matrix.inverted()._transformBounds(
+ new Rectangle(new Point(), this._viewSize));
+ return this._bounds;
+ },
+
+ getSize: function() {
+ return this.getBounds().getSize();
+ },
+
+ getCenter: function() {
+ return this.getBounds().getCenter();
+ },
+
+ setCenter: function() {
+ var center = Point.read(arguments);
+ this.scrollBy(center.subtract(this.getCenter()));
+ },
+
+ getZoom: function() {
+ return this._zoom;
+ },
+
+ setZoom: function(zoom) {
+ this._transform(new Matrix().scale(zoom / this._zoom,
+ this.getCenter()));
+ this._zoom = zoom;
+ },
+
+ isVisible: function() {
+ return DomElement.isInView(this._element);
+ },
+
+ scrollBy: function() {
+ this._transform(new Matrix().translate(Point.read(arguments).negate()));
+ },
+
+ play: function() {
+ this._animate = true;
+ if (!this._requested)
+ this._requestFrame();
+ },
+
+ pause: function() {
+ this._animate = false;
+ },
+
+ draw: function() {
+ this.update();
+ },
+
+ projectToView: function() {
+ return this._matrix._transformPoint(Point.read(arguments));
+ },
+
+ viewToProject: function() {
+ return this._matrix._inverseTransform(Point.read(arguments));
+ }
+
+}, {
+ statics: {
+ _views: [],
+ _viewsById: {},
+ _id: 0,
+
+ create: function(project, element) {
+ if (typeof element === 'string')
+ element = document.getElementById(element);
+ return new CanvasView(project, element);
+ }
+ }
+}, new function() {
+ var tool,
+ prevFocus,
+ tempFocus,
+ dragging = false;
+
+ function getView(event) {
+ var target = DomEvent.getTarget(event);
+ return target.getAttribute && View._viewsById[target.getAttribute('id')];
+ }
+
+ function viewToProject(view, event) {
+ return view.viewToProject(DomEvent.getOffset(event, view._element));
+ }
+
+ function updateFocus() {
+ if (!View._focused || !View._focused.isVisible()) {
+ for (var i = 0, l = View._views.length; i < l; i++) {
+ var view = View._views[i];
+ if (view && view.isVisible()) {
+ View._focused = tempFocus = view;
+ break;
+ }
+ }
+ }
+ }
+
+ function handleMouseMove(view, point, event) {
+ view._handleEvent('mousemove', point, event);
+ var tool = view._scope.tool;
+ if (tool) {
+ tool._handleEvent(dragging && tool.responds('mousedrag')
+ ? 'mousedrag' : 'mousemove', point, event);
+ }
+ view.update();
+ return tool;
+ }
+
+ var navigator = window.navigator,
+ mousedown, mousemove, mouseup;
+ if (navigator.pointerEnabled || navigator.msPointerEnabled) {
+ mousedown = 'pointerdown MSPointerDown';
+ mousemove = 'pointermove MSPointerMove';
+ mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel';
+ } else {
+ mousedown = 'touchstart';
+ mousemove = 'touchmove';
+ mouseup = 'touchend touchcancel';
+ if (!('ontouchstart' in window && navigator.userAgent.match(
+ /mobile|tablet|ip(ad|hone|od)|android|silk/i))) {
+ mousedown += ' mousedown';
+ mousemove += ' mousemove';
+ mouseup += ' mouseup';
+ }
+ }
+
+ var viewEvents = {
+ 'selectstart dragstart': function(event) {
+ if (dragging)
+ event.preventDefault();
+ }
+ };
+
+ var docEvents = {
+ mouseout: function(event) {
+ var view = View._focused,
+ target = DomEvent.getRelatedTarget(event);
+ if (view && (!target || target.nodeName === 'HTML'))
+ handleMouseMove(view, viewToProject(view, event), event);
+ },
+
+ scroll: updateFocus
+ };
+
+ viewEvents[mousedown] = function(event) {
+ var view = View._focused = getView(event),
+ point = viewToProject(view, event);
+ dragging = true;
+ view._handleEvent('mousedown', point, event);
+ if (tool = view._scope.tool)
+ tool._handleEvent('mousedown', point, event);
+ view.update();
+ };
+
+ docEvents[mousemove] = function(event) {
+ var view = View._focused;
+ if (!dragging) {
+ var target = getView(event);
+ if (target) {
+ if (view !== target)
+ handleMouseMove(view, viewToProject(view, event), event);
+ prevFocus = view;
+ view = View._focused = tempFocus = target;
+ } else if (tempFocus && tempFocus === view) {
+ view = View._focused = prevFocus;
+ updateFocus();
+ }
+ }
+ if (view) {
+ var point = viewToProject(view, event);
+ if (dragging || view.getBounds().contains(point))
+ tool = handleMouseMove(view, point, event);
+ }
+ };
+
+ docEvents[mouseup] = function(event) {
+ var view = View._focused;
+ if (!view || !dragging)
+ return;
+ var point = viewToProject(view, event);
+ dragging = false;
+ view._handleEvent('mouseup', point, event);
+ if (tool)
+ tool._handleEvent('mouseup', point, event);
+ view.update();
+ };
+
+ DomEvent.add(document, docEvents);
+
+ DomEvent.add(window, {
+ load: updateFocus
+ });
+
+ return {
+ _viewEvents: viewEvents,
+
+ _handleEvent: function() {},
+
+ statics: {
+ updateFocus: updateFocus
+ }
+ };
+});
+
+var CanvasView = View.extend({
+ _class: 'CanvasView',
+
+ initialize: function CanvasView(project, canvas) {
+ if (!(canvas instanceof HTMLCanvasElement)) {
+ var size = Size.read(arguments);
+ if (size.isZero())
+ throw new Error(
+ 'Cannot create CanvasView with the provided argument: '
+ + [].slice.call(arguments, 1));
+ canvas = CanvasProvider.getCanvas(size);
+ }
+ this._context = canvas.getContext('2d');
+ this._eventCounters = {};
+ this._pixelRatio = 1;
+ if (!/^off|false$/.test(PaperScope.getAttribute(canvas, 'hidpi'))) {
+ var deviceRatio = window.devicePixelRatio || 1,
+ backingStoreRatio = DomElement.getPrefixed(this._context,
+ 'backingStorePixelRatio') || 1;
+ this._pixelRatio = deviceRatio / backingStoreRatio;
+ }
+ View.call(this, project, canvas);
+ },
+
+ _setViewSize: function(size) {
+ var width = size.width,
+ height = size.height,
+ pixelRatio = this._pixelRatio,
+ element = this._element,
+ style = element.style;
+ element.width = width * pixelRatio;
+ element.height = height * pixelRatio;
+ if (pixelRatio !== 1) {
+ style.width = width + 'px';
+ style.height = height + 'px';
+ this._context.scale(pixelRatio, pixelRatio);
+ }
+ },
+
+ getPixelSize: function(size) {
+ var ctx = this._context,
+ prevFont = ctx.font;
+ ctx.font = size + ' serif';
+ size = parseFloat(ctx.font);
+ ctx.font = prevFont;
+ return size;
+ },
+
+ getTextWidth: function(font, lines) {
+ var ctx = this._context,
+ prevFont = ctx.font,
+ width = 0;
+ ctx.font = font;
+ for (var i = 0, l = lines.length; i < l; i++)
+ width = Math.max(width, ctx.measureText(lines[i]).width);
+ ctx.font = prevFont;
+ return width;
+ },
+
+ update: function() {
+ var project = this._project;
+ if (!project || !project._needsUpdate)
+ return false;
+ var ctx = this._context,
+ size = this._viewSize;
+ ctx.clearRect(0, 0, size.width + 1, size.height + 1);
+ project.draw(ctx, this._matrix, this._pixelRatio);
+ project._needsUpdate = false;
+ return true;
+ }
+}, new function() {
+
+ var downPoint,
+ lastPoint,
+ overPoint,
+ downItem,
+ lastItem,
+ overItem,
+ dragItem,
+ dblClick,
+ clickTime;
+
+ function callEvent(view, type, event, point, target, lastPoint) {
+ var item = target,
+ mouseEvent;
+
+ function call(obj) {
+ if (obj.responds(type)) {
+ if (!mouseEvent) {
+ mouseEvent = new MouseEvent(type, event, point, target,
+ lastPoint ? point.subtract(lastPoint) : null);
+ }
+ if (obj.emit(type, mouseEvent) && mouseEvent.isStopped) {
+ event.preventDefault();
+ return true;
+ }
+ }
+ }
+
+ while (item) {
+ if (call(item))
+ return true;
+ item = item.getParent();
+ }
+ if (call(view))
+ return true;
+ return false;
+ }
+
+ return {
+ _handleEvent: function(type, point, event) {
+ if (!this._eventCounters[type])
+ return;
+ var project = this._project,
+ hit = project.hitTest(point, {
+ tolerance: 0,
+ fill: true,
+ stroke: true
+ }),
+ item = hit && hit.item,
+ stopped = false;
+ switch (type) {
+ case 'mousedown':
+ stopped = callEvent(this, type, event, point, item);
+ dblClick = lastItem == item && (Date.now() - clickTime < 300);
+ downItem = lastItem = item;
+ downPoint = lastPoint = overPoint = point;
+ dragItem = !stopped && item;
+ while (dragItem && !dragItem.responds('mousedrag'))
+ dragItem = dragItem._parent;
+ break;
+ case 'mouseup':
+ stopped = callEvent(this, type, event, point, item, downPoint);
+ if (dragItem) {
+ if (lastPoint && !lastPoint.equals(point))
+ callEvent(this, 'mousedrag', event, point, dragItem,
+ lastPoint);
+ if (item !== dragItem) {
+ overPoint = point;
+ callEvent(this, 'mousemove', event, point, item,
+ overPoint);
+ }
+ }
+ if (!stopped && item && item === downItem) {
+ clickTime = Date.now();
+ callEvent(this, dblClick && downItem.responds('doubleclick')
+ ? 'doubleclick' : 'click', event, downPoint, item);
+ dblClick = false;
+ }
+ downItem = dragItem = null;
+ break;
+ case 'mousemove':
+ if (dragItem)
+ stopped = callEvent(this, 'mousedrag', event, point,
+ dragItem, lastPoint);
+ if (!stopped) {
+ if (item !== overItem)
+ overPoint = point;
+ stopped = callEvent(this, type, event, point, item,
+ overPoint);
+ }
+ lastPoint = overPoint = point;
+ if (item !== overItem) {
+ callEvent(this, 'mouseleave', event, point, overItem);
+ overItem = item;
+ callEvent(this, 'mouseenter', event, point, item);
+ }
+ break;
+ }
+ return stopped;
+ }
+ };
+});
+
+var Event = Base.extend({
+ _class: 'Event',
+
+ initialize: function Event(event) {
+ this.event = event;
+ },
+
+ isPrevented: false,
+ isStopped: false,
+
+ preventDefault: function() {
+ this.isPrevented = true;
+ this.event.preventDefault();
+ },
+
+ stopPropagation: function() {
+ this.isStopped = true;
+ this.event.stopPropagation();
+ },
+
+ stop: function() {
+ this.stopPropagation();
+ this.preventDefault();
+ },
+
+ getModifiers: function() {
+ return Key.modifiers;
+ }
+});
+
+var KeyEvent = Event.extend({
+ _class: 'KeyEvent',
+
+ initialize: function KeyEvent(down, key, character, event) {
+ Event.call(this, event);
+ this.type = down ? 'keydown' : 'keyup';
+ this.key = key;
+ this.character = character;
+ },
+
+ toString: function() {
+ return "{ type: '" + this.type
+ + "', key: '" + this.key
+ + "', character: '" + this.character
+ + "', modifiers: " + this.getModifiers()
+ + " }";
+ }
+});
+
+var Key = new function() {
+
+ var specialKeys = {
+ 8: 'backspace',
+ 9: 'tab',
+ 13: 'enter',
+ 16: 'shift',
+ 17: 'control',
+ 18: 'option',
+ 19: 'pause',
+ 20: 'caps-lock',
+ 27: 'escape',
+ 32: 'space',
+ 35: 'end',
+ 36: 'home',
+ 37: 'left',
+ 38: 'up',
+ 39: 'right',
+ 40: 'down',
+ 46: 'delete',
+ 91: 'command',
+ 93: 'command',
+ 224: 'command'
+ },
+
+ specialChars = {
+ 9: true,
+ 13: true,
+ 32: true
+ },
+
+ modifiers = new Base({
+ shift: false,
+ control: false,
+ option: false,
+ command: false,
+ capsLock: false,
+ space: false
+ }),
+
+ charCodeMap = {},
+ keyMap = {},
+ downCode;
+
+ function handleKey(down, keyCode, charCode, event) {
+ var character = charCode ? String.fromCharCode(charCode) : '',
+ specialKey = specialKeys[keyCode],
+ key = specialKey || character.toLowerCase(),
+ type = down ? 'keydown' : 'keyup',
+ view = View._focused,
+ scope = view && view.isVisible() && view._scope,
+ tool = scope && scope.tool,
+ name;
+ keyMap[key] = down;
+ if (specialKey && (name = Base.camelize(specialKey)) in modifiers)
+ modifiers[name] = down;
+ if (down) {
+ charCodeMap[keyCode] = charCode;
+ } else {
+ delete charCodeMap[keyCode];
+ }
+ if (tool && tool.responds(type)) {
+ paper = scope;
+ tool.emit(type, new KeyEvent(down, key, character, event));
+ if (view)
+ view.update();
+ }
+ }
+
+ DomEvent.add(document, {
+ keydown: function(event) {
+ var code = event.which || event.keyCode;
+ if (code in specialKeys || modifiers.command) {
+ handleKey(true, code,
+ code in specialChars || modifiers.command ? code : 0,
+ event);
+ } else {
+ downCode = code;
+ }
+ },
+
+ keypress: function(event) {
+ if (downCode != null) {
+ handleKey(true, downCode, event.which || event.keyCode, event);
+ downCode = null;
+ }
+ },
+
+ keyup: function(event) {
+ var code = event.which || event.keyCode;
+ if (code in charCodeMap)
+ handleKey(false, code, charCodeMap[code], event);
+ }
+ });
+
+ DomEvent.add(window, {
+ blur: function(event) {
+ for (var code in charCodeMap)
+ handleKey(false, code, charCodeMap[code], event);
+ }
+ });
+
+ return {
+ modifiers: modifiers,
+
+ isDown: function(key) {
+ return !!keyMap[key];
+ }
+ };
+};
+
+var MouseEvent = Event.extend({
+ _class: 'MouseEvent',
+
+ initialize: function MouseEvent(type, event, point, target, delta) {
+ Event.call(this, event);
+ this.type = type;
+ this.point = point;
+ this.target = target;
+ this.delta = delta;
+ },
+
+ toString: function() {
+ return "{ type: '" + this.type
+ + "', point: " + this.point
+ + ', target: ' + this.target
+ + (this.delta ? ', delta: ' + this.delta : '')
+ + ', modifiers: ' + this.getModifiers()
+ + ' }';
+ }
+});
+
+var ToolEvent = Event.extend({
+ _class: 'ToolEvent',
+ _item: null,
+
+ initialize: function ToolEvent(tool, type, event) {
+ this.tool = tool;
+ this.type = type;
+ this.event = event;
+ },
+
+ _choosePoint: function(point, toolPoint) {
+ return point ? point : toolPoint ? toolPoint.clone() : null;
+ },
+
+ getPoint: function() {
+ return this._choosePoint(this._point, this.tool._point);
+ },
+
+ setPoint: function(point) {
+ this._point = point;
+ },
+
+ getLastPoint: function() {
+ return this._choosePoint(this._lastPoint, this.tool._lastPoint);
+ },
+
+ setLastPoint: function(lastPoint) {
+ this._lastPoint = lastPoint;
+ },
+
+ getDownPoint: function() {
+ return this._choosePoint(this._downPoint, this.tool._downPoint);
+ },
+
+ setDownPoint: function(downPoint) {
+ this._downPoint = downPoint;
+ },
+
+ getMiddlePoint: function() {
+ if (!this._middlePoint && this.tool._lastPoint) {
+ return this.tool._point.add(this.tool._lastPoint).divide(2);
+ }
+ return this._middlePoint;
+ },
+
+ setMiddlePoint: function(middlePoint) {
+ this._middlePoint = middlePoint;
+ },
+
+ getDelta: function() {
+ return !this._delta && this.tool._lastPoint
+ ? this.tool._point.subtract(this.tool._lastPoint)
+ : this._delta;
+ },
+
+ setDelta: function(delta) {
+ this._delta = delta;
+ },
+
+ getCount: function() {
+ return /^mouse(down|up)$/.test(this.type)
+ ? this.tool._downCount
+ : this.tool._count;
+ },
+
+ setCount: function(count) {
+ this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
+ = count;
+ },
+
+ getItem: function() {
+ if (!this._item) {
+ var result = this.tool._scope.project.hitTest(this.getPoint());
+ if (result) {
+ var item = result.item,
+ parent = item._parent;
+ while (/^(Group|CompoundPath)$/.test(parent._class)) {
+ item = parent;
+ parent = parent._parent;
+ }
+ this._item = item;
+ }
+ }
+ return this._item;
+ },
+
+ setItem: function(item) {
+ this._item = item;
+ },
+
+ toString: function() {
+ return '{ type: ' + this.type
+ + ', point: ' + this.getPoint()
+ + ', count: ' + this.getCount()
+ + ', modifiers: ' + this.getModifiers()
+ + ' }';
+ }
+});
+
+var Tool = PaperScopeItem.extend({
+ _class: 'Tool',
+ _list: 'tools',
+ _reference: 'tool',
+ _events: [ 'onActivate', 'onDeactivate', 'onEditOptions',
+ 'onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
+ 'onKeyDown', 'onKeyUp' ],
+
+ initialize: function Tool(props) {
+ PaperScopeItem.call(this);
+ this._firstMove = true;
+ this._count = 0;
+ this._downCount = 0;
+ this._set(props);
+ },
+
+ getMinDistance: function() {
+ return this._minDistance;
+ },
+
+ setMinDistance: function(minDistance) {
+ this._minDistance = minDistance;
+ if (this._minDistance != null && this._maxDistance != null
+ && this._minDistance > this._maxDistance) {
+ this._maxDistance = this._minDistance;
+ }
+ },
+
+ getMaxDistance: function() {
+ return this._maxDistance;
+ },
+
+ setMaxDistance: function(maxDistance) {
+ this._maxDistance = maxDistance;
+ if (this._minDistance != null && this._maxDistance != null
+ && this._maxDistance < this._minDistance) {
+ this._minDistance = maxDistance;
+ }
+ },
+
+ getFixedDistance: function() {
+ return this._minDistance == this._maxDistance
+ ? this._minDistance : null;
+ },
+
+ setFixedDistance: function(distance) {
+ this._minDistance = distance;
+ this._maxDistance = distance;
+ },
+
+ _updateEvent: function(type, point, minDistance, maxDistance, start,
+ needsChange, matchMaxDistance) {
+ if (!start) {
+ if (minDistance != null || maxDistance != null) {
+ var minDist = minDistance != null ? minDistance : 0,
+ vector = point.subtract(this._point),
+ distance = vector.getLength();
+ if (distance < minDist)
+ return false;
+ var maxDist = maxDistance != null ? maxDistance : 0;
+ if (maxDist != 0) {
+ if (distance > maxDist) {
+ point = this._point.add(vector.normalize(maxDist));
+ } else if (matchMaxDistance) {
+ return false;
+ }
+ }
+ }
+ if (needsChange && point.equals(this._point))
+ return false;
+ }
+ this._lastPoint = start && type == 'mousemove' ? point : this._point;
+ this._point = point;
+ switch (type) {
+ case 'mousedown':
+ this._lastPoint = this._downPoint;
+ this._downPoint = this._point;
+ this._downCount++;
+ break;
+ case 'mouseup':
+ this._lastPoint = this._downPoint;
+ break;
+ }
+ this._count = start ? 0 : this._count + 1;
+ return true;
+ },
+
+ _fireEvent: function(type, event) {
+ var sets = paper.project._removeSets;
+ if (sets) {
+ if (type === 'mouseup')
+ sets.mousedrag = null;
+ var set = sets[type];
+ if (set) {
+ for (var id in set) {
+ var item = set[id];
+ for (var key in sets) {
+ var other = sets[key];
+ if (other && other != set)
+ delete other[item._id];
+ }
+ item.remove();
+ }
+ sets[type] = null;
+ }
+ }
+ return this.responds(type)
+ && this.emit(type, new ToolEvent(this, type, event));
+ },
+
+ _handleEvent: function(type, point, event) {
+ paper = this._scope;
+ var called = false;
+ switch (type) {
+ case 'mousedown':
+ this._updateEvent(type, point, null, null, true, false, false);
+ called = this._fireEvent(type, event);
+ break;
+ case 'mousedrag':
+ var needsChange = false,
+ matchMaxDistance = false;
+ while (this._updateEvent(type, point, this.minDistance,
+ this.maxDistance, false, needsChange, matchMaxDistance)) {
+ called = this._fireEvent(type, event) || called;
+ needsChange = true;
+ matchMaxDistance = true;
+ }
+ break;
+ case 'mouseup':
+ if (!point.equals(this._point)
+ && this._updateEvent('mousedrag', point, this.minDistance,
+ this.maxDistance, false, false, false)) {
+ called = this._fireEvent('mousedrag', event);
+ }
+ this._updateEvent(type, point, null, this.maxDistance, false,
+ false, false);
+ called = this._fireEvent(type, event) || called;
+ this._updateEvent(type, point, null, null, true, false, false);
+ this._firstMove = true;
+ break;
+ case 'mousemove':
+ while (this._updateEvent(type, point, this.minDistance,
+ this.maxDistance, this._firstMove, true, false)) {
+ called = this._fireEvent(type, event) || called;
+ this._firstMove = false;
+ }
+ break;
+ }
+ if (called)
+ event.preventDefault();
+ return called;
+ }
+
+});
+
+var Http = {
+ request: function(method, url, callback) {
+ var xhr = new (window.ActiveXObject || XMLHttpRequest)(
+ 'Microsoft.XMLHTTP');
+ xhr.open(method.toUpperCase(), url, true);
+ if ('overrideMimeType' in xhr)
+ xhr.overrideMimeType('text/plain');
+ xhr.onreadystatechange = function() {
+ if (xhr.readyState === 4) {
+ var status = xhr.status;
+ if (status === 0 || status === 200) {
+ callback.call(xhr, xhr.responseText);
+ } else {
+ throw new Error('Could not load ' + url + ' (Error '
+ + status + ')');
+ }
+ }
+ };
+ return xhr.send(null);
+ }
+};
+
+var CanvasProvider = {
+ canvases: [],
+
+ getCanvas: function(width, height) {
+ var canvas,
+ clear = true;
+ if (typeof width === 'object') {
+ height = width.height;
+ width = width.width;
+ }
+ if (this.canvases.length) {
+ canvas = this.canvases.pop();
+ } else {
+ canvas = document.createElement('canvas');
+ }
+ var ctx = canvas.getContext('2d');
+ if (canvas.width === width && canvas.height === height) {
+ if (clear)
+ ctx.clearRect(0, 0, width + 1, height + 1);
+ } else {
+ canvas.width = width;
+ canvas.height = height;
+ }
+ ctx.save();
+ return canvas;
+ },
+
+ getContext: function(width, height) {
+ return this.getCanvas(width, height).getContext('2d');
+ },
+
+ release: function(obj) {
+ var canvas = obj.canvas ? obj.canvas : obj;
+ canvas.getContext('2d').restore();
+ this.canvases.push(canvas);
+ }
+};
+
+var BlendMode = new function() {
+ var min = Math.min,
+ max = Math.max,
+ abs = Math.abs,
+ sr, sg, sb, sa,
+ br, bg, bb, ba,
+ dr, dg, db;
+
+ function getLum(r, g, b) {
+ return 0.2989 * r + 0.587 * g + 0.114 * b;
+ }
+
+ function setLum(r, g, b, l) {
+ var d = l - getLum(r, g, b);
+ dr = r + d;
+ dg = g + d;
+ db = b + d;
+ var l = getLum(dr, dg, db),
+ mn = min(dr, dg, db),
+ mx = max(dr, dg, db);
+ if (mn < 0) {
+ var lmn = l - mn;
+ dr = l + (dr - l) * l / lmn;
+ dg = l + (dg - l) * l / lmn;
+ db = l + (db - l) * l / lmn;
+ }
+ if (mx > 255) {
+ var ln = 255 - l,
+ mxl = mx - l;
+ dr = l + (dr - l) * ln / mxl;
+ dg = l + (dg - l) * ln / mxl;
+ db = l + (db - l) * ln / mxl;
+ }
+ }
+
+ function getSat(r, g, b) {
+ return max(r, g, b) - min(r, g, b);
+ }
+
+ function setSat(r, g, b, s) {
+ var col = [r, g, b],
+ mx = max(r, g, b),
+ mn = min(r, g, b),
+ md;
+ mn = mn === r ? 0 : mn === g ? 1 : 2;
+ mx = mx === r ? 0 : mx === g ? 1 : 2;
+ md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
+ if (col[mx] > col[mn]) {
+ col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
+ col[mx] = s;
+ } else {
+ col[md] = col[mx] = 0;
+ }
+ col[mn] = 0;
+ dr = col[0];
+ dg = col[1];
+ db = col[2];
+ }
+
+ var modes = {
+ multiply: function() {
+ dr = br * sr / 255;
+ dg = bg * sg / 255;
+ db = bb * sb / 255;
+ },
+
+ screen: function() {
+ dr = br + sr - (br * sr / 255);
+ dg = bg + sg - (bg * sg / 255);
+ db = bb + sb - (bb * sb / 255);
+ },
+
+ overlay: function() {
+ dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
+ dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
+ db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
+ },
+
+ 'soft-light': function() {
+ var t = sr * br / 255;
+ dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
+ t = sg * bg / 255;
+ dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
+ t = sb * bb / 255;
+ db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
+ },
+
+ 'hard-light': function() {
+ dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
+ dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
+ db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
+ },
+
+ 'color-dodge': function() {
+ dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
+ dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
+ db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
+ },
+
+ 'color-burn': function() {
+ dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
+ dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
+ db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
+ },
+
+ darken: function() {
+ dr = br < sr ? br : sr;
+ dg = bg < sg ? bg : sg;
+ db = bb < sb ? bb : sb;
+ },
+
+ lighten: function() {
+ dr = br > sr ? br : sr;
+ dg = bg > sg ? bg : sg;
+ db = bb > sb ? bb : sb;
+ },
+
+ difference: function() {
+ dr = br - sr;
+ if (dr < 0)
+ dr = -dr;
+ dg = bg - sg;
+ if (dg < 0)
+ dg = -dg;
+ db = bb - sb;
+ if (db < 0)
+ db = -db;
+ },
+
+ exclusion: function() {
+ dr = br + sr * (255 - br - br) / 255;
+ dg = bg + sg * (255 - bg - bg) / 255;
+ db = bb + sb * (255 - bb - bb) / 255;
+ },
+
+ hue: function() {
+ setSat(sr, sg, sb, getSat(br, bg, bb));
+ setLum(dr, dg, db, getLum(br, bg, bb));
+ },
+
+ saturation: function() {
+ setSat(br, bg, bb, getSat(sr, sg, sb));
+ setLum(dr, dg, db, getLum(br, bg, bb));
+ },
+
+ luminosity: function() {
+ setLum(br, bg, bb, getLum(sr, sg, sb));
+ },
+
+ color: function() {
+ setLum(sr, sg, sb, getLum(br, bg, bb));
+ },
+
+ add: function() {
+ dr = min(br + sr, 255);
+ dg = min(bg + sg, 255);
+ db = min(bb + sb, 255);
+ },
+
+ subtract: function() {
+ dr = max(br - sr, 0);
+ dg = max(bg - sg, 0);
+ db = max(bb - sb, 0);
+ },
+
+ average: function() {
+ dr = (br + sr) / 2;
+ dg = (bg + sg) / 2;
+ db = (bb + sb) / 2;
+ },
+
+ negation: function() {
+ dr = 255 - abs(255 - sr - br);
+ dg = 255 - abs(255 - sg - bg);
+ db = 255 - abs(255 - sb - bb);
+ }
+ };
+
+ var nativeModes = this.nativeModes = Base.each([
+ 'source-over', 'source-in', 'source-out', 'source-atop',
+ 'destination-over', 'destination-in', 'destination-out',
+ 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
+ ], function(mode) {
+ this[mode] = true;
+ }, {});
+
+ var ctx = CanvasProvider.getContext(1, 1);
+ Base.each(modes, function(func, mode) {
+ var darken = mode === 'darken',
+ ok = false;
+ ctx.save();
+ try {
+ ctx.fillStyle = darken ? '#300' : '#a00';
+ ctx.fillRect(0, 0, 1, 1);
+ ctx.globalCompositeOperation = mode;
+ if (ctx.globalCompositeOperation === mode) {
+ ctx.fillStyle = darken ? '#a00' : '#300';
+ ctx.fillRect(0, 0, 1, 1);
+ ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken ? 170 : 51;
+ }
+ } catch (e) {}
+ ctx.restore();
+ nativeModes[mode] = ok;
+ });
+ CanvasProvider.release(ctx);
+
+ this.process = function(mode, srcContext, dstContext, alpha, offset) {
+ var srcCanvas = srcContext.canvas,
+ normal = mode === 'normal';
+ if (normal || nativeModes[mode]) {
+ dstContext.save();
+ dstContext.setTransform(1, 0, 0, 1, 0, 0);
+ dstContext.globalAlpha = alpha;
+ if (!normal)
+ dstContext.globalCompositeOperation = mode;
+ dstContext.drawImage(srcCanvas, offset.x, offset.y);
+ dstContext.restore();
+ } else {
+ var process = modes[mode];
+ if (!process)
+ return;
+ var dstData = dstContext.getImageData(offset.x, offset.y,
+ srcCanvas.width, srcCanvas.height),
+ dst = dstData.data,
+ src = srcContext.getImageData(0, 0,
+ srcCanvas.width, srcCanvas.height).data;
+ for (var i = 0, l = dst.length; i < l; i += 4) {
+ sr = src[i];
+ br = dst[i];
+ sg = src[i + 1];
+ bg = dst[i + 1];
+ sb = src[i + 2];
+ bb = dst[i + 2];
+ sa = src[i + 3];
+ ba = dst[i + 3];
+ process();
+ var a1 = sa * alpha / 255,
+ a2 = 1 - a1;
+ dst[i] = a1 * dr + a2 * br;
+ dst[i + 1] = a1 * dg + a2 * bg;
+ dst[i + 2] = a1 * db + a2 * bb;
+ dst[i + 3] = sa * alpha + a2 * ba;
+ }
+ dstContext.putImageData(dstData, offset.x, offset.y);
+ }
+ };
+};
+
+var SVGStyles = Base.each({
+ fillColor: ['fill', 'color'],
+ strokeColor: ['stroke', 'color'],
+ strokeWidth: ['stroke-width', 'number'],
+ strokeCap: ['stroke-linecap', 'string'],
+ strokeJoin: ['stroke-linejoin', 'string'],
+ strokeScaling: ['vector-effect', 'lookup', {
+ true: 'none',
+ false: 'non-scaling-stroke'
+ }, function(item, value) {
+ return !value
+ && (item instanceof PathItem
+ || item instanceof Shape
+ || item instanceof TextItem);
+ }],
+ miterLimit: ['stroke-miterlimit', 'number'],
+ dashArray: ['stroke-dasharray', 'array'],
+ dashOffset: ['stroke-dashoffset', 'number'],
+ fontFamily: ['font-family', 'string'],
+ fontWeight: ['font-weight', 'string'],
+ fontSize: ['font-size', 'number'],
+ justification: ['text-anchor', 'lookup', {
+ left: 'start',
+ center: 'middle',
+ right: 'end'
+ }],
+ opacity: ['opacity', 'number'],
+ blendMode: ['mix-blend-mode', 'string']
+}, function(entry, key) {
+ var part = Base.capitalize(key),
+ lookup = entry[2];
+ this[key] = {
+ type: entry[1],
+ property: key,
+ attribute: entry[0],
+ toSVG: lookup,
+ fromSVG: lookup && Base.each(lookup, function(value, name) {
+ this[value] = name;
+ }, {}),
+ exportFilter: entry[3],
+ get: 'get' + part,
+ set: 'set' + part
+ };
+}, {});
+
+var SVGNamespaces = {
+ href: 'http://www.w3.org/1999/xlink',
+ xlink: 'http://www.w3.org/2000/xmlns'
+};
+
+new function() {
+ var formatter;
+
+ function setAttributes(node, attrs) {
+ for (var key in attrs) {
+ var val = attrs[key],
+ namespace = SVGNamespaces[key];
+ if (typeof val === 'number')
+ val = formatter.number(val);
+ if (namespace) {
+ node.setAttributeNS(namespace, key, val);
+ } else {
+ node.setAttribute(key, val);
+ }
+ }
+ return node;
+ }
+
+ function createElement(tag, attrs) {
+ return setAttributes(
+ document.createElementNS('http://www.w3.org/2000/svg', tag), attrs);
+ }
+
+ function getTransform(matrix, coordinates, center) {
+ var attrs = new Base(),
+ trans = matrix.getTranslation();
+ if (coordinates) {
+ matrix = matrix.shiftless();
+ var point = matrix._inverseTransform(trans);
+ attrs[center ? 'cx' : 'x'] = point.x;
+ attrs[center ? 'cy' : 'y'] = point.y;
+ trans = null;
+ }
+ if (!matrix.isIdentity()) {
+ var decomposed = matrix.decompose();
+ if (decomposed && !decomposed.shearing) {
+ var parts = [],
+ angle = decomposed.rotation,
+ scale = decomposed.scaling;
+ if (trans && !trans.isZero())
+ parts.push('translate(' + formatter.point(trans) + ')');
+ if (angle)
+ parts.push('rotate(' + formatter.number(angle) + ')');
+ if (!Numerical.isZero(scale.x - 1)
+ || !Numerical.isZero(scale.y - 1))
+ parts.push('scale(' + formatter.point(scale) +')');
+ attrs.transform = parts.join(' ');
+ } else {
+ attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
+ }
+ }
+ return attrs;
+ }
+
+ function exportGroup(item, options) {
+ var attrs = getTransform(item._matrix),
+ children = item._children;
+ var node = createElement('g', attrs);
+ for (var i = 0, l = children.length; i < l; i++) {
+ var child = children[i];
+ var childNode = exportSVG(child, options);
+ if (childNode) {
+ if (child.isClipMask()) {
+ var clip = createElement('clipPath');
+ clip.appendChild(childNode);
+ setDefinition(child, clip, 'clip');
+ setAttributes(node, {
+ 'clip-path': 'url(#' + clip.id + ')'
+ });
+ } else {
+ node.appendChild(childNode);
+ }
+ }
+ }
+ return node;
+ }
+
+ function exportRaster(item) {
+ var attrs = getTransform(item._matrix, true),
+ size = item.getSize();
+ attrs.x -= size.width / 2;
+ attrs.y -= size.height / 2;
+ attrs.width = size.width;
+ attrs.height = size.height;
+ attrs.href = item.toDataURL();
+ return createElement('image', attrs);
+ }
+
+ function exportPath(item, options) {
+ if (options.matchShapes) {
+ var shape = item.toShape(false);
+ if (shape)
+ return exportShape(shape, options);
+ }
+ var segments = item._segments,
+ type,
+ attrs = getTransform(item._matrix);
+ if (segments.length === 0)
+ return null;
+ if (item.isPolygon()) {
+ if (segments.length >= 3) {
+ type = item._closed ? 'polygon' : 'polyline';
+ var parts = [];
+ for(i = 0, l = segments.length; i < l; i++)
+ parts.push(formatter.point(segments[i]._point));
+ attrs.points = parts.join(' ');
+ } else {
+ type = 'line';
+ var first = segments[0]._point,
+ last = segments[segments.length - 1]._point;
+ attrs.set({
+ x1: first.x,
+ y1: first.y,
+ x2: last.x,
+ y2: last.y
+ });
+ }
+ } else {
+ type = 'path';
+ attrs.d = item.getPathData(null, options.precision);
+ }
+ return createElement(type, attrs);
+ }
+
+ function exportShape(item) {
+ var type = item._type,
+ radius = item._radius,
+ attrs = getTransform(item._matrix, true, type !== 'rectangle');
+ if (type === 'rectangle') {
+ type = 'rect';
+ var size = item._size,
+ width = size.width,
+ height = size.height;
+ attrs.x -= width / 2;
+ attrs.y -= height / 2;
+ attrs.width = width;
+ attrs.height = height;
+ if (radius.isZero())
+ radius = null;
+ }
+ if (radius) {
+ if (type === 'circle') {
+ attrs.r = radius;
+ } else {
+ attrs.rx = radius.width;
+ attrs.ry = radius.height;
+ }
+ }
+ return createElement(type, attrs);
+ }
+
+ function exportCompoundPath(item, options) {
+ var attrs = getTransform(item._matrix);
+ var data = item.getPathData(null, options.precision);
+ if (data)
+ attrs.d = data;
+ return createElement('path', attrs);
+ }
+
+ function exportPlacedSymbol(item, options) {
+ var attrs = getTransform(item._matrix, true),
+ symbol = item.getSymbol(),
+ symbolNode = getDefinition(symbol, 'symbol'),
+ definition = symbol.getDefinition(),
+ bounds = definition.getBounds();
+ if (!symbolNode) {
+ symbolNode = createElement('symbol', {
+ viewBox: formatter.rectangle(bounds)
+ });
+ symbolNode.appendChild(exportSVG(definition, options));
+ setDefinition(symbol, symbolNode, 'symbol');
+ }
+ attrs.href = '#' + symbolNode.id;
+ attrs.x += bounds.x;
+ attrs.y += bounds.y;
+ attrs.width = formatter.number(bounds.width);
+ attrs.height = formatter.number(bounds.height);
+ return createElement('use', attrs);
+ }
+
+ function exportGradient(color) {
+ var gradientNode = getDefinition(color, 'color');
+ if (!gradientNode) {
+ var gradient = color.getGradient(),
+ radial = gradient._radial,
+ origin = color.getOrigin().transform(),
+ destination = color.getDestination().transform(),
+ attrs;
+ if (radial) {
+ attrs = {
+ cx: origin.x,
+ cy: origin.y,
+ r: origin.getDistance(destination)
+ };
+ var highlight = color.getHighlight();
+ if (highlight) {
+ highlight = highlight.transform();
+ attrs.fx = highlight.x;
+ attrs.fy = highlight.y;
+ }
+ } else {
+ attrs = {
+ x1: origin.x,
+ y1: origin.y,
+ x2: destination.x,
+ y2: destination.y
+ };
+ }
+ attrs.gradientUnits = 'userSpaceOnUse';
+ gradientNode = createElement(
+ (radial ? 'radial' : 'linear') + 'Gradient', attrs);
+ var stops = gradient._stops;
+ for (var i = 0, l = stops.length; i < l; i++) {
+ var stop = stops[i],
+ stopColor = stop._color,
+ alpha = stopColor.getAlpha();
+ attrs = {
+ offset: stop._rampPoint,
+ 'stop-color': stopColor.toCSS(true)
+ };
+ if (alpha < 1)
+ attrs['stop-opacity'] = alpha;
+ gradientNode.appendChild(createElement('stop', attrs));
+ }
+ setDefinition(color, gradientNode, 'color');
+ }
+ return 'url(#' + gradientNode.id + ')';
+ }
+
+ function exportText(item) {
+ var node = createElement('text', getTransform(item._matrix, true));
+ node.textContent = item._content;
+ return node;
+ }
+
+ var exporters = {
+ Group: exportGroup,
+ Layer: exportGroup,
+ Raster: exportRaster,
+ Path: exportPath,
+ Shape: exportShape,
+ CompoundPath: exportCompoundPath,
+ PlacedSymbol: exportPlacedSymbol,
+ PointText: exportText
+ };
+
+ function applyStyle(item, node, isRoot) {
+ var attrs = {},
+ parent = !isRoot && item.getParent();
+
+ if (item._name != null)
+ attrs.id = item._name;
+
+ Base.each(SVGStyles, function(entry) {
+ var get = entry.get,
+ type = entry.type,
+ value = item[get]();
+ if (entry.exportFilter
+ ? entry.exportFilter(item, value)
+ : !parent || !Base.equals(parent[get](), value)) {
+ if (type === 'color' && value != null) {
+ var alpha = value.getAlpha();
+ if (alpha < 1)
+ attrs[entry.attribute + '-opacity'] = alpha;
+ }
+ attrs[entry.attribute] = value == null
+ ? 'none'
+ : type === 'number'
+ ? formatter.number(value)
+ : type === 'color'
+ ? value.gradient
+ ? exportGradient(value, item)
+ : value.toCSS(true)
+ : type === 'array'
+ ? value.join(',')
+ : type === 'lookup'
+ ? entry.toSVG[value]
+ : value;
+ }
+ });
+
+ if (attrs.opacity === 1)
+ delete attrs.opacity;
+
+ if (!item._visible)
+ attrs.visibility = 'hidden';
+
+ return setAttributes(node, attrs);
+ }
+
+ var definitions;
+ function getDefinition(item, type) {
+ if (!definitions)
+ definitions = { ids: {}, svgs: {} };
+ return item && definitions.svgs[type + '-' + item._id];
+ }
+
+ function setDefinition(item, node, type) {
+ if (!definitions)
+ getDefinition();
+ var id = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
+ node.id = type + '-' + id;
+ definitions.svgs[type + '-' + item._id] = node;
+ }
+
+ function exportDefinitions(node, options) {
+ var svg = node,
+ defs = null;
+ if (definitions) {
+ svg = node.nodeName.toLowerCase() === 'svg' && node;
+ for (var i in definitions.svgs) {
+ if (!defs) {
+ if (!svg) {
+ svg = createElement('svg');
+ svg.appendChild(node);
+ }
+ defs = svg.insertBefore(createElement('defs'),
+ svg.firstChild);
+ }
+ defs.appendChild(definitions.svgs[i]);
+ }
+ definitions = null;
+ }
+ return options.asString
+ ? new XMLSerializer().serializeToString(svg)
+ : svg;
+ }
+
+ function exportSVG(item, options, isRoot) {
+ var exporter = exporters[item._class],
+ node = exporter && exporter(item, options);
+ if (node) {
+ var onExport = options.onExport;
+ if (onExport)
+ node = onExport(item, node, options) || node;
+ var data = JSON.stringify(item._data);
+ if (data && data !== '{}')
+ node.setAttribute('data-paper-data', data);
+ }
+ return node && applyStyle(item, node, isRoot);
+ }
+
+ function setOptions(options) {
+ if (!options)
+ options = {};
+ formatter = new Formatter(options.precision);
+ return options;
+ }
+
+ Item.inject({
+ exportSVG: function(options) {
+ options = setOptions(options);
+ return exportDefinitions(exportSVG(this, options, true), options);
+ }
+ });
+
+ Project.inject({
+ exportSVG: function(options) {
+ options = setOptions(options);
+ var layers = this.layers,
+ view = this.getView(),
+ size = view.getViewSize(),
+ node = createElement('svg', {
+ x: 0,
+ y: 0,
+ width: size.width,
+ height: size.height,
+ version: '1.1',
+ xmlns: 'http://www.w3.org/2000/svg',
+ 'xmlns:xlink': 'http://www.w3.org/1999/xlink'
+ }),
+ parent = node,
+ matrix = view._matrix;
+ if (!matrix.isIdentity())
+ parent = node.appendChild(
+ createElement('g', getTransform(matrix)));
+ for (var i = 0, l = layers.length; i < l; i++)
+ parent.appendChild(exportSVG(layers[i], options, true));
+ return exportDefinitions(node, options);
+ }
+ });
+};
+
+new function() {
+
+ function getValue(node, name, isString, allowNull) {
+ var namespace = SVGNamespaces[name],
+ value = namespace
+ ? node.getAttributeNS(namespace, name)
+ : node.getAttribute(name);
+ if (value === 'null')
+ value = null;
+ return value == null
+ ? allowNull
+ ? null
+ : isString
+ ? ''
+ : 0
+ : isString
+ ? value
+ : parseFloat(value);
+ }
+
+ function getPoint(node, x, y, allowNull) {
+ x = getValue(node, x, false, allowNull);
+ y = getValue(node, y, false, allowNull);
+ return allowNull && (x == null || y == null) ? null
+ : new Point(x, y);
+ }
+
+ function getSize(node, w, h, allowNull) {
+ w = getValue(node, w, false, allowNull);
+ h = getValue(node, h, false, allowNull);
+ return allowNull && (w == null || h == null) ? null
+ : new Size(w, h);
+ }
+
+ function convertValue(value, type, lookup) {
+ return value === 'none'
+ ? null
+ : type === 'number'
+ ? parseFloat(value)
+ : type === 'array'
+ ? value ? value.split(/[\s,]+/g).map(parseFloat) : []
+ : type === 'color'
+ ? getDefinition(value) || value
+ : type === 'lookup'
+ ? lookup[value]
+ : value;
+ }
+
+ function importGroup(node, type, options, isRoot) {
+ var nodes = node.childNodes,
+ isClip = type === 'clippath',
+ item = new Group(),
+ project = item._project,
+ currentStyle = project._currentStyle,
+ children = [];
+ if (!isClip) {
+ item = applyAttributes(item, node, isRoot);
+ project._currentStyle = item._style.clone();
+ }
+ for (var i = 0, l = nodes.length; i < l; i++) {
+ var childNode = nodes[i],
+ child;
+ if (childNode.nodeType === 1
+ && (child = importSVG(childNode, options, false))
+ && !(child instanceof Symbol))
+ children.push(child);
+ }
+ item.addChildren(children);
+ if (isClip)
+ item = applyAttributes(item.reduce(), node, isRoot);
+ project._currentStyle = currentStyle;
+ if (isClip || type === 'defs') {
+ item.remove();
+ item = null;
+ }
+ return item;
+ }
+
+ function importPoly(node, type) {
+ var coords = node.getAttribute('points').match(
+ /[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g),
+ points = [];
+ for (var i = 0, l = coords.length; i < l; i += 2)
+ points.push(new Point(
+ parseFloat(coords[i]),
+ parseFloat(coords[i + 1])));
+ var path = new Path(points);
+ if (type === 'polygon')
+ path.closePath();
+ return path;
+ }
+
+ function importPath(node) {
+ var data = node.getAttribute('d'),
+ param = { pathData: data };
+ return (data.match(/m/gi) || []).length > 1 || /z\S+/i.test(data)
+ ? new CompoundPath(param)
+ : new Path(param);
+ }
+
+ function importGradient(node, type) {
+ var id = (getValue(node, 'href', true) || '').substring(1),
+ isRadial = type === 'radialgradient',
+ gradient;
+ if (id) {
+ gradient = definitions[id].getGradient();
+ } else {
+ var nodes = node.childNodes,
+ stops = [];
+ for (var i = 0, l = nodes.length; i < l; i++) {
+ var child = nodes[i];
+ if (child.nodeType === 1)
+ stops.push(applyAttributes(new GradientStop(), child));
+ }
+ gradient = new Gradient(stops, isRadial);
+ }
+ var origin, destination, highlight;
+ if (isRadial) {
+ origin = getPoint(node, 'cx', 'cy');
+ destination = origin.add(getValue(node, 'r'), 0);
+ highlight = getPoint(node, 'fx', 'fy', true);
+ } else {
+ origin = getPoint(node, 'x1', 'y1');
+ destination = getPoint(node, 'x2', 'y2');
+ }
+ applyAttributes(
+ new Color(gradient, origin, destination, highlight), node);
+ return null;
+ }
+
+ var importers = {
+ '#document': function (node, type, options, isRoot) {
+ var nodes = node.childNodes;
+ for (var i = 0, l = nodes.length; i < l; i++) {
+ var child = nodes[i];
+ if (child.nodeType === 1) {
+ var next = child.nextSibling;
+ document.body.appendChild(child);
+ var item = importSVG(child, options, isRoot);
+ if (next) {
+ node.insertBefore(child, next);
+ } else {
+ node.appendChild(child);
+ }
+ return item;
+ }
+ }
+ },
+ g: importGroup,
+ svg: importGroup,
+ clippath: importGroup,
+ polygon: importPoly,
+ polyline: importPoly,
+ path: importPath,
+ lineargradient: importGradient,
+ radialgradient: importGradient,
+
+ image: function (node) {
+ var raster = new Raster(getValue(node, 'href', true));
+ raster.on('load', function() {
+ var size = getSize(node, 'width', 'height');
+ this.setSize(size);
+ var center = this._matrix._transformPoint(
+ getPoint(node, 'x', 'y').add(size.divide(2)));
+ this.translate(center);
+ });
+ return raster;
+ },
+
+ symbol: function(node, type, options, isRoot) {
+ return new Symbol(importGroup(node, type, options, isRoot), true);
+ },
+
+ defs: importGroup,
+
+ use: function(node) {
+ var id = (getValue(node, 'href', true) || '').substring(1),
+ definition = definitions[id],
+ point = getPoint(node, 'x', 'y');
+ return definition
+ ? definition instanceof Symbol
+ ? definition.place(point)
+ : definition.clone().translate(point)
+ : null;
+ },
+
+ circle: function(node) {
+ return new Shape.Circle(getPoint(node, 'cx', 'cy'),
+ getValue(node, 'r'));
+ },
+
+ ellipse: function(node) {
+ return new Shape.Ellipse({
+ center: getPoint(node, 'cx', 'cy'),
+ radius: getSize(node, 'rx', 'ry')
+ });
+ },
+
+ rect: function(node) {
+ var point = getPoint(node, 'x', 'y'),
+ size = getSize(node, 'width', 'height'),
+ radius = getSize(node, 'rx', 'ry');
+ return new Shape.Rectangle(new Rectangle(point, size), radius);
+ },
+
+ line: function(node) {
+ return new Path.Line(getPoint(node, 'x1', 'y1'),
+ getPoint(node, 'x2', 'y2'));
+ },
+
+ text: function(node) {
+ var text = new PointText(getPoint(node, 'x', 'y')
+ .add(getPoint(node, 'dx', 'dy')));
+ text.setContent(node.textContent.trim() || '');
+ return text;
+ }
+ };
+
+ function applyTransform(item, value, name, node) {
+ var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
+ matrix = new Matrix();
+ for (var i = 0, l = transforms.length; i < l; i++) {
+ var transform = transforms[i];
+ if (!transform)
+ break;
+ var parts = transform.split(/\(\s*/),
+ command = parts[0],
+ v = parts[1].split(/[\s,]+/g);
+ for (var j = 0, m = v.length; j < m; j++)
+ v[j] = parseFloat(v[j]);
+ switch (command) {
+ case 'matrix':
+ matrix.concatenate(
+ new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
+ break;
+ case 'rotate':
+ matrix.rotate(v[0], v[1], v[2]);
+ break;
+ case 'translate':
+ matrix.translate(v[0], v[1]);
+ break;
+ case 'scale':
+ matrix.scale(v);
+ break;
+ case 'skewX':
+ matrix.skew(v[0], 0);
+ break;
+ case 'skewY':
+ matrix.skew(0, v[0]);
+ break;
+ }
+ }
+ item.transform(matrix);
+ }
+
+ function applyOpacity(item, value, name) {
+ var color = item[name === 'fill-opacity' ? 'getFillColor'
+ : 'getStrokeColor']();
+ if (color)
+ color.setAlpha(parseFloat(value));
+ }
+
+ var attributes = Base.each(SVGStyles, function(entry) {
+ this[entry.attribute] = function(item, value) {
+ item[entry.set](convertValue(value, entry.type, entry.fromSVG));
+ if (entry.type === 'color' && item instanceof Shape) {
+ var color = item[entry.get]();
+ if (color)
+ color.transform(new Matrix().translate(
+ item.getPosition(true).negate()));
+ }
+ };
+ }, {
+ id: function(item, value) {
+ definitions[value] = item;
+ if (item.setName)
+ item.setName(value);
+ },
+
+ 'clip-path': function(item, value) {
+ var clip = getDefinition(value);
+ if (clip) {
+ clip = clip.clone();
+ clip.setClipMask(true);
+ if (item instanceof Group) {
+ item.insertChild(0, clip);
+ } else {
+ return new Group(clip, item);
+ }
+ }
+ },
+
+ gradientTransform: applyTransform,
+ transform: applyTransform,
+
+ 'fill-opacity': applyOpacity,
+ 'stroke-opacity': applyOpacity,
+
+ visibility: function(item, value) {
+ item.setVisible(value === 'visible');
+ },
+
+ display: function(item, value) {
+ item.setVisible(value !== null);
+ },
+
+ 'stop-color': function(item, value) {
+ if (item.setColor)
+ item.setColor(value);
+ },
+
+ 'stop-opacity': function(item, value) {
+ if (item._color)
+ item._color.setAlpha(parseFloat(value));
+ },
+
+ offset: function(item, value) {
+ var percentage = value.match(/(.*)%$/);
+ item.setRampPoint(percentage
+ ? percentage[1] / 100
+ : parseFloat(value));
+ },
+
+ viewBox: function(item, value, name, node, styles) {
+ var rect = new Rectangle(convertValue(value, 'array')),
+ size = getSize(node, 'width', 'height', true);
+ if (item instanceof Group) {
+ var scale = size ? rect.getSize().divide(size) : 1,
+ matrix = new Matrix().translate(rect.getPoint()).scale(scale);
+ item.transform(matrix.inverted());
+ } else if (item instanceof Symbol) {
+ if (size)
+ rect.setSize(size);
+ var clip = getAttribute(node, 'overflow', styles) != 'visible',
+ group = item._definition;
+ if (clip && !rect.contains(group.getBounds())) {
+ clip = new Shape.Rectangle(rect).transform(group._matrix);
+ clip.setClipMask(true);
+ group.addChild(clip);
+ }
+ }
+ }
+ });
+
+ function getAttribute(node, name, styles) {
+ var attr = node.attributes[name],
+ value = attr && attr.value;
+ if (!value) {
+ var style = Base.camelize(name);
+ value = node.style[style];
+ if (!value && styles.node[style] !== styles.parent[style])
+ value = styles.node[style];
+ }
+ return !value
+ ? undefined
+ : value === 'none'
+ ? null
+ : value;
+ }
+
+ function applyAttributes(item, node, isRoot) {
+ var styles = {
+ node: DomElement.getStyles(node) || {},
+ parent: !isRoot && DomElement.getStyles(node.parentNode) || {}
+ };
+ Base.each(attributes, function(apply, name) {
+ var value = getAttribute(node, name, styles);
+ if (value !== undefined)
+ item = Base.pick(apply(item, value, name, node, styles), item);
+ });
+ return item;
+ }
+
+ var definitions = {};
+ function getDefinition(value) {
+ var match = value && value.match(/\((?:#|)([^)']+)/);
+ return match && definitions[match[1]];
+ }
+
+ function importSVG(source, options, isRoot) {
+ if (!source)
+ return null;
+ if (!options) {
+ options = {};
+ } else if (typeof options === 'function') {
+ options = { onLoad: options };
+ }
+
+ var node = source,
+ scope = paper;
+
+ function onLoadCallback(svg) {
+ paper = scope;
+ var item = importSVG(svg, options, isRoot),
+ onLoad = options.onLoad,
+ view = scope.project && scope.getView();
+ if (onLoad)
+ onLoad.call(this, item);
+ view.update();
+ }
+
+ if (isRoot) {
+ if (typeof source === 'string' && !/^.*</.test(source)) {
+ node = document.getElementById(source);
+ if (node) {
+ source = null;
+ } else {
+ return Http.request('get', source, onLoadCallback);
+ }
+ } else if (typeof File !== 'undefined' && source instanceof File) {
+ var reader = new FileReader();
+ reader.onload = function() {
+ onLoadCallback(reader.result);
+ };
+ return reader.readAsText(source);
+ }
+ }
+
+ if (typeof source === 'string')
+ node = new DOMParser().parseFromString(source, 'image/svg+xml');
+ if (!node.nodeName)
+ throw new Error('Unsupported SVG source: ' + source);
+ var type = node.nodeName.toLowerCase(),
+ importer = importers[type],
+ item,
+ data = node.getAttribute && node.getAttribute('data-paper-data'),
+ settings = scope.settings,
+ prevApplyMatrix = settings.applyMatrix;
+ settings.applyMatrix = false;
+ item = importer && importer(node, type, options, isRoot) || null;
+ settings.applyMatrix = prevApplyMatrix;
+ if (item) {
+ if (type !== '#document' && !(item instanceof Group))
+ item = applyAttributes(item, node, isRoot);
+ var onImport = options.onImport;
+ if (onImport)
+ item = onImport(node, item, options) || item;
+ if (options.expandShapes && item instanceof Shape) {
+ item.remove();
+ item = item.toPath();
+ }
+ if (data)
+ item._data = JSON.parse(data);
+ }
+ if (isRoot)
+ definitions = {};
+ return item;
+ }
+
+ Item.inject({
+ importSVG: function(node, options) {
+ return this.addChild(importSVG(node, options, true));
+ }
+ });
+
+ Project.inject({
+ importSVG: function(node, options) {
+ this.activate();
+ return importSVG(node, options, true);
+ }
+ });
+};
+
+Base.exports.PaperScript = (function() {
+ var exports, define,
+ scope = this;
+!function(e,r){return"object"==typeof exports&&"object"==typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):(r(e.acorn||(e.acorn={})),void 0)}(this,function(e){"use strict";function r(e){fr=e||{};for(var r in mr)Object.prototype.hasOwnProperty.call(fr,r)||(fr[r]=mr[r]);hr=fr.sourceFile||null}function t(e,r){var t=vr(dr,e);r+=" ("+t.line+":"+t.column+")";var n=new SyntaxError(r);throw n.pos=e,n.loc=t,n.raisedAt=br,n}function n(e){function r(e){if(1==e.length)return t+="return str === "+JSON.stringify(e[0])+";";t+="switch(str){";for(var r=0;r<e.length;++r)t+="case "+JSON.stringify(e[r])+":";t+="return true}return false;"}e=e.split(" ");var t="",n=[];e:for(var a=0;a<e.length;++a){for(var o=0;o<n.length;++o)if(n[o][0].length==e[a].length){n[o].push(e[a]);continue e}n.push([e[a]])}if(n.length>3){n.sort(function(e,r){return r.length-e.length}),t+="switch(str.length){";for(var a=0;a<n.length;++a){var i=n[a];t+="case "+i[0].length+":",r(i)}t+="}"}else r(e);return new Function("str",t)}function a(){this.line=Ar,this.column=br-Sr}function o(){Ar=1,br=Sr=0,Er=!0,u()}function i(e,r){gr=br,fr.locations&&(kr=new a),wr=e,u(),Cr=r,Er=e.beforeExpr}function s(){var e=fr.onComment&&fr.locations&&new a,r=br,n=dr.indexOf("*/",br+=2);if(-1===n&&t(br-2,"Unterminated comment"),br=n+2,fr.locations){Kt.lastIndex=r;for(var o;(o=Kt.exec(dr))&&o.index<br;)++Ar,Sr=o.index+o[0].length}fr.onComment&&fr.onComment(!0,dr.slice(r+2,n),r,br,e,fr.locations&&new a)}function c(){for(var e=br,r=fr.onComment&&fr.locations&&new a,t=dr.charCodeAt(br+=2);pr>br&&10!==t&&13!==t&&8232!==t&&8233!==t;)++br,t=dr.charCodeAt(br);fr.onComment&&fr.onComment(!1,dr.slice(e+2,br),e,br,r,fr.locations&&new a)}function u(){for(;pr>br;){var e=dr.charCodeAt(br);if(32===e)++br;else if(13===e){++br;var r=dr.charCodeAt(br);10===r&&++br,fr.locations&&(++Ar,Sr=br)}else if(10===e||8232===e||8233===e)++br,fr.locations&&(++Ar,Sr=br);else if(e>8&&14>e)++br;else if(47===e){var r=dr.charCodeAt(br+1);if(42===r)s();else{if(47!==r)break;c()}}else if(160===e)++br;else{if(!(e>=5760&&Jt.test(String.fromCharCode(e))))break;++br}}}function l(){var e=dr.charCodeAt(br+1);return e>=48&&57>=e?E(!0):(++br,i(xt))}function f(){var e=dr.charCodeAt(br+1);return Er?(++br,k()):61===e?x(Et,2):x(wt,1)}function d(){var e=dr.charCodeAt(br+1);return 61===e?x(Et,2):x(Dt,1)}function p(e){var r=dr.charCodeAt(br+1);return r===e?x(124===e?Lt:Ut,2):61===r?x(Et,2):x(124===e?Rt:Tt,1)}function h(){var e=dr.charCodeAt(br+1);return 61===e?x(Et,2):x(Vt,1)}function m(e){var r=dr.charCodeAt(br+1);return r===e?45==r&&62==dr.charCodeAt(br+2)&&Gt.test(dr.slice(Lr,br))?(br+=3,c(),u(),g()):x(St,2):61===r?x(Et,2):x(At,1)}function v(e){var r=dr.charCodeAt(br+1),t=1;return r===e?(t=62===e&&62===dr.charCodeAt(br+2)?3:2,61===dr.charCodeAt(br+t)?x(Et,t+1):x(jt,t)):33==r&&60==e&&45==dr.charCodeAt(br+2)&&45==dr.charCodeAt(br+3)?(br+=4,c(),u(),g()):(61===r&&(t=61===dr.charCodeAt(br+2)?3:2),x(Ot,t))}function b(e){var r=dr.charCodeAt(br+1);return 61===r?x(qt,61===dr.charCodeAt(br+2)?3:2):x(61===e?Ct:It,1)}function y(e){switch(e){case 46:return l();case 40:return++br,i(mt);case 41:return++br,i(vt);case 59:return++br,i(yt);case 44:return++br,i(bt);case 91:return++br,i(ft);case 93:return++br,i(dt);case 123:return++br,i(pt);case 125:return++br,i(ht);case 58:return++br,i(gt);case 63:return++br,i(kt);case 48:var r=dr.charCodeAt(br+1);if(120===r||88===r)return C();case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return E(!1);case 34:case 39:return A(e);case 47:return f(e);case 37:case 42:return d();case 124:case 38:return p(e);case 94:return h();case 43:case 45:return m(e);case 60:case 62:return v(e);case 61:case 33:return b(e);case 126:return x(It,1)}return!1}function g(e){if(e?br=yr+1:yr=br,fr.locations&&(xr=new a),e)return k();if(br>=pr)return i(Br);var r=dr.charCodeAt(br);if(Qt(r)||92===r)return L();var n=y(r);if(n===!1){var o=String.fromCharCode(r);if("\\"===o||$t.test(o))return L();t(br,"Unexpected character '"+o+"'")}return n}function x(e,r){var t=dr.slice(br,br+r);br+=r,i(e,t)}function k(){for(var e,r,n="",a=br;;){br>=pr&&t(a,"Unterminated regular expression");var o=dr.charAt(br);if(Gt.test(o)&&t(a,"Unterminated regular expression"),e)e=!1;else{if("["===o)r=!0;else if("]"===o&&r)r=!1;else if("/"===o&&!r)break;e="\\"===o}++br}var n=dr.slice(a,br);++br;var s=I();return s&&!/^[gmsiy]*$/.test(s)&&t(a,"Invalid regexp flag"),i(jr,new RegExp(n,s))}function w(e,r){for(var t=br,n=0,a=0,o=null==r?1/0:r;o>a;++a){var i,s=dr.charCodeAt(br);if(i=s>=97?s-97+10:s>=65?s-65+10:s>=48&&57>=s?s-48:1/0,i>=e)break;++br,n=n*e+i}return br===t||null!=r&&br-t!==r?null:n}function C(){br+=2;var e=w(16);return null==e&&t(yr+2,"Expected hexadecimal number"),Qt(dr.charCodeAt(br))&&t(br,"Identifier directly after number"),i(Or,e)}function E(e){var r=br,n=!1,a=48===dr.charCodeAt(br);e||null!==w(10)||t(r,"Invalid number"),46===dr.charCodeAt(br)&&(++br,w(10),n=!0);var o=dr.charCodeAt(br);(69===o||101===o)&&(o=dr.charCodeAt(++br),(43===o||45===o)&&++br,null===w(10)&&t(r,"Invalid number"),n=!0),Qt(dr.charCodeAt(br))&&t(br,"Identifier directly after number");var s,c=dr.slice(r,br);return n?s=parseFloat(c):a&&1!==c.length?/[89]/.test(c)||Tr?t(r,"Invalid number"):s=parseInt(c,8):s=parseInt(c,10),i(Or,s)}function A(e){br++;for(var r="";;){br>=pr&&t(yr,"Unterminated string constant");var n=dr.charCodeAt(br);if(n===e)return++br,i(Dr,r);if(92===n){n=dr.charCodeAt(++br);var a=/^[0-7]+/.exec(dr.slice(br,br+3));for(a&&(a=a[0]);a&&parseInt(a,8)>255;)a=a.slice(0,a.length-1);if("0"===a&&(a=null),++br,a)Tr&&t(br-2,"Octal literal in strict mode"),r+=String.fromCharCode(parseInt(a,8)),br+=a.length-1;else switch(n){case 110:r+="\n";break;case 114:r+="\r";break;case 120:r+=String.fromCharCode(S(2));break;case 117:r+=String.fromCharCode(S(4));break;case 85:r+=String.fromCharCode(S(8));break;case 116:r+=" ";break;case 98:r+="\b";break;case 118:r+="";break;case 102:r+="\f";break;case 48:r+="\0";break;case 13:10===dr.charCodeAt(br)&&++br;case 10:fr.locations&&(Sr=br,++Ar);break;default:r+=String.fromCharCode(n)}}else(13===n||10===n||8232===n||8233===n)&&t(yr,"Unterminated string constant"),r+=String.fromCharCode(n),++br}}function S(e){var r=w(16,e);return null===r&&t(yr,"Bad character escape sequence"),r}function I(){Bt=!1;for(var e,r=!0,n=br;;){var a=dr.charCodeAt(br);if(Yt(a))Bt&&(e+=dr.charAt(br)),++br;else{if(92!==a)break;Bt||(e=dr.slice(n,br)),Bt=!0,117!=dr.charCodeAt(++br)&&t(br,"Expecting Unicode escape sequence \\uXXXX"),++br;var o=S(4),i=String.fromCharCode(o);i||t(br-1,"Invalid Unicode escape"),(r?Qt(o):Yt(o))||t(br-4,"Invalid Unicode escape"),e+=i}r=!1}return Bt?e:dr.slice(n,br)}function L(){var e=I(),r=Fr;return Bt||(Wt(e)?r=lt[e]:(fr.forbidReserved&&(3===fr.ecmaVersion?Mt:zt)(e)||Tr&&Xt(e))&&t(yr,"The keyword '"+e+"' is reserved")),i(r,e)}function U(){Ir=yr,Lr=gr,Ur=kr,g()}function R(e){if(Tr=e,br=Lr,fr.locations)for(;Sr>br;)Sr=dr.lastIndexOf("\n",Sr-2)+1,--Ar;u(),g()}function V(){this.type=null,this.start=yr,this.end=null}function T(){this.start=xr,this.end=null,null!==hr&&(this.source=hr)}function q(){var e=new V;return fr.locations&&(e.loc=new T),fr.ranges&&(e.range=[yr,0]),e}function O(e){var r=new V;return r.start=e.start,fr.locations&&(r.loc=new T,r.loc.start=e.loc.start),fr.ranges&&(r.range=[e.range[0],0]),r}function j(e,r){return e.type=r,e.end=Lr,fr.locations&&(e.loc.end=Ur),fr.ranges&&(e.range[1]=Lr),e}function D(e){return fr.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"use strict"===e.expression.value}function F(e){return wr===e?(U(),!0):void 0}function B(){return!fr.strictSemicolons&&(wr===Br||wr===ht||Gt.test(dr.slice(Lr,yr)))}function M(){F(yt)||B()||X()}function z(e){wr===e?U():X()}function X(){t(yr,"Unexpected token")}function N(e){"Identifier"!==e.type&&"MemberExpression"!==e.type&&t(e.start,"Assigning to rvalue"),Tr&&"Identifier"===e.type&&Nt(e.name)&&t(e.start,"Assigning to "+e.name+" in strict mode")}function W(e){Ir=Lr=br,fr.locations&&(Ur=new a),Rr=Tr=null,Vr=[],g();var r=e||q(),t=!0;for(e||(r.body=[]);wr!==Br;){var n=J();r.body.push(n),t&&D(n)&&R(!0),t=!1}return j(r,"Program")}function J(){(wr===wt||wr===Et&&"/="==Cr)&&g(!0);var e=wr,r=q();switch(e){case Mr:case Nr:U();var n=e===Mr;F(yt)||B()?r.label=null:wr!==Fr?X():(r.label=lr(),M());for(var a=0;a<Vr.length;++a){var o=Vr[a];if(null==r.label||o.name===r.label.name){if(null!=o.kind&&(n||"loop"===o.kind))break;if(r.label&&n)break}}return a===Vr.length&&t(r.start,"Unsyntactic "+e.keyword),j(r,n?"BreakStatement":"ContinueStatement");case Wr:return U(),M(),j(r,"DebuggerStatement");case Pr:return U(),Vr.push(Zt),r.body=J(),Vr.pop(),z(tt),r.test=P(),M(),j(r,"DoWhileStatement");case _r:if(U(),Vr.push(Zt),z(mt),wr===yt)return $(r,null);if(wr===rt){var i=q();return U(),G(i,!0),j(i,"VariableDeclaration"),1===i.declarations.length&&F(ut)?_(r,i):$(r,i)}var i=K(!1,!0);return F(ut)?(N(i),_(r,i)):$(r,i);case Gr:return U(),cr(r,!0);case Kr:return U(),r.test=P(),r.consequent=J(),r.alternate=F(Hr)?J():null,j(r,"IfStatement");case Qr:return Rr||t(yr,"'return' outside of function"),U(),F(yt)||B()?r.argument=null:(r.argument=K(),M()),j(r,"ReturnStatement");case Yr:U(),r.discriminant=P(),r.cases=[],z(pt),Vr.push(en);for(var s,c;wr!=ht;)if(wr===zr||wr===Jr){var u=wr===zr;s&&j(s,"SwitchCase"),r.cases.push(s=q()),s.consequent=[],U(),u?s.test=K():(c&&t(Ir,"Multiple default clauses"),c=!0,s.test=null),z(gt)}else s||X(),s.consequent.push(J());return s&&j(s,"SwitchCase"),U(),Vr.pop(),j(r,"SwitchStatement");case Zr:return U(),Gt.test(dr.slice(Lr,yr))&&t(Lr,"Illegal newline after throw"),r.argument=K(),M(),j(r,"ThrowStatement");case et:if(U(),r.block=H(),r.handler=null,wr===Xr){var l=q();U(),z(mt),l.param=lr(),Tr&&Nt(l.param.name)&&t(l.param.start,"Binding "+l.param.name+" in strict mode"),z(vt),l.guard=null,l.body=H(),r.handler=j(l,"CatchClause")}return r.guardedHandlers=qr,r.finalizer=F($r)?H():null,r.handler||r.finalizer||t(r.start,"Missing catch or finally clause"),j(r,"TryStatement");case rt:return U(),G(r),M(),j(r,"VariableDeclaration");case tt:return U(),r.test=P(),Vr.push(Zt),r.body=J(),Vr.pop(),j(r,"WhileStatement");case nt:return Tr&&t(yr,"'with' in strict mode"),U(),r.object=P(),r.body=J(),j(r,"WithStatement");case pt:return H();case yt:return U(),j(r,"EmptyStatement");default:var f=Cr,d=K();if(e===Fr&&"Identifier"===d.type&&F(gt)){for(var a=0;a<Vr.length;++a)Vr[a].name===f&&t(d.start,"Label '"+f+"' is already declared");var p=wr.isLoop?"loop":wr===Yr?"switch":null;return Vr.push({name:f,kind:p}),r.body=J(),Vr.pop(),r.label=d,j(r,"LabeledStatement")}return r.expression=d,M(),j(r,"ExpressionStatement")}}function P(){z(mt);var e=K();return z(vt),e}function H(e){var r,t=q(),n=!0,a=!1;for(t.body=[],z(pt);!F(ht);){var o=J();t.body.push(o),n&&e&&D(o)&&(r=a,R(a=!0)),n=!1}return a&&!r&&R(!1),j(t,"BlockStatement")}function $(e,r){return e.init=r,z(yt),e.test=wr===yt?null:K(),z(yt),e.update=wr===vt?null:K(),z(vt),e.body=J(),Vr.pop(),j(e,"ForStatement")}function _(e,r){return e.left=r,e.right=K(),z(vt),e.body=J(),Vr.pop(),j(e,"ForInStatement")}function G(e,r){for(e.declarations=[],e.kind="var";;){var n=q();if(n.id=lr(),Tr&&Nt(n.id.name)&&t(n.id.start,"Binding "+n.id.name+" in strict mode"),n.init=F(Ct)?K(!0,r):null,e.declarations.push(j(n,"VariableDeclarator")),!F(bt))break}return e}function K(e,r){var t=Q(r);if(!e&&wr===bt){var n=O(t);for(n.expressions=[t];F(bt);)n.expressions.push(Q(r));return j(n,"SequenceExpression")}return t}function Q(e){var r=Y(e);if(wr.isAssign){var t=O(r);return t.operator=Cr,t.left=r,U(),t.right=Q(e),N(r),j(t,"AssignmentExpression")}return r}function Y(e){var r=Z(e);if(F(kt)){var t=O(r);return t.test=r,t.consequent=K(!0),z(gt),t.alternate=K(!0,e),j(t,"ConditionalExpression")}return r}function Z(e){return er(rr(),-1,e)}function er(e,r,t){var n=wr.binop;if(null!=n&&(!t||wr!==ut)&&n>r){var a=O(e);a.left=e,a.operator=Cr,U(),a.right=er(rr(),n,t);var o=j(a,/&&|\|\|/.test(a.operator)?"LogicalExpression":"BinaryExpression");return er(o,r,t)}return e}function rr(){if(wr.prefix){var e=q(),r=wr.isUpdate;return e.operator=Cr,e.prefix=!0,Er=!0,U(),e.argument=rr(),r?N(e.argument):Tr&&"delete"===e.operator&&"Identifier"===e.argument.type&&t(e.start,"Deleting local variable in strict mode"),j(e,r?"UpdateExpression":"UnaryExpression")}for(var n=tr();wr.postfix&&!B();){var e=O(n);e.operator=Cr,e.prefix=!1,e.argument=n,N(n),U(),n=j(e,"UpdateExpression")}return n}function tr(){return nr(ar())}function nr(e,r){if(F(xt)){var t=O(e);return t.object=e,t.property=lr(!0),t.computed=!1,nr(j(t,"MemberExpression"),r)}if(F(ft)){var t=O(e);return t.object=e,t.property=K(),t.computed=!0,z(dt),nr(j(t,"MemberExpression"),r)}if(!r&&F(mt)){var t=O(e);return t.callee=e,t.arguments=ur(vt,!1),nr(j(t,"CallExpression"),r)}return e}function ar(){switch(wr){case ot:var e=q();return U(),j(e,"ThisExpression");case Fr:return lr();case Or:case Dr:case jr:var e=q();return e.value=Cr,e.raw=dr.slice(yr,gr),U(),j(e,"Literal");case it:case st:case ct:var e=q();return e.value=wr.atomValue,e.raw=wr.keyword,U(),j(e,"Literal");case mt:var r=xr,t=yr;U();var n=K();return n.start=t,n.end=gr,fr.locations&&(n.loc.start=r,n.loc.end=kr),fr.ranges&&(n.range=[t,gr]),z(vt),n;case ft:var e=q();return U(),e.elements=ur(dt,!0,!0),j(e,"ArrayExpression");case pt:return ir();case Gr:var e=q();return U(),cr(e,!1);case at:return or();default:X()}}function or(){var e=q();return U(),e.callee=nr(ar(),!0),e.arguments=F(mt)?ur(vt,!1):qr,j(e,"NewExpression")}function ir(){var e=q(),r=!0,n=!1;for(e.properties=[],U();!F(ht);){if(r)r=!1;else if(z(bt),fr.allowTrailingCommas&&F(ht))break;var a,o={key:sr()},i=!1;if(F(gt)?(o.value=K(!0),a=o.kind="init"):fr.ecmaVersion>=5&&"Identifier"===o.key.type&&("get"===o.key.name||"set"===o.key.name)?(i=n=!0,a=o.kind=o.key.name,o.key=sr(),wr!==mt&&X(),o.value=cr(q(),!1)):X(),"Identifier"===o.key.type&&(Tr||n))for(var s=0;s<e.properties.length;++s){var c=e.properties[s];if(c.key.name===o.key.name){var u=a==c.kind||i&&"init"===c.kind||"init"===a&&("get"===c.kind||"set"===c.kind);u&&!Tr&&"init"===a&&"init"===c.kind&&(u=!1),u&&t(o.key.start,"Redefinition of property")}}e.properties.push(o)}return j(e,"ObjectExpression")}function sr(){return wr===Or||wr===Dr?ar():lr(!0)}function cr(e,r){wr===Fr?e.id=lr():r?X():e.id=null,e.params=[];var n=!0;for(z(mt);!F(vt);)n?n=!1:z(bt),e.params.push(lr());var a=Rr,o=Vr;if(Rr=!0,Vr=[],e.body=H(!0),Rr=a,Vr=o,Tr||e.body.body.length&&D(e.body.body[0]))for(var i=e.id?-1:0;i<e.params.length;++i){var s=0>i?e.id:e.params[i];if((Xt(s.name)||Nt(s.name))&&t(s.start,"Defining '"+s.name+"' in strict mode"),i>=0)for(var c=0;i>c;++c)s.name===e.params[c].name&&t(s.start,"Argument name clash in strict mode")}return j(e,r?"FunctionDeclaration":"FunctionExpression")}function ur(e,r,t){for(var n=[],a=!0;!F(e);){if(a)a=!1;else if(z(bt),r&&fr.allowTrailingCommas&&F(e))break;t&&wr===bt?n.push(null):n.push(K(!0))}return n}function lr(e){var r=q();return r.name=wr===Fr?Cr:e&&!fr.forbidReserved&&wr.keyword||X(),Er=!1,U(),j(r,"Identifier")}e.version="0.4.0";var fr,dr,pr,hr;e.parse=function(e,t){return dr=String(e),pr=dr.length,r(t),o(),W(fr.program)};var mr=e.defaultOptions={ecmaVersion:5,strictSemicolons:!1,allowTrailingCommas:!0,forbidReserved:!1,locations:!1,onComment:null,ranges:!1,program:null,sourceFile:null},vr=e.getLineInfo=function(e,r){for(var t=1,n=0;;){Kt.lastIndex=n;var a=Kt.exec(e);if(!(a&&a.index<r))break;++t,n=a.index+a[0].length}return{line:t,column:r-n}};e.tokenize=function(e,t){function n(e){return g(e),a.start=yr,a.end=gr,a.startLoc=xr,a.endLoc=kr,a.type=wr,a.value=Cr,a}dr=String(e),pr=dr.length,r(t),o();var a={};return n.jumpTo=function(e,r){if(br=e,fr.locations){Ar=1,Sr=Kt.lastIndex=0;for(var t;(t=Kt.exec(dr))&&t.index<e;)++Ar,Sr=t.index+t[0].length}Er=r,u()},n};var br,yr,gr,xr,kr,wr,Cr,Er,Ar,Sr,Ir,Lr,Ur,Rr,Vr,Tr,qr=[],Or={type:"num"},jr={type:"regexp"},Dr={type:"string"},Fr={type:"name"},Br={type:"eof"},Mr={keyword:"break"},zr={keyword:"case",beforeExpr:!0},Xr={keyword:"catch"},Nr={keyword:"continue"},Wr={keyword:"debugger"},Jr={keyword:"default"},Pr={keyword:"do",isLoop:!0},Hr={keyword:"else",beforeExpr:!0},$r={keyword:"finally"},_r={keyword:"for",isLoop:!0},Gr={keyword:"function"},Kr={keyword:"if"},Qr={keyword:"return",beforeExpr:!0},Yr={keyword:"switch"},Zr={keyword:"throw",beforeExpr:!0},et={keyword:"try"},rt={keyword:"var"},tt={keyword:"while",isLoop:!0},nt={keyword:"with"},at={keyword:"new",beforeExpr:!0},ot={keyword:"this"},it={keyword:"null",atomValue:null},st={keyword:"true",atomValue:!0},ct={keyword:"false",atomValue:!1},ut={keyword:"in",binop:7,beforeExpr:!0},lt={"break":Mr,"case":zr,"catch":Xr,"continue":Nr,"debugger":Wr,"default":Jr,"do":Pr,"else":Hr,"finally":$r,"for":_r,"function":Gr,"if":Kr,"return":Qr,"switch":Yr,"throw":Zr,"try":et,"var":rt,"while":tt,"with":nt,"null":it,"true":st,"false":ct,"new":at,"in":ut,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:!0},"this":ot,"typeof":{keyword:"typeof",prefix:!0,beforeExpr:!0},"void":{keyword:"void",prefix:!0,beforeExpr:!0},"delete":{keyword:"delete",prefix:!0,beforeExpr:!0}},ft={type:"[",beforeExpr:!0},dt={type:"]"},pt={type:"{",beforeExpr:!0},ht={type:"}"},mt={type:"(",beforeExpr:!0},vt={type:")"},bt={type:",",beforeExpr:!0},yt={type:";",beforeExpr:!0},gt={type:":",beforeExpr:!0},xt={type:"."},kt={type:"?",beforeExpr:!0},wt={binop:10,beforeExpr:!0},Ct={isAssign:!0,beforeExpr:!0},Et={isAssign:!0,beforeExpr:!0},At={binop:9,prefix:!0,beforeExpr:!0},St={postfix:!0,prefix:!0,isUpdate:!0},It={prefix:!0,beforeExpr:!0},Lt={binop:1,beforeExpr:!0},Ut={binop:2,beforeExpr:!0},Rt={binop:3,beforeExpr:!0},Vt={binop:4,beforeExpr:!0},Tt={binop:5,beforeExpr:!0},qt={binop:6,beforeExpr:!0},Ot={binop:7,beforeExpr:!0},jt={binop:8,beforeExpr:!0},Dt={binop:10,beforeExpr:!0};e.tokTypes={bracketL:ft,bracketR:dt,braceL:pt,braceR:ht,parenL:mt,parenR:vt,comma:bt,semi:yt,colon:gt,dot:xt,question:kt,slash:wt,eq:Ct,name:Fr,eof:Br,num:Or,regexp:jr,string:Dr};for(var Ft in lt)e.tokTypes["_"+Ft]=lt[Ft];var Bt,Mt=n("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"),zt=n("class enum extends super const export import"),Xt=n("implements interface let package private protected public static yield"),Nt=n("eval arguments"),Wt=n("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"),Jt=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,Pt="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",Ht="\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f",$t=new RegExp("["+Pt+"]"),_t=new RegExp("["+Pt+Ht+"]"),Gt=/[\n\r\u2028\u2029]/,Kt=/\r\n|[\n\r\u2028\u2029]/g,Qt=e.isIdentifierStart=function(e){return 65>e?36===e:91>e?!0:97>e?95===e:123>e?!0:e>=170&&$t.test(String.fromCharCode(e))},Yt=e.isIdentifierChar=function(e){return 48>e?36===e:58>e?!0:65>e?!1:91>e?!0:97>e?95===e:123>e?!0:e>=170&&_t.test(String.fromCharCode(e))},Zt={kind:"loop"},en={kind:"switch"}});
+
+ var binaryOperators = {
+ '+': '__add',
+ '-': '__subtract',
+ '*': '__multiply',
+ '/': '__divide',
+ '%': '__modulo',
+ '==': 'equals',
+ '!=': 'equals'
+ };
+
+ var unaryOperators = {
+ '-': '__negate',
+ '+': null
+ };
+
+ var fields = Base.each(
+ ['add', 'subtract', 'multiply', 'divide', 'modulo', 'negate'],
+ function(name) {
+ this['__' + name] = '#' + name;
+ },
+ {}
+ );
+ Point.inject(fields);
+ Size.inject(fields);
+ Color.inject(fields);
+
+ function __$__(left, operator, right) {
+ var handler = binaryOperators[operator];
+ if (left && left[handler]) {
+ var res = left[handler](right);
+ return operator === '!=' ? !res : res;
+ }
+ switch (operator) {
+ case '+': return left + right;
+ case '-': return left - right;
+ case '*': return left * right;
+ case '/': return left / right;
+ case '%': return left % right;
+ case '==': return left == right;
+ case '!=': return left != right;
+ }
+ }
+
+ function $__(operator, value) {
+ var handler = unaryOperators[operator];
+ if (handler && value && value[handler])
+ return value[handler]();
+ switch (operator) {
+ case '+': return +value;
+ case '-': return -value;
+ }
+ }
+
+ function parse(code, options) {
+ return scope.acorn.parse(code, options);
+ }
+
+ function compile(code, url, options) {
+ if (!code)
+ return '';
+ options = options || {};
+ url = url || '';
+
+ var insertions = [];
+
+ function getOffset(offset) {
+ for (var i = 0, l = insertions.length; i < l; i++) {
+ var insertion = insertions[i];
+ if (insertion[0] >= offset)
+ break;
+ offset += insertion[1];
+ }
+ return offset;
+ }
+
+ function getCode(node) {
+ return code.substring(getOffset(node.range[0]),
+ getOffset(node.range[1]));
+ }
+
+ function getBetween(left, right) {
+ return code.substring(getOffset(left.range[1]),
+ getOffset(right.range[0]));
+ }
+
+ function replaceCode(node, str) {
+ var start = getOffset(node.range[0]),
+ end = getOffset(node.range[1]),
+ insert = 0;
+ for (var i = insertions.length - 1; i >= 0; i--) {
+ if (start > insertions[i][0]) {
+ insert = i + 1;
+ break;
+ }
+ }
+ insertions.splice(insert, 0, [start, str.length - end + start]);
+ code = code.substring(0, start) + str + code.substring(end);
+ }
+
+ function walkAST(node, parent) {
+ if (!node)
+ return;
+ for (var key in node) {
+ if (key === 'range' || key === 'loc')
+ continue;
+ var value = node[key];
+ if (Array.isArray(value)) {
+ for (var i = 0, l = value.length; i < l; i++)
+ walkAST(value[i], node);
+ } else if (value && typeof value === 'object') {
+ walkAST(value, node);
+ }
+ }
+ switch (node.type) {
+ case 'UnaryExpression':
+ if (node.operator in unaryOperators
+ && node.argument.type !== 'Literal') {
+ var arg = getCode(node.argument);
+ replaceCode(node, '$__("' + node.operator + '", '
+ + arg + ')');
+ }
+ break;
+ case 'BinaryExpression':
+ if (node.operator in binaryOperators
+ && node.left.type !== 'Literal') {
+ var left = getCode(node.left),
+ right = getCode(node.right),
+ between = getBetween(node.left, node.right),
+ operator = node.operator;
+ replaceCode(node, '__$__(' + left + ','
+ + between.replace(new RegExp('\\' + operator),
+ '"' + operator + '"')
+ + ', ' + right + ')');
+ }
+ break;
+ case 'UpdateExpression':
+ case 'AssignmentExpression':
+ var parentType = parent && parent.type;
+ if (!(
+ parentType === 'ForStatement'
+ || parentType === 'BinaryExpression'
+ && /^[=!<>]/.test(parent.operator)
+ || parentType === 'MemberExpression' && parent.computed
+ )) {
+ if (node.type === 'UpdateExpression') {
+ var arg = getCode(node.argument);
+ var str = arg + ' = __$__(' + arg
+ + ', "' + node.operator[0] + '", 1)';
+ if (!node.prefix
+ && (parentType === 'AssignmentExpression'
+ || parentType === 'VariableDeclarator'))
+ str = arg + '; ' + str;
+ replaceCode(node, str);
+ } else {
+ if (/^.=$/.test(node.operator)
+ && node.left.type !== 'Literal') {
+ var left = getCode(node.left),
+ right = getCode(node.right);
+ replaceCode(node, left + ' = __$__(' + left + ', "'
+ + node.operator[0] + '", ' + right + ')');
+ }
+ }
+ }
+ break;
+ }
+ }
+ var sourceMap = null,
+ browser = paper.browser,
+ version = browser.versionNumber,
+ lineBreaks = /\r\n|\n|\r/mg;
+ if (browser.chrome && version >= 30
+ || browser.webkit && version >= 537.76
+ || browser.firefox && version >= 23) {
+ var offset = 0;
+ if (window.location.href.indexOf(url) === 0) {
+ var html = document.getElementsByTagName('html')[0].innerHTML;
+ offset = html.substr(0, html.indexOf(code) + 1).match(
+ lineBreaks).length + 1;
+ }
+ var mappings = ['AAAA'];
+ mappings.length = (code.match(lineBreaks) || []).length + 1 + offset;
+ sourceMap = {
+ version: 3,
+ file: url,
+ names:[],
+ mappings: mappings.join(';AACA'),
+ sourceRoot: '',
+ sources: [url]
+ };
+ var source = options.source || !url && code;
+ if (source)
+ sourceMap.sourcesContent = [source];
+ }
+ walkAST(parse(code, { ranges: true }));
+ if (sourceMap) {
+ code = new Array(offset + 1).join('\n') + code
+ + "\n//# sourceMappingURL=data:application/json;base64,"
+ + (btoa(unescape(encodeURIComponent(
+ JSON.stringify(sourceMap)))))
+ + "\n//# sourceURL=" + (url || 'paperscript');
+ }
+ return code;
+ }
+
+ function execute(code, scope, url, options) {
+ paper = scope;
+ var view = scope.getView(),
+ tool = /\s+on(?:Key|Mouse)(?:Up|Down|Move|Drag)\b/.test(code)
+ ? new Tool()
+ : null,
+ toolHandlers = tool ? tool._events : [],
+ handlers = ['onFrame', 'onResize'].concat(toolHandlers),
+ params = [],
+ args = [],
+ func;
+ code = compile(code, url, options);
+ function expose(scope, hidden) {
+ for (var key in scope) {
+ if ((hidden || !/^_/.test(key)) && new RegExp('([\\b\\s\\W]|^)'
+ + key.replace(/\$/g, '\\$') + '\\b').test(code)) {
+ params.push(key);
+ args.push(scope[key]);
+ }
+ }
+ }
+ expose({ __$__: __$__, $__: $__, paper: scope, view: view, tool: tool },
+ true);
+ expose(scope);
+ handlers = Base.each(handlers, function(key) {
+ if (new RegExp('\\s+' + key + '\\b').test(code)) {
+ params.push(key);
+ this.push(key + ': ' + key);
+ }
+ }, []).join(', ');
+ if (handlers)
+ code += '\nreturn { ' + handlers + ' };';
+ var browser = paper.browser;
+ if (browser.chrome || browser.firefox) {
+ var script = document.createElement('script'),
+ head = document.head;
+ if (browser.firefox)
+ code = '\n' + code;
+ script.appendChild(document.createTextNode(
+ 'paper._execute = function(' + params + ') {' + code + '\n}'
+ ));
+ head.appendChild(script);
+ func = paper._execute;
+ delete paper._execute;
+ head.removeChild(script);
+ } else {
+ func = Function(params, code);
+ }
+ var res = func.apply(scope, args) || {};
+ Base.each(toolHandlers, function(key) {
+ var value = res[key];
+ if (value)
+ tool[key] = value;
+ });
+ if (view) {
+ if (res.onResize)
+ view.setOnResize(res.onResize);
+ view.emit('resize', {
+ size: view.size,
+ delta: new Point()
+ });
+ if (res.onFrame)
+ view.setOnFrame(res.onFrame);
+ view.update();
+ }
+ }
+
+ function loadScript(script) {
+ if (/^text\/(?:x-|)paperscript$/.test(script.type)
+ && PaperScope.getAttribute(script, 'ignore') !== 'true') {
+ var canvasId = PaperScope.getAttribute(script, 'canvas'),
+ canvas = document.getElementById(canvasId),
+ src = script.src,
+ scopeAttribute = 'data-paper-scope';
+ if (!canvas)
+ throw new Error('Unable to find canvas with id "'
+ + canvasId + '"');
+ var scope = PaperScope.get(canvas.getAttribute(scopeAttribute))
+ || new PaperScope().setup(canvas);
+ canvas.setAttribute(scopeAttribute, scope._id);
+ if (src) {
+ Http.request('get', src, function(code) {
+ execute(code, scope, src);
+ });
+ } else {
+ execute(script.innerHTML, scope, script.baseURI);
+ }
+ script.setAttribute('data-paper-ignore', 'true');
+ return scope;
+ }
+ }
+
+ function loadAll() {
+ Base.each(document.getElementsByTagName('script'), loadScript);
+ }
+
+ function load(script) {
+ return script ? loadScript(script) : loadAll();
+ }
+
+ if (document.readyState === 'complete') {
+ setTimeout(loadAll);
+ } else {
+ DomEvent.add(window, { load: loadAll });
+ }
+
+ return {
+ compile: compile,
+ execute: execute,
+ load: load,
+ parse: parse
+ };
+
+}).call(this);
+
+paper = new (PaperScope.inject(Base.exports, {
+ enumerable: true,
+ Base: Base,
+ Numerical: Numerical,
+ Key: Key
+}))();
+
+if (typeof define === 'function' && define.amd) {
+ define('paper', paper);
+} else if (typeof module === 'object' && module) {
+ module.exports = paper;
+}
+
+return paper;
+};
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/requirejs/require.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,2076 @@
+/** vim: et:ts=4:sw=4:sts=4
+ * @license RequireJS 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Not using strict: uneven strict support in browsers, #392, and causes
+//problems with requirejs.exec()/transpiler plugins that may not be strict.
+/*jslint regexp: true, nomen: true, sloppy: true */
+/*global window, navigator, document, importScripts, setTimeout, opera */
+
+var requirejs, require, define;
+(function (global) {
+ var req, s, head, baseElement, dataMain, src,
+ interactiveScript, currentlyAddingScript, mainScript, subPath,
+ version = '2.1.15',
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
+ cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
+ jsSuffixRegExp = /\.js$/,
+ currDirRegExp = /^\.\//,
+ op = Object.prototype,
+ ostring = op.toString,
+ hasOwn = op.hasOwnProperty,
+ ap = Array.prototype,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
+ isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is 'loading', 'loaded', execution,
+ // then 'complete'. The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
+ /^complete$/ : /^(complete|loaded)$/,
+ defContextName = '_',
+ //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
+ isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
+ contexts = {},
+ cfg = {},
+ globalDefQueue = [],
+ useInteractive = false;
+
+ function isFunction(it) {
+ return ostring.call(it) === '[object Function]';
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === '[object Array]';
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function for iterating over an array backwards. If the func
+ * returns a true value, it will break out of the loop.
+ */
+ function eachReverse(ary, func) {
+ if (ary) {
+ var i;
+ for (i = ary.length - 1; i > -1; i -= 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ function getOwn(obj, prop) {
+ return hasProp(obj, prop) && obj[prop];
+ }
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ function eachProp(obj, func) {
+ var prop;
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ */
+ function mixin(target, source, force, deepStringMixin) {
+ if (source) {
+ eachProp(source, function (value, prop) {
+ if (force || !hasProp(target, prop)) {
+ if (deepStringMixin && typeof value === 'object' && value &&
+ !isArray(value) && !isFunction(value) &&
+ !(value instanceof RegExp)) {
+
+ if (!target[prop]) {
+ target[prop] = {};
+ }
+ mixin(target[prop], value, force, deepStringMixin);
+ } else {
+ target[prop] = value;
+ }
+ }
+ });
+ }
+ return target;
+ }
+
+ //Similar to Function.prototype.bind, but the 'this' object is specified
+ //first, since it is easier to read/figure out what 'this' will be.
+ function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments);
+ };
+ }
+
+ function scripts() {
+ return document.getElementsByTagName('script');
+ }
+
+ function defaultOnError(err) {
+ throw err;
+ }
+
+ //Allow getting a global that is expressed in
+ //dot notation, like 'a.b.c'.
+ function getGlobal(value) {
+ if (!value) {
+ return value;
+ }
+ var g = global;
+ each(value.split('.'), function (part) {
+ g = g[part];
+ });
+ return g;
+ }
+
+ /**
+ * Constructs an error with a pointer to an URL with more information.
+ * @param {String} id the error ID that maps to an ID on a web page.
+ * @param {String} message human readable error.
+ * @param {Error} [err] the original error, if there is one.
+ *
+ * @returns {Error}
+ */
+ function makeError(id, msg, err, requireModules) {
+ var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
+ e.requireType = id;
+ e.requireModules = requireModules;
+ if (err) {
+ e.originalError = err;
+ }
+ return e;
+ }
+
+ if (typeof define !== 'undefined') {
+ //If a define is already in play via another AMD loader,
+ //do not overwrite.
+ return;
+ }
+
+ if (typeof requirejs !== 'undefined') {
+ if (isFunction(requirejs)) {
+ //Do not overwrite an existing requirejs instance.
+ return;
+ }
+ cfg = requirejs;
+ requirejs = undefined;
+ }
+
+ //Allow for a require config object
+ if (typeof require !== 'undefined' && !isFunction(require)) {
+ //assume it is a config object.
+ cfg = require;
+ require = undefined;
+ }
+
+ function newContext(contextName) {
+ var inCheckLoaded, Module, context, handlers,
+ checkLoadedTimeoutId,
+ config = {
+ //Defaults. Do not set a default for map
+ //config to speed up normalize(), which
+ //will run faster if there is no default.
+ waitSeconds: 7,
+ baseUrl: './',
+ paths: {},
+ bundles: {},
+ pkgs: {},
+ shim: {},
+ config: {}
+ },
+ registry = {},
+ //registry of just enabled modules, to speed
+ //cycle breaking code when lots of modules
+ //are registered, but not activated.
+ enabledRegistry = {},
+ undefEvents = {},
+ defQueue = [],
+ defined = {},
+ urlFetched = {},
+ bundlesMap = {},
+ requireCounter = 1,
+ unnormalizedCounter = 1;
+
+ /**
+ * Trims the . and .. from an array of path segments.
+ * It will keep a leading path segment if a .. will become
+ * the first path segment, to help with module name lookups,
+ * which act like paths, but can be remapped. But the end result,
+ * all paths that use this function should look normalized.
+ * NOTE: this method MODIFIES the input array.
+ * @param {Array} ary the array of path segments.
+ */
+ function trimDots(ary) {
+ var i, part;
+ for (i = 0; i < ary.length; i++) {
+ part = ary[i];
+ if (part === '.') {
+ ary.splice(i, 1);
+ i -= 1;
+ } else if (part === '..') {
+ // If at the start, or previous value is still ..,
+ // keep them so that when converted to a path it may
+ // still work when converted to a path, even though
+ // as an ID it is less than ideal. In larger point
+ // releases, may be better to just kick out an error.
+ if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
+ continue;
+ } else if (i > 0) {
+ ary.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ }
+ }
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @param {Boolean} applyMap apply the map config to the value. Should
+ * only be done if this normalization is for a dependency ID.
+ * @returns {String} normalized name
+ */
+ function normalize(name, baseName, applyMap) {
+ var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
+ foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
+ baseParts = (baseName && baseName.split('/')),
+ map = config.map,
+ starMap = map && map['*'];
+
+ //Adjust any relative paths.
+ if (name) {
+ name = name.split('/');
+ lastIndex = name.length - 1;
+
+ // If wanting node ID compatibility, strip .js from end
+ // of IDs. Have to do this here, and not in nameToUrl
+ // because node allows either .js or non .js to map
+ // to same file.
+ if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
+ name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
+ }
+
+ // Starts with a '.' so need the baseName
+ if (name[0].charAt(0) === '.' && baseParts) {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that 'directory' and not name of the baseName's
+ //module. For instance, baseName of 'one/two/three', maps to
+ //'one/two/three.js', but we want the directory, 'one/two' for
+ //this normalization.
+ normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
+ name = normalizedBaseParts.concat(name);
+ }
+
+ trimDots(name);
+ name = name.join('/');
+ }
+
+ //Apply map config if available.
+ if (applyMap && map && (baseParts || starMap)) {
+ nameParts = name.split('/');
+
+ outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join('/');
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = getOwn(mapValue, nameSegment);
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue;
+ foundI = i;
+ break outerLoop;
+ }
+ }
+ }
+ }
+
+ //Check for a star map match, but just hold on to it,
+ //if there is a shorter segment match later in a matching
+ //config, then favor over this star map.
+ if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
+ foundStarMap = getOwn(starMap, nameSegment);
+ starI = i;
+ }
+ }
+
+ if (!foundMap && foundStarMap) {
+ foundMap = foundStarMap;
+ foundI = starI;
+ }
+
+ if (foundMap) {
+ nameParts.splice(0, foundI, foundMap);
+ name = nameParts.join('/');
+ }
+ }
+
+ // If the name points to a package's name, use
+ // the package main instead.
+ pkgMain = getOwn(config.pkgs, name);
+
+ return pkgMain ? pkgMain : name;
+ }
+
+ function removeScript(name) {
+ if (isBrowser) {
+ each(scripts(), function (scriptNode) {
+ if (scriptNode.getAttribute('data-requiremodule') === name &&
+ scriptNode.getAttribute('data-requirecontext') === context.contextName) {
+ scriptNode.parentNode.removeChild(scriptNode);
+ return true;
+ }
+ });
+ }
+ }
+
+ function hasPathFallback(id) {
+ var pathConfig = getOwn(config.paths, id);
+ if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
+ //Pop off the first array value, since it failed, and
+ //retry
+ pathConfig.shift();
+ context.require.undef(id);
+
+ //Custom require that does not do map translation, since
+ //ID is "absolute", already mapped/resolved.
+ context.makeRequire(null, {
+ skipMap: true
+ })([id]);
+
+ return true;
+ }
+ }
+
+ //Turns a plugin!resource to [plugin, resource]
+ //with the plugin being undefined if the name
+ //did not have a plugin prefix.
+ function splitPrefix(name) {
+ var prefix,
+ index = name ? name.indexOf('!') : -1;
+ if (index > -1) {
+ prefix = name.substring(0, index);
+ name = name.substring(index + 1, name.length);
+ }
+ return [prefix, name];
+ }
+
+ /**
+ * Creates a module mapping that includes plugin prefix, module
+ * name, and path. If parentModuleMap is provided it will
+ * also normalize the name via require.normalize()
+ *
+ * @param {String} name the module name
+ * @param {String} [parentModuleMap] parent module map
+ * for the module name, used to resolve relative names.
+ * @param {Boolean} isNormalized: is the ID already normalized.
+ * This is true if this call is done for a define() module ID.
+ * @param {Boolean} applyMap: apply the map config to the ID.
+ * Should only be true if this map is for a dependency.
+ *
+ * @returns {Object}
+ */
+ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
+ var url, pluginModule, suffix, nameParts,
+ prefix = null,
+ parentName = parentModuleMap ? parentModuleMap.name : null,
+ originalName = name,
+ isDefine = true,
+ normalizedName = '';
+
+ //If no name, then it means it is a require call, generate an
+ //internal name.
+ if (!name) {
+ isDefine = false;
+ name = '_@r' + (requireCounter += 1);
+ }
+
+ nameParts = splitPrefix(name);
+ prefix = nameParts[0];
+ name = nameParts[1];
+
+ if (prefix) {
+ prefix = normalize(prefix, parentName, applyMap);
+ pluginModule = getOwn(defined, prefix);
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ if (prefix) {
+ if (pluginModule && pluginModule.normalize) {
+ //Plugin is loaded, use its normalize method.
+ normalizedName = pluginModule.normalize(name, function (name) {
+ return normalize(name, parentName, applyMap);
+ });
+ } else {
+ // If nested plugin references, then do not try to
+ // normalize, as it will not normalize correctly. This
+ // places a restriction on resourceIds, and the longer
+ // term solution is not to normalize until plugins are
+ // loaded and all normalizations to allow for async
+ // loading of a loader plugin. But for now, fixes the
+ // common uses. Details in #1131
+ normalizedName = name.indexOf('!') === -1 ?
+ normalize(name, parentName, applyMap) :
+ name;
+ }
+ } else {
+ //A regular module.
+ normalizedName = normalize(name, parentName, applyMap);
+
+ //Normalized name may be a plugin ID due to map config
+ //application in normalize. The map config values must
+ //already be normalized, so do not need to redo that part.
+ nameParts = splitPrefix(normalizedName);
+ prefix = nameParts[0];
+ normalizedName = nameParts[1];
+ isNormalized = true;
+
+ url = context.nameToUrl(normalizedName);
+ }
+ }
+
+ //If the id is a plugin id that cannot be determined if it needs
+ //normalization, stamp it with a unique ID so two matching relative
+ //ids that may conflict can be separate.
+ suffix = prefix && !pluginModule && !isNormalized ?
+ '_unnormalized' + (unnormalizedCounter += 1) :
+ '';
+
+ return {
+ prefix: prefix,
+ name: normalizedName,
+ parentMap: parentModuleMap,
+ unnormalized: !!suffix,
+ url: url,
+ originalName: originalName,
+ isDefine: isDefine,
+ id: (prefix ?
+ prefix + '!' + normalizedName :
+ normalizedName) + suffix
+ };
+ }
+
+ function getModule(depMap) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (!mod) {
+ mod = registry[id] = new context.Module(depMap);
+ }
+
+ return mod;
+ }
+
+ function on(depMap, name, fn) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (hasProp(defined, id) &&
+ (!mod || mod.defineEmitComplete)) {
+ if (name === 'defined') {
+ fn(defined[id]);
+ }
+ } else {
+ mod = getModule(depMap);
+ if (mod.error && name === 'error') {
+ fn(mod.error);
+ } else {
+ mod.on(name, fn);
+ }
+ }
+ }
+
+ function onError(err, errback) {
+ var ids = err.requireModules,
+ notified = false;
+
+ if (errback) {
+ errback(err);
+ } else {
+ each(ids, function (id) {
+ var mod = getOwn(registry, id);
+ if (mod) {
+ //Set error on module, so it skips timeout checks.
+ mod.error = err;
+ if (mod.events.error) {
+ notified = true;
+ mod.emit('error', err);
+ }
+ }
+ });
+
+ if (!notified) {
+ req.onError(err);
+ }
+ }
+ }
+
+ /**
+ * Internal method to transfer globalQueue items to this context's
+ * defQueue.
+ */
+ function takeGlobalQueue() {
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(defQueue,
+ [defQueue.length, 0].concat(globalDefQueue));
+ globalDefQueue = [];
+ }
+ }
+
+ handlers = {
+ 'require': function (mod) {
+ if (mod.require) {
+ return mod.require;
+ } else {
+ return (mod.require = context.makeRequire(mod.map));
+ }
+ },
+ 'exports': function (mod) {
+ mod.usingExports = true;
+ if (mod.map.isDefine) {
+ if (mod.exports) {
+ return (defined[mod.map.id] = mod.exports);
+ } else {
+ return (mod.exports = defined[mod.map.id] = {});
+ }
+ }
+ },
+ 'module': function (mod) {
+ if (mod.module) {
+ return mod.module;
+ } else {
+ return (mod.module = {
+ id: mod.map.id,
+ uri: mod.map.url,
+ config: function () {
+ return getOwn(config.config, mod.map.id) || {};
+ },
+ exports: mod.exports || (mod.exports = {})
+ });
+ }
+ }
+ };
+
+ function cleanRegistry(id) {
+ //Clean up machinery used for waiting modules.
+ delete registry[id];
+ delete enabledRegistry[id];
+ }
+
+ function breakCycle(mod, traced, processed) {
+ var id = mod.map.id;
+
+ if (mod.error) {
+ mod.emit('error', mod.error);
+ } else {
+ traced[id] = true;
+ each(mod.depMaps, function (depMap, i) {
+ var depId = depMap.id,
+ dep = getOwn(registry, depId);
+
+ //Only force things that have not completed
+ //being defined, so still in the registry,
+ //and only if it has not been matched up
+ //in the module already.
+ if (dep && !mod.depMatched[i] && !processed[depId]) {
+ if (getOwn(traced, depId)) {
+ mod.defineDep(i, defined[depId]);
+ mod.check(); //pass false?
+ } else {
+ breakCycle(dep, traced, processed);
+ }
+ }
+ });
+ processed[id] = true;
+ }
+ }
+
+ function checkLoaded() {
+ var err, usingPathFallback,
+ waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
+ noLoads = [],
+ reqCalls = [],
+ stillLoading = false,
+ needCycleCheck = true;
+
+ //Do not bother if this call was a result of a cycle break.
+ if (inCheckLoaded) {
+ return;
+ }
+
+ inCheckLoaded = true;
+
+ //Figure out the state of all the modules.
+ eachProp(enabledRegistry, function (mod) {
+ var map = mod.map,
+ modId = map.id;
+
+ //Skip things that are not enabled or in error state.
+ if (!mod.enabled) {
+ return;
+ }
+
+ if (!map.isDefine) {
+ reqCalls.push(mod);
+ }
+
+ if (!mod.error) {
+ //If the module should be executed, and it has not
+ //been inited and time is up, remember it.
+ if (!mod.inited && expired) {
+ if (hasPathFallback(modId)) {
+ usingPathFallback = true;
+ stillLoading = true;
+ } else {
+ noLoads.push(modId);
+ removeScript(modId);
+ }
+ } else if (!mod.inited && mod.fetched && map.isDefine) {
+ stillLoading = true;
+ if (!map.prefix) {
+ //No reason to keep looking for unfinished
+ //loading. If the only stillLoading is a
+ //plugin resource though, keep going,
+ //because it may be that a plugin resource
+ //is waiting on a non-plugin cycle.
+ return (needCycleCheck = false);
+ }
+ }
+ }
+ });
+
+ if (expired && noLoads.length) {
+ //If wait time expired, throw error of unloaded modules.
+ err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
+ err.contextName = context.contextName;
+ return onError(err);
+ }
+
+ //Not expired, check for a cycle.
+ if (needCycleCheck) {
+ each(reqCalls, function (mod) {
+ breakCycle(mod, {}, {});
+ });
+ }
+
+ //If still waiting on loads, and the waiting load is something
+ //other than a plugin resource, or there are still outstanding
+ //scripts, then just try back later.
+ if ((!expired || usingPathFallback) && stillLoading) {
+ //Something is still waiting to load. Wait for it, but only
+ //if a timeout is not already in effect.
+ if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
+ checkLoadedTimeoutId = setTimeout(function () {
+ checkLoadedTimeoutId = 0;
+ checkLoaded();
+ }, 50);
+ }
+ }
+
+ inCheckLoaded = false;
+ }
+
+ Module = function (map) {
+ this.events = getOwn(undefEvents, map.id) || {};
+ this.map = map;
+ this.shim = getOwn(config.shim, map.id);
+ this.depExports = [];
+ this.depMaps = [];
+ this.depMatched = [];
+ this.pluginMaps = {};
+ this.depCount = 0;
+
+ /* this.exports this.factory
+ this.depMaps = [],
+ this.enabled, this.fetched
+ */
+ };
+
+ Module.prototype = {
+ init: function (depMaps, factory, errback, options) {
+ options = options || {};
+
+ //Do not do more inits if already done. Can happen if there
+ //are multiple define calls for the same module. That is not
+ //a normal, common case, but it is also not unexpected.
+ if (this.inited) {
+ return;
+ }
+
+ this.factory = factory;
+
+ if (errback) {
+ //Register for errors on this module.
+ this.on('error', errback);
+ } else if (this.events.error) {
+ //If no errback already, but there are error listeners
+ //on this module, set up an errback to pass to the deps.
+ errback = bind(this, function (err) {
+ this.emit('error', err);
+ });
+ }
+
+ //Do a copy of the dependency array, so that
+ //source inputs are not modified. For example
+ //"shim" deps are passed in here directly, and
+ //doing a direct modification of the depMaps array
+ //would affect that config.
+ this.depMaps = depMaps && depMaps.slice(0);
+
+ this.errback = errback;
+
+ //Indicate this module has be initialized
+ this.inited = true;
+
+ this.ignore = options.ignore;
+
+ //Could have option to init this module in enabled mode,
+ //or could have been previously marked as enabled. However,
+ //the dependencies are not known until init is called. So
+ //if enabled previously, now trigger dependencies as enabled.
+ if (options.enabled || this.enabled) {
+ //Enable this module and dependencies.
+ //Will call this.check()
+ this.enable();
+ } else {
+ this.check();
+ }
+ },
+
+ defineDep: function (i, depExports) {
+ //Because of cycles, defined callback for a given
+ //export can be called more than once.
+ if (!this.depMatched[i]) {
+ this.depMatched[i] = true;
+ this.depCount -= 1;
+ this.depExports[i] = depExports;
+ }
+ },
+
+ fetch: function () {
+ if (this.fetched) {
+ return;
+ }
+ this.fetched = true;
+
+ context.startTime = (new Date()).getTime();
+
+ var map = this.map;
+
+ //If the manager is for a plugin managed resource,
+ //ask the plugin to load it now.
+ if (this.shim) {
+ context.makeRequire(this.map, {
+ enableBuildCallback: true
+ })(this.shim.deps || [], bind(this, function () {
+ return map.prefix ? this.callPlugin() : this.load();
+ }));
+ } else {
+ //Regular dependency.
+ return map.prefix ? this.callPlugin() : this.load();
+ }
+ },
+
+ load: function () {
+ var url = this.map.url;
+
+ //Regular dependency.
+ if (!urlFetched[url]) {
+ urlFetched[url] = true;
+ context.load(this.map.id, url);
+ }
+ },
+
+ /**
+ * Checks if the module is ready to define itself, and if so,
+ * define it.
+ */
+ check: function () {
+ if (!this.enabled || this.enabling) {
+ return;
+ }
+
+ var err, cjsModule,
+ id = this.map.id,
+ depExports = this.depExports,
+ exports = this.exports,
+ factory = this.factory;
+
+ if (!this.inited) {
+ this.fetch();
+ } else if (this.error) {
+ this.emit('error', this.error);
+ } else if (!this.defining) {
+ //The factory could trigger another require call
+ //that would result in checking this module to
+ //define itself again. If already in the process
+ //of doing that, skip this work.
+ this.defining = true;
+
+ if (this.depCount < 1 && !this.defined) {
+ if (isFunction(factory)) {
+ //If there is an error listener, favor passing
+ //to that instead of throwing an error. However,
+ //only do it for define()'d modules. require
+ //errbacks should not be called for failures in
+ //their callbacks (#699). However if a global
+ //onError is set, use that.
+ if ((this.events.error && this.map.isDefine) ||
+ req.onError !== defaultOnError) {
+ try {
+ exports = context.execCb(id, factory, depExports, exports);
+ } catch (e) {
+ err = e;
+ }
+ } else {
+ exports = context.execCb(id, factory, depExports, exports);
+ }
+
+ // Favor return value over exports. If node/cjs in play,
+ // then will not have a return value anyway. Favor
+ // module.exports assignment over exports object.
+ if (this.map.isDefine && exports === undefined) {
+ cjsModule = this.module;
+ if (cjsModule) {
+ exports = cjsModule.exports;
+ } else if (this.usingExports) {
+ //exports already set the defined value.
+ exports = this.exports;
+ }
+ }
+
+ if (err) {
+ err.requireMap = this.map;
+ err.requireModules = this.map.isDefine ? [this.map.id] : null;
+ err.requireType = this.map.isDefine ? 'define' : 'require';
+ return onError((this.error = err));
+ }
+
+ } else {
+ //Just a literal value
+ exports = factory;
+ }
+
+ this.exports = exports;
+
+ if (this.map.isDefine && !this.ignore) {
+ defined[id] = exports;
+
+ if (req.onResourceLoad) {
+ req.onResourceLoad(context, this.map, this.depMaps);
+ }
+ }
+
+ //Clean up
+ cleanRegistry(id);
+
+ this.defined = true;
+ }
+
+ //Finished the define stage. Allow calling check again
+ //to allow define notifications below in the case of a
+ //cycle.
+ this.defining = false;
+
+ if (this.defined && !this.defineEmitted) {
+ this.defineEmitted = true;
+ this.emit('defined', this.exports);
+ this.defineEmitComplete = true;
+ }
+
+ }
+ },
+
+ callPlugin: function () {
+ var map = this.map,
+ id = map.id,
+ //Map already normalized the prefix.
+ pluginMap = makeModuleMap(map.prefix);
+
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(pluginMap);
+
+ on(pluginMap, 'defined', bind(this, function (plugin) {
+ var load, normalizedMap, normalizedMod,
+ bundleId = getOwn(bundlesMap, this.map.id),
+ name = this.map.name,
+ parentName = this.map.parentMap ? this.map.parentMap.name : null,
+ localRequire = context.makeRequire(map.parentMap, {
+ enableBuildCallback: true
+ });
+
+ //If current map is not normalized, wait for that
+ //normalized name to load instead of continuing.
+ if (this.map.unnormalized) {
+ //Normalize the ID if the plugin allows it.
+ if (plugin.normalize) {
+ name = plugin.normalize(name, function (name) {
+ return normalize(name, parentName, true);
+ }) || '';
+ }
+
+ //prefix and name should already be normalized, no need
+ //for applying map config again either.
+ normalizedMap = makeModuleMap(map.prefix + '!' + name,
+ this.map.parentMap);
+ on(normalizedMap,
+ 'defined', bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true,
+ ignore: true
+ });
+ }));
+
+ normalizedMod = getOwn(registry, normalizedMap.id);
+ if (normalizedMod) {
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(normalizedMap);
+
+ if (this.events.error) {
+ normalizedMod.on('error', bind(this, function (err) {
+ this.emit('error', err);
+ }));
+ }
+ normalizedMod.enable();
+ }
+
+ return;
+ }
+
+ //If a paths config, then just load that file instead to
+ //resolve the plugin, as it is built into that paths layer.
+ if (bundleId) {
+ this.map.url = context.nameToUrl(bundleId);
+ this.load();
+ return;
+ }
+
+ load = bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true
+ });
+ });
+
+ load.error = bind(this, function (err) {
+ this.inited = true;
+ this.error = err;
+ err.requireModules = [id];
+
+ //Remove temp unnormalized modules for this module,
+ //since they will never be resolved otherwise now.
+ eachProp(registry, function (mod) {
+ if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
+ cleanRegistry(mod.map.id);
+ }
+ });
+
+ onError(err);
+ });
+
+ //Allow plugins to load other code without having to know the
+ //context or how to 'complete' the load.
+ load.fromText = bind(this, function (text, textAlt) {
+ /*jslint evil: true */
+ var moduleName = map.name,
+ moduleMap = makeModuleMap(moduleName),
+ hasInteractive = useInteractive;
+
+ //As of 2.1.0, support just passing the text, to reinforce
+ //fromText only being called once per resource. Still
+ //support old style of passing moduleName but discard
+ //that moduleName in favor of the internal ref.
+ if (textAlt) {
+ text = textAlt;
+ }
+
+ //Turn off interactive script matching for IE for any define
+ //calls in the text, then turn it back on at the end.
+ if (hasInteractive) {
+ useInteractive = false;
+ }
+
+ //Prime the system by creating a module instance for
+ //it.
+ getModule(moduleMap);
+
+ //Transfer any config to this other module.
+ if (hasProp(config.config, id)) {
+ config.config[moduleName] = config.config[id];
+ }
+
+ try {
+ req.exec(text);
+ } catch (e) {
+ return onError(makeError('fromtexteval',
+ 'fromText eval for ' + id +
+ ' failed: ' + e,
+ e,
+ [id]));
+ }
+
+ if (hasInteractive) {
+ useInteractive = true;
+ }
+
+ //Mark this as a dependency for the plugin
+ //resource
+ this.depMaps.push(moduleMap);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+
+ //Bind the value of that module to the value for this
+ //resource ID.
+ localRequire([moduleName], load);
+ });
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugin.load(map.name, localRequire, load, config);
+ }));
+
+ context.enable(pluginMap, this);
+ this.pluginMaps[pluginMap.id] = pluginMap;
+ },
+
+ enable: function () {
+ enabledRegistry[this.map.id] = this;
+ this.enabled = true;
+
+ //Set flag mentioning that the module is enabling,
+ //so that immediate calls to the defined callbacks
+ //for dependencies do not trigger inadvertent load
+ //with the depCount still being zero.
+ this.enabling = true;
+
+ //Enable each dependency
+ each(this.depMaps, bind(this, function (depMap, i) {
+ var id, mod, handler;
+
+ if (typeof depMap === 'string') {
+ //Dependency needs to be converted to a depMap
+ //and wired up to this module.
+ depMap = makeModuleMap(depMap,
+ (this.map.isDefine ? this.map : this.map.parentMap),
+ false,
+ !this.skipMap);
+ this.depMaps[i] = depMap;
+
+ handler = getOwn(handlers, depMap.id);
+
+ if (handler) {
+ this.depExports[i] = handler(this);
+ return;
+ }
+
+ this.depCount += 1;
+
+ on(depMap, 'defined', bind(this, function (depExports) {
+ this.defineDep(i, depExports);
+ this.check();
+ }));
+
+ if (this.errback) {
+ on(depMap, 'error', bind(this, this.errback));
+ }
+ }
+
+ id = depMap.id;
+ mod = registry[id];
+
+ //Skip special modules like 'require', 'exports', 'module'
+ //Also, don't call enable if it is already enabled,
+ //important in circular dependency cases.
+ if (!hasProp(handlers, id) && mod && !mod.enabled) {
+ context.enable(depMap, this);
+ }
+ }));
+
+ //Enable each plugin that is used in
+ //a dependency
+ eachProp(this.pluginMaps, bind(this, function (pluginMap) {
+ var mod = getOwn(registry, pluginMap.id);
+ if (mod && !mod.enabled) {
+ context.enable(pluginMap, this);
+ }
+ }));
+
+ this.enabling = false;
+
+ this.check();
+ },
+
+ on: function (name, cb) {
+ var cbs = this.events[name];
+ if (!cbs) {
+ cbs = this.events[name] = [];
+ }
+ cbs.push(cb);
+ },
+
+ emit: function (name, evt) {
+ each(this.events[name], function (cb) {
+ cb(evt);
+ });
+ if (name === 'error') {
+ //Now that the error handler was triggered, remove
+ //the listeners, since this broken Module instance
+ //can stay around for a while in the registry.
+ delete this.events[name];
+ }
+ }
+ };
+
+ function callGetModule(args) {
+ //Skip modules already defined.
+ if (!hasProp(defined, args[0])) {
+ getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
+ }
+ }
+
+ function removeListener(node, func, name, ieName) {
+ //Favor detachEvent because of IE9
+ //issue, see attachEvent/addEventListener comment elsewhere
+ //in this file.
+ if (node.detachEvent && !isOpera) {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ if (ieName) {
+ node.detachEvent(ieName, func);
+ }
+ } else {
+ node.removeEventListener(name, func, false);
+ }
+ }
+
+ /**
+ * Given an event from a script node, get the requirejs info from it,
+ * and then removes the event listeners on the node.
+ * @param {Event} evt
+ * @returns {Object}
+ */
+ function getScriptData(evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement;
+
+ //Remove the listeners once here.
+ removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
+ removeListener(node, context.onScriptError, 'error');
+
+ return {
+ node: node,
+ id: node && node.getAttribute('data-requiremodule')
+ };
+ }
+
+ function intakeDefines() {
+ var args;
+
+ //Any defined modules in the global queue, intake them now.
+ takeGlobalQueue();
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
+ } else {
+ //args are id, deps, factory. Should be normalized by the
+ //define() function.
+ callGetModule(args);
+ }
+ }
+ }
+
+ context = {
+ config: config,
+ contextName: contextName,
+ registry: registry,
+ defined: defined,
+ urlFetched: urlFetched,
+ defQueue: defQueue,
+ Module: Module,
+ makeModuleMap: makeModuleMap,
+ nextTick: req.nextTick,
+ onError: onError,
+
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
+ cfg.baseUrl += '/';
+ }
+ }
+
+ //Save off the paths since they require special processing,
+ //they are additive.
+ var shim = config.shim,
+ objs = {
+ paths: true,
+ bundles: true,
+ config: true,
+ map: true
+ };
+
+ eachProp(cfg, function (value, prop) {
+ if (objs[prop]) {
+ if (!config[prop]) {
+ config[prop] = {};
+ }
+ mixin(config[prop], value, true, true);
+ } else {
+ config[prop] = value;
+ }
+ });
+
+ //Reverse map the bundles
+ if (cfg.bundles) {
+ eachProp(cfg.bundles, function (value, prop) {
+ each(value, function (v) {
+ if (v !== prop) {
+ bundlesMap[v] = prop;
+ }
+ });
+ });
+ }
+
+ //Merge shim
+ if (cfg.shim) {
+ eachProp(cfg.shim, function (value, id) {
+ //Normalize the structure
+ if (isArray(value)) {
+ value = {
+ deps: value
+ };
+ }
+ if ((value.exports || value.init) && !value.exportsFn) {
+ value.exportsFn = context.makeShimExports(value);
+ }
+ shim[id] = value;
+ });
+ config.shim = shim;
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ each(cfg.packages, function (pkgObj) {
+ var location, name;
+
+ pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
+
+ name = pkgObj.name;
+ location = pkgObj.location;
+ if (location) {
+ config.paths[name] = pkgObj.location;
+ }
+
+ //Save pointer to main module ID for pkg name.
+ //Remove leading dot in main, so main paths are normalized,
+ //and remove any trailing .js, since different package
+ //envs have different conventions: some use a module name,
+ //some use a file name.
+ config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
+ .replace(currDirRegExp, '')
+ .replace(jsSuffixRegExp, '');
+ });
+ }
+
+ //If there are any "waiting to execute" modules in the registry,
+ //update the maps for them, since their info, like URLs to load,
+ //may have changed.
+ eachProp(registry, function (mod, id) {
+ //If module already has init called, since it is too
+ //late to modify them, and ignore unnormalized ones
+ //since they are transient.
+ if (!mod.inited && !mod.map.unnormalized) {
+ mod.map = makeModuleMap(id);
+ }
+ });
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback);
+ }
+ },
+
+ makeShimExports: function (value) {
+ function fn() {
+ var ret;
+ if (value.init) {
+ ret = value.init.apply(global, arguments);
+ }
+ return ret || (value.exports && getGlobal(value.exports));
+ }
+ return fn;
+ },
+
+ makeRequire: function (relMap, options) {
+ options = options || {};
+
+ function localRequire(deps, callback, errback) {
+ var id, map, requireMod;
+
+ if (options.enableBuildCallback && callback && isFunction(callback)) {
+ callback.__requireJsBuild = true;
+ }
+
+ if (typeof deps === 'string') {
+ if (isFunction(callback)) {
+ //Invalid call
+ return onError(makeError('requireargs', 'Invalid require call'), errback);
+ }
+
+ //If require|exports|module are requested, get the
+ //value for them from the special handlers. Caveat:
+ //this only works while module is being defined.
+ if (relMap && hasProp(handlers, deps)) {
+ return handlers[deps](registry[relMap.id]);
+ }
+
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ if (req.get) {
+ return req.get(context, deps, relMap, localRequire);
+ }
+
+ //Normalize module name, if it contains . or ..
+ map = makeModuleMap(deps, relMap, false, true);
+ id = map.id;
+
+ if (!hasProp(defined, id)) {
+ return onError(makeError('notloaded', 'Module name "' +
+ id +
+ '" has not been loaded yet for context: ' +
+ contextName +
+ (relMap ? '' : '. Use require([])')));
+ }
+ return defined[id];
+ }
+
+ //Grab defines waiting in the global queue.
+ intakeDefines();
+
+ //Mark all the dependencies as needing to be loaded.
+ context.nextTick(function () {
+ //Some defines could have been added since the
+ //require call, collect them.
+ intakeDefines();
+
+ requireMod = getModule(makeModuleMap(null, relMap));
+
+ //Store if map config should be applied to this require
+ //call for dependencies.
+ requireMod.skipMap = options.skipMap;
+
+ requireMod.init(deps, callback, errback, {
+ enabled: true
+ });
+
+ checkLoaded();
+ });
+
+ return localRequire;
+ }
+
+ mixin(localRequire, {
+ isBrowser: isBrowser,
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt) {
+ var ext,
+ index = moduleNamePlusExt.lastIndexOf('.'),
+ segment = moduleNamePlusExt.split('/')[0],
+ isRelative = segment === '.' || segment === '..';
+
+ //Have a file extension alias, and it is not the
+ //dots from a relative path.
+ if (index !== -1 && (!isRelative || index > 1)) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
+ }
+
+ return context.nameToUrl(normalize(moduleNamePlusExt,
+ relMap && relMap.id, true), ext, true);
+ },
+
+ defined: function (id) {
+ return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
+ },
+
+ specified: function (id) {
+ id = makeModuleMap(id, relMap, false, true).id;
+ return hasProp(defined, id) || hasProp(registry, id);
+ }
+ });
+
+ //Only allow undef on top level require calls
+ if (!relMap) {
+ localRequire.undef = function (id) {
+ //Bind any waiting define() calls to this context,
+ //fix for #408
+ takeGlobalQueue();
+
+ var map = makeModuleMap(id, relMap, true),
+ mod = getOwn(registry, id);
+
+ removeScript(id);
+
+ delete defined[id];
+ delete urlFetched[map.url];
+ delete undefEvents[id];
+
+ //Clean queued defines too. Go backwards
+ //in array so that the splices do not
+ //mess up the iteration.
+ eachReverse(defQueue, function(args, i) {
+ if(args[0] === id) {
+ defQueue.splice(i, 1);
+ }
+ });
+
+ if (mod) {
+ //Hold on to listeners in case the
+ //module will be attempted to be reloaded
+ //using a different config.
+ if (mod.events.defined) {
+ undefEvents[id] = mod.events;
+ }
+
+ cleanRegistry(id);
+ }
+ };
+ }
+
+ return localRequire;
+ },
+
+ /**
+ * Called to enable a module if it is still in the registry
+ * awaiting enablement. A second arg, parent, the parent module,
+ * is passed in for context, when this method is overridden by
+ * the optimizer. Not shown here to keep code compact.
+ */
+ enable: function (depMap) {
+ var mod = getOwn(registry, depMap.id);
+ if (mod) {
+ getModule(depMap).enable();
+ }
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var found, args, mod,
+ shim = getOwn(config.shim, moduleName) || {},
+ shExports = shim.exports;
+
+ takeGlobalQueue();
+
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ args[0] = moduleName;
+ //If already found an anonymous module and bound it
+ //to this name, then this is some other anon module
+ //waiting for its completeLoad to fire.
+ if (found) {
+ break;
+ }
+ found = true;
+ } else if (args[0] === moduleName) {
+ //Found matching define call for this script!
+ found = true;
+ }
+
+ callGetModule(args);
+ }
+
+ //Do this after the cycle of callGetModule in case the result
+ //of those calls/init calls changes the registry.
+ mod = getOwn(registry, moduleName);
+
+ if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
+ if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
+ if (hasPathFallback(moduleName)) {
+ return;
+ } else {
+ return onError(makeError('nodefine',
+ 'No define call for ' + moduleName,
+ null,
+ [moduleName]));
+ }
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it.
+ callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
+ }
+ }
+
+ checkLoaded();
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ * Note that it **does not** call normalize on the moduleName,
+ * it is assumed to have already been normalized. This is an
+ * internal API, not a public one. Use toUrl for the public API.
+ */
+ nameToUrl: function (moduleName, ext, skipExt) {
+ var paths, syms, i, parentModule, url,
+ parentPath, bundleId,
+ pkgMain = getOwn(config.pkgs, moduleName);
+
+ if (pkgMain) {
+ moduleName = pkgMain;
+ }
+
+ bundleId = getOwn(bundlesMap, moduleName);
+
+ if (bundleId) {
+ return context.nameToUrl(bundleId, ext, skipExt);
+ }
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
+ //or ends with .js, then assume the user meant to use an url and not a module id.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext || '');
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths;
+
+ syms = moduleName.split('/');
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i -= 1) {
+ parentModule = syms.slice(0, i).join('/');
+
+ parentPath = getOwn(paths, parentModule);
+ if (parentPath) {
+ //If an array, it means there are a few choices,
+ //Choose the one that is desired
+ if (isArray(parentPath)) {
+ parentPath = parentPath[0];
+ }
+ syms.splice(0, i, parentPath);
+ break;
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join('/');
+ url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
+ url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
+ }
+
+ return config.urlArgs ? url +
+ ((url.indexOf('?') === -1 ? '?' : '&') +
+ config.urlArgs) : url;
+ },
+
+ //Delegates to req.load. Broken out as a separate function to
+ //allow overriding in the optimizer.
+ load: function (id, url) {
+ req.load(context, id, url);
+ },
+
+ /**
+ * Executes a module callback function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ execCb: function (name, callback, args, exports) {
+ return callback.apply(exports, args);
+ },
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ */
+ onScriptLoad: function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ if (evt.type === 'load' ||
+ (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null;
+
+ //Pull out the name of the module and the context.
+ var data = getScriptData(evt);
+ context.completeLoad(data.id);
+ }
+ },
+
+ /**
+ * Callback for script errors.
+ */
+ onScriptError: function (evt) {
+ var data = getScriptData(evt);
+ if (!hasPathFallback(data.id)) {
+ return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
+ }
+ }
+ };
+
+ context.require = context.makeRequire();
+ return context;
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = requirejs = function (deps, callback, errback, optional) {
+
+ //Find the right context, use default
+ var context, config,
+ contextName = defContextName;
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== 'string') {
+ // deps is a config object
+ config = deps;
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback;
+ callback = errback;
+ errback = optional;
+ } else {
+ deps = [];
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context;
+ }
+
+ context = getOwn(contexts, contextName);
+ if (!context) {
+ context = contexts[contextName] = req.s.newContext(contextName);
+ }
+
+ if (config) {
+ context.configure(config);
+ }
+
+ return context.require(deps, callback, errback);
+ };
+
+ /**
+ * Support require.config() to make it easier to cooperate with other
+ * AMD loaders on globally agreed names.
+ */
+ req.config = function (config) {
+ return req(config);
+ };
+
+ /**
+ * Execute something after the current tick
+ * of the event loop. Override for other envs
+ * that have a better solution than setTimeout.
+ * @param {Function} fn function to execute later.
+ */
+ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
+ setTimeout(fn, 4);
+ } : function (fn) { fn(); };
+
+ /**
+ * Export require as a global, but only if it does not already exist.
+ */
+ if (!require) {
+ require = req;
+ }
+
+ req.version = version;
+
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/;
+ req.isBrowser = isBrowser;
+ s = req.s = {
+ contexts: contexts,
+ newContext: newContext
+ };
+
+ //Create default context.
+ req({});
+
+ //Exports some context-sensitive methods on global require.
+ each([
+ 'toUrl',
+ 'undef',
+ 'defined',
+ 'specified'
+ ], function (prop) {
+ //Reference from contexts instead of early binding to default context,
+ //so that during builds, the latest instance of the default context
+ //with its config gets used.
+ req[prop] = function () {
+ var ctx = contexts[defContextName];
+ return ctx.require[prop].apply(ctx, arguments);
+ };
+ });
+
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName('head')[0];
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName('base')[0];
+ if (baseElement) {
+ head = s.head = baseElement.parentNode;
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = defaultOnError;
+
+ /**
+ * Creates the node for the load command. Only used in browser envs.
+ */
+ req.createNode = function (config, moduleName, url) {
+ var node = config.xhtml ?
+ document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
+ document.createElement('script');
+ node.type = config.scriptType || 'text/javascript';
+ node.charset = 'utf-8';
+ node.async = true;
+ return node;
+ };
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ * @param {Object} url the URL to the module.
+ */
+ req.load = function (context, moduleName, url) {
+ var config = (context && context.config) || {},
+ node;
+ if (isBrowser) {
+ //In the browser so use a script tag
+ node = req.createNode(config, moduleName, url);
+
+ node.setAttribute('data-requirecontext', context.contextName);
+ node.setAttribute('data-requiremodule', moduleName);
+
+ //Set up load listener. Test attachEvent first because IE9 has
+ //a subtle issue in its addEventListener and script onload firings
+ //that do not match the behavior of all other browsers with
+ //addEventListener support, which fire the onload event for a
+ //script right after the script execution. See:
+ //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
+ //UNFORTUNATELY Opera implements attachEvent but does not follow the script
+ //script execution mode.
+ if (node.attachEvent &&
+ //Check if node.attachEvent is artificially added by custom script or
+ //natively supported by browser
+ //read https://github.com/jrburke/requirejs/issues/187
+ //if we can NOT find [native code] then it must NOT natively supported.
+ //in IE8, node.attachEvent does not have toString()
+ //Note the test for "[native code" with no closing brace, see:
+ //https://github.com/jrburke/requirejs/issues/273
+ !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
+ !isOpera) {
+ //Probably IE. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous define call to a name.
+ //However, IE reports the script as being in 'interactive'
+ //readyState at the time of the define call.
+ useInteractive = true;
+
+ node.attachEvent('onreadystatechange', context.onScriptLoad);
+ //It would be great to add an error handler here to catch
+ //404s in IE9+. However, onreadystatechange will fire before
+ //the error handler, so that does not help. If addEventListener
+ //is used, then IE will fire error before load, but we cannot
+ //use that pathway given the connect.microsoft.com issue
+ //mentioned above about not doing the 'script execute,
+ //then fire the script load event listener before execute
+ //next script' that other browsers do.
+ //Best hope: IE10 fixes the issues,
+ //and then destroys all installs of IE 6-9.
+ //node.attachEvent('onerror', context.onScriptError);
+ } else {
+ node.addEventListener('load', context.onScriptLoad, false);
+ node.addEventListener('error', context.onScriptError, false);
+ }
+ node.src = url;
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous define
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node;
+ if (baseElement) {
+ head.insertBefore(node, baseElement);
+ } else {
+ head.appendChild(node);
+ }
+ currentlyAddingScript = null;
+
+ return node;
+ } else if (isWebWorker) {
+ try {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ importScripts(url);
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName);
+ } catch (e) {
+ context.onError(makeError('importscripts',
+ 'importScripts failed for ' +
+ moduleName + ' at ' + url,
+ e,
+ [moduleName]));
+ }
+ }
+ };
+
+ function getInteractiveScript() {
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript;
+ }
+
+ eachReverse(scripts(), function (script) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script);
+ }
+ });
+ return interactiveScript;
+ }
+
+ //Look for a data-main script attribute, which could also adjust the baseUrl.
+ if (isBrowser && !cfg.skipDataMain) {
+ //Figure out baseUrl. Get it from the script tag with require.js in it.
+ eachReverse(scripts(), function (script) {
+ //Set the 'head' where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode;
+ }
+
+ //Look for a data-main attribute to set main script for the page
+ //to load. If it is there, the path to data main becomes the
+ //baseUrl, if it is not already set.
+ dataMain = script.getAttribute('data-main');
+ if (dataMain) {
+ //Preserve dataMain in case it is a path (i.e. contains '?')
+ mainScript = dataMain;
+
+ //Set final baseUrl if there is not already an explicit one.
+ if (!cfg.baseUrl) {
+ //Pull off the directory of data-main for use as the
+ //baseUrl.
+ src = mainScript.split('/');
+ mainScript = src.pop();
+ subPath = src.length ? src.join('/') + '/' : './';
+
+ cfg.baseUrl = subPath;
+ }
+
+ //Strip off any trailing .js since mainScript is now
+ //like a module name.
+ mainScript = mainScript.replace(jsSuffixRegExp, '');
+
+ //If mainScript is still a path, fall back to dataMain
+ if (req.jsExtRegExp.test(mainScript)) {
+ mainScript = dataMain;
+ }
+
+ //Put the data-main script in the files to load.
+ cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
+
+ return true;
+ }
+ });
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = function (name, deps, callback) {
+ var node, context;
+
+ //Allow for anonymous modules
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps;
+ deps = name;
+ name = null;
+ }
+
+ //This module may not have dependencies
+ if (!isArray(deps)) {
+ callback = deps;
+ deps = null;
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!deps && isFunction(callback)) {
+ deps = [];
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, '')
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep);
+ });
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and module. Avoid doing exports and module
+ //work though if it just needs require.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript();
+ if (node) {
+ if (!name) {
+ name = node.getAttribute('data-requiremodule');
+ }
+ context = contexts[node.getAttribute('data-requirecontext')];
+ }
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
+ };
+
+ define.amd = {
+ jQuery: true
+ };
+
+
+ /**
+ * Executes the text. Normally just uses eval, but can be modified
+ * to use a better, environment-specific call. Only used for transpiling
+ * loader plugins, not for plain JS modules.
+ * @param {String} text the text to execute/evaluate.
+ */
+ req.exec = function (text) {
+ /*jslint evil: true */
+ return eval(text);
+ };
+
+ //Set up with config info.
+ req(cfg);
+}(this));
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/server/python/django/renkanmanager/static/renkanmanager/lib/underscore/underscore.js Mon Dec 22 12:36:32 2014 +0100
@@ -0,0 +1,1415 @@
+// Underscore.js 1.7.0
+// http://underscorejs.org
+// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+// Underscore may be freely distributed under the MIT license.
+
+(function() {
+
+ // Baseline setup
+ // --------------
+
+ // Establish the root object, `window` in the browser, or `exports` on the server.
+ var root = this;
+
+ // Save the previous value of the `_` variable.
+ var previousUnderscore = root._;
+
+ // Save bytes in the minified (but not gzipped) version:
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
+
+ // Create quick reference variables for speed access to core prototypes.
+ var
+ push = ArrayProto.push,
+ slice = ArrayProto.slice,
+ concat = ArrayProto.concat,
+ toString = ObjProto.toString,
+ hasOwnProperty = ObjProto.hasOwnProperty;
+
+ // All **ECMAScript 5** native function implementations that we hope to use
+ // are declared here.
+ var
+ nativeIsArray = Array.isArray,
+ nativeKeys = Object.keys,
+ nativeBind = FuncProto.bind;
+
+ // Create a safe reference to the Underscore object for use below.
+ var _ = function(obj) {
+ if (obj instanceof _) return obj;
+ if (!(this instanceof _)) return new _(obj);
+ this._wrapped = obj;
+ };
+
+ // Export the Underscore object for **Node.js**, with
+ // backwards-compatibility for the old `require()` API. If we're in
+ // the browser, add `_` as a global object.
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports) {
+ exports = module.exports = _;
+ }
+ exports._ = _;
+ } else {
+ root._ = _;
+ }
+
+ // Current version.
+ _.VERSION = '1.7.0';
+
+ // Internal function that returns an efficient (for current engines) version
+ // of the passed-in callback, to be repeatedly applied in other Underscore
+ // functions.
+ var createCallback = function(func, context, argCount) {
+ if (context === void 0) return func;
+ switch (argCount == null ? 3 : argCount) {
+ case 1: return function(value) {
+ return func.call(context, value);
+ };
+ case 2: return function(value, other) {
+ return func.call(context, value, other);
+ };
+ case 3: return function(value, index, collection) {
+ return func.call(context, value, index, collection);
+ };
+ case 4: return function(accumulator, value, index, collection) {
+ return func.call(context, accumulator, value, index, collection);
+ };
+ }
+ return function() {
+ return func.apply(context, arguments);
+ };
+ };
+
+ // A mostly-internal function to generate callbacks that can be applied
+ // to each element in a collection, returning the desired result — either
+ // identity, an arbitrary callback, a property matcher, or a property accessor.
+ _.iteratee = function(value, context, argCount) {
+ if (value == null) return _.identity;
+ if (_.isFunction(value)) return createCallback(value, context, argCount);
+ if (_.isObject(value)) return _.matches(value);
+ return _.property(value);
+ };
+
+ // Collection Functions
+ // --------------------
+
+ // The cornerstone, an `each` implementation, aka `forEach`.
+ // Handles raw objects in addition to array-likes. Treats all
+ // sparse array-likes as if they were dense.
+ _.each = _.forEach = function(obj, iteratee, context) {
+ if (obj == null) return obj;
+ iteratee = createCallback(iteratee, context);
+ var i, length = obj.length;
+ if (length === +length) {
+ for (i = 0; i < length; i++) {
+ iteratee(obj[i], i, obj);
+ }
+ } else {
+ var keys = _.keys(obj);
+ for (i = 0, length = keys.length; i < length; i++) {
+ iteratee(obj[keys[i]], keys[i], obj);
+ }
+ }
+ return obj;
+ };
+
+ // Return the results of applying the iteratee to each element.
+ _.map = _.collect = function(obj, iteratee, context) {
+ if (obj == null) return [];
+ iteratee = _.iteratee(iteratee, context);
+ var keys = obj.length !== +obj.length && _.keys(obj),
+ length = (keys || obj).length,
+ results = Array(length),
+ currentKey;
+ for (var index = 0; index < length; index++) {
+ currentKey = keys ? keys[index] : index;
+ results[index] = iteratee(obj[currentKey], currentKey, obj);
+ }
+ return results;
+ };
+
+ var reduceError = 'Reduce of empty array with no initial value';
+
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
+ // or `foldl`.
+ _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {
+ if (obj == null) obj = [];
+ iteratee = createCallback(iteratee, context, 4);
+ var keys = obj.length !== +obj.length && _.keys(obj),
+ length = (keys || obj).length,
+ index = 0, currentKey;
+ if (arguments.length < 3) {
+ if (!length) throw new TypeError(reduceError);
+ memo = obj[keys ? keys[index++] : index++];
+ }
+ for (; index < length; index++) {
+ currentKey = keys ? keys[index] : index;
+ memo = iteratee(memo, obj[currentKey], currentKey, obj);
+ }
+ return memo;
+ };
+
+ // The right-associative version of reduce, also known as `foldr`.
+ _.reduceRight = _.foldr = function(obj, iteratee, memo, context) {
+ if (obj == null) obj = [];
+ iteratee = createCallback(iteratee, context, 4);
+ var keys = obj.length !== + obj.length && _.keys(obj),
+ index = (keys || obj).length,
+ currentKey;
+ if (arguments.length < 3) {
+ if (!index) throw new TypeError(reduceError);
+ memo = obj[keys ? keys[--index] : --index];
+ }
+ while (index--) {
+ currentKey = keys ? keys[index] : index;
+ memo = iteratee(memo, obj[currentKey], currentKey, obj);
+ }
+ return memo;
+ };
+
+ // Return the first value which passes a truth test. Aliased as `detect`.
+ _.find = _.detect = function(obj, predicate, context) {
+ var result;
+ predicate = _.iteratee(predicate, context);
+ _.some(obj, function(value, index, list) {
+ if (predicate(value, index, list)) {
+ result = value;
+ return true;
+ }
+ });
+ return result;
+ };
+
+ // Return all the elements that pass a truth test.
+ // Aliased as `select`.
+ _.filter = _.select = function(obj, predicate, context) {
+ var results = [];
+ if (obj == null) return results;
+ predicate = _.iteratee(predicate, context);
+ _.each(obj, function(value, index, list) {
+ if (predicate(value, index, list)) results.push(value);
+ });
+ return results;
+ };
+
+ // Return all the elements for which a truth test fails.
+ _.reject = function(obj, predicate, context) {
+ return _.filter(obj, _.negate(_.iteratee(predicate)), context);
+ };
+
+ // Determine whether all of the elements match a truth test.
+ // Aliased as `all`.
+ _.every = _.all = function(obj, predicate, context) {
+ if (obj == null) return true;
+ predicate = _.iteratee(predicate, context);
+ var keys = obj.length !== +obj.length && _.keys(obj),
+ length = (keys || obj).length,
+ index, currentKey;
+ for (index = 0; index < length; index++) {
+ currentKey = keys ? keys[index] : index;
+ if (!predicate(obj[currentKey], currentKey, obj)) return false;
+ }
+ return true;
+ };
+
+ // Determine if at least one element in the object matches a truth test.
+ // Aliased as `any`.
+ _.some = _.any = function(obj, predicate, context) {
+ if (obj == null) return false;
+ predicate = _.iteratee(predicate, context);
+ var keys = obj.length !== +obj.length && _.keys(obj),
+ length = (keys || obj).length,
+ index, currentKey;
+ for (index = 0; index < length; index++) {
+ currentKey = keys ? keys[index] : index;
+ if (predicate(obj[currentKey], currentKey, obj)) return true;
+ }
+ return false;
+ };
+
+ // Determine if the array or object contains a given value (using `===`).
+ // Aliased as `include`.
+ _.contains = _.include = function(obj, target) {
+ if (obj == null) return false;
+ if (obj.length !== +obj.length) obj = _.values(obj);
+ return _.indexOf(obj, target) >= 0;
+ };
+
+ // Invoke a method (with arguments) on every item in a collection.
+ _.invoke = function(obj, method) {
+ var args = slice.call(arguments, 2);
+ var isFunc = _.isFunction(method);
+ return _.map(obj, function(value) {
+ return (isFunc ? method : value[method]).apply(value, args);
+ });
+ };
+
+ // Convenience version of a common use case of `map`: fetching a property.
+ _.pluck = function(obj, key) {
+ return _.map(obj, _.property(key));
+ };
+
+ // Convenience version of a common use case of `filter`: selecting only objects
+ // containing specific `key:value` pairs.
+ _.where = function(obj, attrs) {
+ return _.filter(obj, _.matches(attrs));
+ };
+
+ // Convenience version of a common use case of `find`: getting the first object
+ // containing specific `key:value` pairs.
+ _.findWhere = function(obj, attrs) {
+ return _.find(obj, _.matches(attrs));
+ };
+
+ // Return the maximum element (or element-based computation).
+ _.max = function(obj, iteratee, context) {
+ var result = -Infinity, lastComputed = -Infinity,
+ value, computed;
+ if (iteratee == null && obj != null) {
+ obj = obj.length === +obj.length ? obj : _.values(obj);
+ for (var i = 0, length = obj.length; i < length; i++) {
+ value = obj[i];
+ if (value > result) {
+ result = value;
+ }
+ }
+ } else {
+ iteratee = _.iteratee(iteratee, context);
+ _.each(obj, function(value, index, list) {
+ computed = iteratee(value, index, list);
+ if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
+ result = value;
+ lastComputed = computed;
+ }
+ });
+ }
+ return result;
+ };
+
+ // Return the minimum element (or element-based computation).
+ _.min = function(obj, iteratee, context) {
+ var result = Infinity, lastComputed = Infinity,
+ value, computed;
+ if (iteratee == null && obj != null) {
+ obj = obj.length === +obj.length ? obj : _.values(obj);
+ for (var i = 0, length = obj.length; i < length; i++) {
+ value = obj[i];
+ if (value < result) {
+ result = value;
+ }
+ }
+ } else {
+ iteratee = _.iteratee(iteratee, context);
+ _.each(obj, function(value, index, list) {
+ computed = iteratee(value, index, list);
+ if (computed < lastComputed || computed === Infinity && result === Infinity) {
+ result = value;
+ lastComputed = computed;
+ }
+ });
+ }
+ return result;
+ };
+
+ // Shuffle a collection, using the modern version of the
+ // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
+ _.shuffle = function(obj) {
+ var set = obj && obj.length === +obj.length ? obj : _.values(obj);
+ var length = set.length;
+ var shuffled = Array(length);
+ for (var index = 0, rand; index < length; index++) {
+ rand = _.random(0, index);
+ if (rand !== index) shuffled[index] = shuffled[rand];
+ shuffled[rand] = set[index];
+ }
+ return shuffled;
+ };
+
+ // Sample **n** random values from a collection.
+ // If **n** is not specified, returns a single random element.
+ // The internal `guard` argument allows it to work with `map`.
+ _.sample = function(obj, n, guard) {
+ if (n == null || guard) {
+ if (obj.length !== +obj.length) obj = _.values(obj);
+ return obj[_.random(obj.length - 1)];
+ }
+ return _.shuffle(obj).slice(0, Math.max(0, n));
+ };
+
+ // Sort the object's values by a criterion produced by an iteratee.
+ _.sortBy = function(obj, iteratee, context) {
+ iteratee = _.iteratee(iteratee, context);
+ return _.pluck(_.map(obj, function(value, index, list) {
+ return {
+ value: value,
+ index: index,
+ criteria: iteratee(value, index, list)
+ };
+ }).sort(function(left, right) {
+ var a = left.criteria;
+ var b = right.criteria;
+ if (a !== b) {
+ if (a > b || a === void 0) return 1;
+ if (a < b || b === void 0) return -1;
+ }
+ return left.index - right.index;
+ }), 'value');
+ };
+
+ // An internal function used for aggregate "group by" operations.
+ var group = function(behavior) {
+ return function(obj, iteratee, context) {
+ var result = {};
+ iteratee = _.iteratee(iteratee, context);
+ _.each(obj, function(value, index) {
+ var key = iteratee(value, index, obj);
+ behavior(result, value, key);
+ });
+ return result;
+ };
+ };
+
+ // Groups the object's values by a criterion. Pass either a string attribute
+ // to group by, or a function that returns the criterion.
+ _.groupBy = group(function(result, value, key) {
+ if (_.has(result, key)) result[key].push(value); else result[key] = [value];
+ });
+
+ // Indexes the object's values by a criterion, similar to `groupBy`, but for
+ // when you know that your index values will be unique.
+ _.indexBy = group(function(result, value, key) {
+ result[key] = value;
+ });
+
+ // Counts instances of an object that group by a certain criterion. Pass
+ // either a string attribute to count by, or a function that returns the
+ // criterion.
+ _.countBy = group(function(result, value, key) {
+ if (_.has(result, key)) result[key]++; else result[key] = 1;
+ });
+
+ // Use a comparator function to figure out the smallest index at which
+ // an object should be inserted so as to maintain order. Uses binary search.
+ _.sortedIndex = function(array, obj, iteratee, context) {
+ iteratee = _.iteratee(iteratee, context, 1);
+ var value = iteratee(obj);
+ var low = 0, high = array.length;
+ while (low < high) {
+ var mid = low + high >>> 1;
+ if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
+ }
+ return low;
+ };
+
+ // Safely create a real, live array from anything iterable.
+ _.toArray = function(obj) {
+ if (!obj) return [];
+ if (_.isArray(obj)) return slice.call(obj);
+ if (obj.length === +obj.length) return _.map(obj, _.identity);
+ return _.values(obj);
+ };
+
+ // Return the number of elements in an object.
+ _.size = function(obj) {
+ if (obj == null) return 0;
+ return obj.length === +obj.length ? obj.length : _.keys(obj).length;
+ };
+
+ // Split a collection into two arrays: one whose elements all satisfy the given
+ // predicate, and one whose elements all do not satisfy the predicate.
+ _.partition = function(obj, predicate, context) {
+ predicate = _.iteratee(predicate, context);
+ var pass = [], fail = [];
+ _.each(obj, function(value, key, obj) {
+ (predicate(value, key, obj) ? pass : fail).push(value);
+ });
+ return [pass, fail];
+ };
+
+ // Array Functions
+ // ---------------
+
+ // Get the first element of an array. Passing **n** will return the first N
+ // values in the array. Aliased as `head` and `take`. The **guard** check
+ // allows it to work with `_.map`.
+ _.first = _.head = _.take = function(array, n, guard) {
+ if (array == null) return void 0;
+ if (n == null || guard) return array[0];
+ if (n < 0) return [];
+ return slice.call(array, 0, n);
+ };
+
+ // Returns everything but the last entry of the array. Especially useful on
+ // the arguments object. Passing **n** will return all the values in
+ // the array, excluding the last N. The **guard** check allows it to work with
+ // `_.map`.
+ _.initial = function(array, n, guard) {
+ return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
+ };
+
+ // Get the last element of an array. Passing **n** will return the last N
+ // values in the array. The **guard** check allows it to work with `_.map`.
+ _.last = function(array, n, guard) {
+ if (array == null) return void 0;
+ if (n == null || guard) return array[array.length - 1];
+ return slice.call(array, Math.max(array.length - n, 0));
+ };
+
+ // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
+ // Especially useful on the arguments object. Passing an **n** will return
+ // the rest N values in the array. The **guard**
+ // check allows it to work with `_.map`.
+ _.rest = _.tail = _.drop = function(array, n, guard) {
+ return slice.call(array, n == null || guard ? 1 : n);
+ };
+
+ // Trim out all falsy values from an array.
+ _.compact = function(array) {
+ return _.filter(array, _.identity);
+ };
+
+ // Internal implementation of a recursive `flatten` function.
+ var flatten = function(input, shallow, strict, output) {
+ if (shallow && _.every(input, _.isArray)) {
+ return concat.apply(output, input);
+ }
+ for (var i = 0, length = input.length; i < length; i++) {
+ var value = input[i];
+ if (!_.isArray(value) && !_.isArguments(value)) {
+ if (!strict) output.push(value);
+ } else if (shallow) {
+ push.apply(output, value);
+ } else {
+ flatten(value, shallow, strict, output);
+ }
+ }
+ return output;
+ };
+
+ // Flatten out an array, either recursively (by default), or just one level.
+ _.flatten = function(array, shallow) {
+ return flatten(array, shallow, false, []);
+ };
+
+ // Return a version of the array that does not contain the specified value(s).
+ _.without = function(array) {
+ return _.difference(array, slice.call(arguments, 1));
+ };
+
+ // Produce a duplicate-free version of the array. If the array has already
+ // been sorted, you have the option of using a faster algorithm.
+ // Aliased as `unique`.
+ _.uniq = _.unique = function(array, isSorted, iteratee, context) {
+ if (array == null) return [];
+ if (!_.isBoolean(isSorted)) {
+ context = iteratee;
+ iteratee = isSorted;
+ isSorted = false;
+ }
+ if (iteratee != null) iteratee = _.iteratee(iteratee, context);
+ var result = [];
+ var seen = [];
+ for (var i = 0, length = array.length; i < length; i++) {
+ var value = array[i];
+ if (isSorted) {
+ if (!i || seen !== value) result.push(value);
+ seen = value;
+ } else if (iteratee) {
+ var computed = iteratee(value, i, array);
+ if (_.indexOf(seen, computed) < 0) {
+ seen.push(computed);
+ result.push(value);
+ }
+ } else if (_.indexOf(result, value) < 0) {
+ result.push(value);
+ }
+ }
+ return result;
+ };
+
+ // Produce an array that contains the union: each distinct element from all of
+ // the passed-in arrays.
+ _.union = function() {
+ return _.uniq(flatten(arguments, true, true, []));
+ };
+
+ // Produce an array that contains every item shared between all the
+ // passed-in arrays.
+ _.intersection = function(array) {
+ if (array == null) return [];
+ var result = [];
+ var argsLength = arguments.length;
+ for (var i = 0, length = array.length; i < length; i++) {
+ var item = array[i];
+ if (_.contains(result, item)) continue;
+ for (var j = 1; j < argsLength; j++) {
+ if (!_.contains(arguments[j], item)) break;
+ }
+ if (j === argsLength) result.push(item);
+ }
+ return result;
+ };
+
+ // Take the difference between one array and a number of other arrays.
+ // Only the elements present in just the first array will remain.
+ _.difference = function(array) {
+ var rest = flatten(slice.call(arguments, 1), true, true, []);
+ return _.filter(array, function(value){
+ return !_.contains(rest, value);
+ });
+ };
+
+ // Zip together multiple lists into a single array -- elements that share
+ // an index go together.
+ _.zip = function(array) {
+ if (array == null) return [];
+ var length = _.max(arguments, 'length').length;
+ var results = Array(length);
+ for (var i = 0; i < length; i++) {
+ results[i] = _.pluck(arguments, i);
+ }
+ return results;
+ };
+
+ // Converts lists into objects. Pass either a single array of `[key, value]`
+ // pairs, or two parallel arrays of the same length -- one of keys, and one of
+ // the corresponding values.
+ _.object = function(list, values) {
+ if (list == null) return {};
+ var result = {};
+ for (var i = 0, length = list.length; i < length; i++) {
+ if (values) {
+ result[list[i]] = values[i];
+ } else {
+ result[list[i][0]] = list[i][1];
+ }
+ }
+ return result;
+ };
+
+ // Return the position of the first occurrence of an item in an array,
+ // or -1 if the item is not included in the array.
+ // If the array is large and already in sort order, pass `true`
+ // for **isSorted** to use binary search.
+ _.indexOf = function(array, item, isSorted) {
+ if (array == null) return -1;
+ var i = 0, length = array.length;
+ if (isSorted) {
+ if (typeof isSorted == 'number') {
+ i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
+ } else {
+ i = _.sortedIndex(array, item);
+ return array[i] === item ? i : -1;
+ }
+ }
+ for (; i < length; i++) if (array[i] === item) return i;
+ return -1;
+ };
+
+ _.lastIndexOf = function(array, item, from) {
+ if (array == null) return -1;
+ var idx = array.length;
+ if (typeof from == 'number') {
+ idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
+ }
+ while (--idx >= 0) if (array[idx] === item) return idx;
+ return -1;
+ };
+
+ // Generate an integer Array containing an arithmetic progression. A port of
+ // the native Python `range()` function. See
+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
+ _.range = function(start, stop, step) {
+ if (arguments.length <= 1) {
+ stop = start || 0;
+ start = 0;
+ }
+ step = step || 1;
+
+ var length = Math.max(Math.ceil((stop - start) / step), 0);
+ var range = Array(length);
+
+ for (var idx = 0; idx < length; idx++, start += step) {
+ range[idx] = start;
+ }
+
+ return range;
+ };
+
+ // Function (ahem) Functions
+ // ------------------
+
+ // Reusable constructor function for prototype setting.
+ var Ctor = function(){};
+
+ // Create a function bound to a given object (assigning `this`, and arguments,
+ // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
+ // available.
+ _.bind = function(func, context) {
+ var args, bound;
+ if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
+ if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
+ args = slice.call(arguments, 2);
+ bound = function() {
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
+ Ctor.prototype = func.prototype;
+ var self = new Ctor;
+ Ctor.prototype = null;
+ var result = func.apply(self, args.concat(slice.call(arguments)));
+ if (_.isObject(result)) return result;
+ return self;
+ };
+ return bound;
+ };
+
+ // Partially apply a function by creating a version that has had some of its
+ // arguments pre-filled, without changing its dynamic `this` context. _ acts
+ // as a placeholder, allowing any combination of arguments to be pre-filled.
+ _.partial = function(func) {
+ var boundArgs = slice.call(arguments, 1);
+ return function() {
+ var position = 0;
+ var args = boundArgs.slice();
+ for (var i = 0, length = args.length; i < length; i++) {
+ if (args[i] === _) args[i] = arguments[position++];
+ }
+ while (position < arguments.length) args.push(arguments[position++]);
+ return func.apply(this, args);
+ };
+ };
+
+ // Bind a number of an object's methods to that object. Remaining arguments
+ // are the method names to be bound. Useful for ensuring that all callbacks
+ // defined on an object belong to it.
+ _.bindAll = function(obj) {
+ var i, length = arguments.length, key;
+ if (length <= 1) throw new Error('bindAll must be passed function names');
+ for (i = 1; i < length; i++) {
+ key = arguments[i];
+ obj[key] = _.bind(obj[key], obj);
+ }
+ return obj;
+ };
+
+ // Memoize an expensive function by storing its results.
+ _.memoize = function(func, hasher) {
+ var memoize = function(key) {
+ var cache = memoize.cache;
+ var address = hasher ? hasher.apply(this, arguments) : key;
+ if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
+ return cache[address];
+ };
+ memoize.cache = {};
+ return memoize;
+ };
+
+ // Delays a function for the given number of milliseconds, and then calls
+ // it with the arguments supplied.
+ _.delay = function(func, wait) {
+ var args = slice.call(arguments, 2);
+ return setTimeout(function(){
+ return func.apply(null, args);
+ }, wait);
+ };
+
+ // Defers a function, scheduling it to run after the current call stack has
+ // cleared.
+ _.defer = function(func) {
+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
+ };
+
+ // Returns a function, that, when invoked, will only be triggered at most once
+ // during a given window of time. Normally, the throttled function will run
+ // as much as it can, without ever going more than once per `wait` duration;
+ // but if you'd like to disable the execution on the leading edge, pass
+ // `{leading: false}`. To disable execution on the trailing edge, ditto.
+ _.throttle = function(func, wait, options) {
+ var context, args, result;
+ var timeout = null;
+ var previous = 0;
+ if (!options) options = {};
+ var later = function() {
+ previous = options.leading === false ? 0 : _.now();
+ timeout = null;
+ result = func.apply(context, args);
+ if (!timeout) context = args = null;
+ };
+ return function() {
+ var now = _.now();
+ if (!previous && options.leading === false) previous = now;
+ var remaining = wait - (now - previous);
+ context = this;
+ args = arguments;
+ if (remaining <= 0 || remaining > wait) {
+ clearTimeout(timeout);
+ timeout = null;
+ previous = now;
+ result = func.apply(context, args);
+ if (!timeout) context = args = null;
+ } else if (!timeout && options.trailing !== false) {
+ timeout = setTimeout(later, remaining);
+ }
+ return result;
+ };
+ };
+
+ // Returns a function, that, as long as it continues to be invoked, will not
+ // be triggered. The function will be called after it stops being called for
+ // N milliseconds. If `immediate` is passed, trigger the function on the
+ // leading edge, instead of the trailing.
+ _.debounce = function(func, wait, immediate) {
+ var timeout, args, context, timestamp, result;
+
+ var later = function() {
+ var last = _.now() - timestamp;
+
+ if (last < wait && last > 0) {
+ timeout = setTimeout(later, wait - last);
+ } else {
+ timeout = null;
+ if (!immediate) {
+ result = func.apply(context, args);
+ if (!timeout) context = args = null;
+ }
+ }
+ };
+
+ return function() {
+ context = this;
+ args = arguments;
+ timestamp = _.now();
+ var callNow = immediate && !timeout;
+ if (!timeout) timeout = setTimeout(later, wait);
+ if (callNow) {
+ result = func.apply(context, args);
+ context = args = null;
+ }
+
+ return result;
+ };
+ };
+
+ // Returns the first function passed as an argument to the second,
+ // allowing you to adjust arguments, run code before and after, and
+ // conditionally execute the original function.
+ _.wrap = function(func, wrapper) {
+ return _.partial(wrapper, func);
+ };
+
+ // Returns a negated version of the passed-in predicate.
+ _.negate = function(predicate) {
+ return function() {
+ return !predicate.apply(this, arguments);
+ };
+ };
+
+ // Returns a function that is the composition of a list of functions, each
+ // consuming the return value of the function that follows.
+ _.compose = function() {
+ var args = arguments;
+ var start = args.length - 1;
+ return function() {
+ var i = start;
+ var result = args[start].apply(this, arguments);
+ while (i--) result = args[i].call(this, result);
+ return result;
+ };
+ };
+
+ // Returns a function that will only be executed after being called N times.
+ _.after = function(times, func) {
+ return function() {
+ if (--times < 1) {
+ return func.apply(this, arguments);
+ }
+ };
+ };
+
+ // Returns a function that will only be executed before being called N times.
+ _.before = function(times, func) {
+ var memo;
+ return function() {
+ if (--times > 0) {
+ memo = func.apply(this, arguments);
+ } else {
+ func = null;
+ }
+ return memo;
+ };
+ };
+
+ // Returns a function that will be executed at most one time, no matter how
+ // often you call it. Useful for lazy initialization.
+ _.once = _.partial(_.before, 2);
+
+ // Object Functions
+ // ----------------
+
+ // Retrieve the names of an object's properties.
+ // Delegates to **ECMAScript 5**'s native `Object.keys`
+ _.keys = function(obj) {
+ if (!_.isObject(obj)) return [];
+ if (nativeKeys) return nativeKeys(obj);
+ var keys = [];
+ for (var key in obj) if (_.has(obj, key)) keys.push(key);
+ return keys;
+ };
+
+ // Retrieve the values of an object's properties.
+ _.values = function(obj) {
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var values = Array(length);
+ for (var i = 0; i < length; i++) {
+ values[i] = obj[keys[i]];
+ }
+ return values;
+ };
+
+ // Convert an object into a list of `[key, value]` pairs.
+ _.pairs = function(obj) {
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var pairs = Array(length);
+ for (var i = 0; i < length; i++) {
+ pairs[i] = [keys[i], obj[keys[i]]];
+ }
+ return pairs;
+ };
+
+ // Invert the keys and values of an object. The values must be serializable.
+ _.invert = function(obj) {
+ var result = {};
+ var keys = _.keys(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ result[obj[keys[i]]] = keys[i];
+ }
+ return result;
+ };
+
+ // Return a sorted list of the function names available on the object.
+ // Aliased as `methods`
+ _.functions = _.methods = function(obj) {
+ var names = [];
+ for (var key in obj) {
+ if (_.isFunction(obj[key])) names.push(key);
+ }
+ return names.sort();
+ };
+
+ // Extend a given object with all the properties in passed-in object(s).
+ _.extend = function(obj) {
+ if (!_.isObject(obj)) return obj;
+ var source, prop;
+ for (var i = 1, length = arguments.length; i < length; i++) {
+ source = arguments[i];
+ for (prop in source) {
+ if (hasOwnProperty.call(source, prop)) {
+ obj[prop] = source[prop];
+ }
+ }
+ }
+ return obj;
+ };
+
+ // Return a copy of the object only containing the whitelisted properties.
+ _.pick = function(obj, iteratee, context) {
+ var result = {}, key;
+ if (obj == null) return result;
+ if (_.isFunction(iteratee)) {
+ iteratee = createCallback(iteratee, context);
+ for (key in obj) {
+ var value = obj[key];
+ if (iteratee(value, key, obj)) result[key] = value;
+ }
+ } else {
+ var keys = concat.apply([], slice.call(arguments, 1));
+ obj = new Object(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ key = keys[i];
+ if (key in obj) result[key] = obj[key];
+ }
+ }
+ return result;
+ };
+
+ // Return a copy of the object without the blacklisted properties.
+ _.omit = function(obj, iteratee, context) {
+ if (_.isFunction(iteratee)) {
+ iteratee = _.negate(iteratee);
+ } else {
+ var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);
+ iteratee = function(value, key) {
+ return !_.contains(keys, key);
+ };
+ }
+ return _.pick(obj, iteratee, context);
+ };
+
+ // Fill in a given object with default properties.
+ _.defaults = function(obj) {
+ if (!_.isObject(obj)) return obj;
+ for (var i = 1, length = arguments.length; i < length; i++) {
+ var source = arguments[i];
+ for (var prop in source) {
+ if (obj[prop] === void 0) obj[prop] = source[prop];
+ }
+ }
+ return obj;
+ };
+
+ // Create a (shallow-cloned) duplicate of an object.
+ _.clone = function(obj) {
+ if (!_.isObject(obj)) return obj;
+ return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
+ };
+
+ // Invokes interceptor with the obj, and then returns obj.
+ // The primary purpose of this method is to "tap into" a method chain, in
+ // order to perform operations on intermediate results within the chain.
+ _.tap = function(obj, interceptor) {
+ interceptor(obj);
+ return obj;
+ };
+
+ // Internal recursive comparison function for `isEqual`.
+ var eq = function(a, b, aStack, bStack) {
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
+ // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
+ if (a === b) return a !== 0 || 1 / a === 1 / b;
+ // A strict comparison is necessary because `null == undefined`.
+ if (a == null || b == null) return a === b;
+ // Unwrap any wrapped objects.
+ if (a instanceof _) a = a._wrapped;
+ if (b instanceof _) b = b._wrapped;
+ // Compare `[[Class]]` names.
+ var className = toString.call(a);
+ if (className !== toString.call(b)) return false;
+ switch (className) {
+ // Strings, numbers, regular expressions, dates, and booleans are compared by value.
+ case '[object RegExp]':
+ // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
+ case '[object String]':
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
+ // equivalent to `new String("5")`.
+ return '' + a === '' + b;
+ case '[object Number]':
+ // `NaN`s are equivalent, but non-reflexive.
+ // Object(NaN) is equivalent to NaN
+ if (+a !== +a) return +b !== +b;
+ // An `egal` comparison is performed for other numeric values.
+ return +a === 0 ? 1 / +a === 1 / b : +a === +b;
+ case '[object Date]':
+ case '[object Boolean]':
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
+ // millisecond representations. Note that invalid dates with millisecond representations
+ // of `NaN` are not equivalent.
+ return +a === +b;
+ }
+ if (typeof a != 'object' || typeof b != 'object') return false;
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
+ var length = aStack.length;
+ while (length--) {
+ // Linear search. Performance is inversely proportional to the number of
+ // unique nested structures.
+ if (aStack[length] === a) return bStack[length] === b;
+ }
+ // Objects with different constructors are not equivalent, but `Object`s
+ // from different frames are.
+ var aCtor = a.constructor, bCtor = b.constructor;
+ if (
+ aCtor !== bCtor &&
+ // Handle Object.create(x) cases
+ 'constructor' in a && 'constructor' in b &&
+ !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
+ _.isFunction(bCtor) && bCtor instanceof bCtor)
+ ) {
+ return false;
+ }
+ // Add the first object to the stack of traversed objects.
+ aStack.push(a);
+ bStack.push(b);
+ var size, result;
+ // Recursively compare objects and arrays.
+ if (className === '[object Array]') {
+ // Compare array lengths to determine if a deep comparison is necessary.
+ size = a.length;
+ result = size === b.length;
+ if (result) {
+ // Deep compare the contents, ignoring non-numeric properties.
+ while (size--) {
+ if (!(result = eq(a[size], b[size], aStack, bStack))) break;
+ }
+ }
+ } else {
+ // Deep compare objects.
+ var keys = _.keys(a), key;
+ size = keys.length;
+ // Ensure that both objects contain the same number of properties before comparing deep equality.
+ result = _.keys(b).length === size;
+ if (result) {
+ while (size--) {
+ // Deep compare each member
+ key = keys[size];
+ if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
+ }
+ }
+ }
+ // Remove the first object from the stack of traversed objects.
+ aStack.pop();
+ bStack.pop();
+ return result;
+ };
+
+ // Perform a deep comparison to check if two objects are equal.
+ _.isEqual = function(a, b) {
+ return eq(a, b, [], []);
+ };
+
+ // Is a given array, string, or object empty?
+ // An "empty" object has no enumerable own-properties.
+ _.isEmpty = function(obj) {
+ if (obj == null) return true;
+ if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;
+ for (var key in obj) if (_.has(obj, key)) return false;
+ return true;
+ };
+
+ // Is a given value a DOM element?
+ _.isElement = function(obj) {
+ return !!(obj && obj.nodeType === 1);
+ };
+
+ // Is a given value an array?
+ // Delegates to ECMA5's native Array.isArray
+ _.isArray = nativeIsArray || function(obj) {
+ return toString.call(obj) === '[object Array]';
+ };
+
+ // Is a given variable an object?
+ _.isObject = function(obj) {
+ var type = typeof obj;
+ return type === 'function' || type === 'object' && !!obj;
+ };
+
+ // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
+ _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
+ _['is' + name] = function(obj) {
+ return toString.call(obj) === '[object ' + name + ']';
+ };
+ });
+
+ // Define a fallback version of the method in browsers (ahem, IE), where
+ // there isn't any inspectable "Arguments" type.
+ if (!_.isArguments(arguments)) {
+ _.isArguments = function(obj) {
+ return _.has(obj, 'callee');
+ };
+ }
+
+ // Optimize `isFunction` if appropriate. Work around an IE 11 bug.
+ if (typeof /./ !== 'function') {
+ _.isFunction = function(obj) {
+ return typeof obj == 'function' || false;
+ };
+ }
+
+ // Is a given object a finite number?
+ _.isFinite = function(obj) {
+ return isFinite(obj) && !isNaN(parseFloat(obj));
+ };
+
+ // Is the given value `NaN`? (NaN is the only number which does not equal itself).
+ _.isNaN = function(obj) {
+ return _.isNumber(obj) && obj !== +obj;
+ };
+
+ // Is a given value a boolean?
+ _.isBoolean = function(obj) {
+ return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
+ };
+
+ // Is a given value equal to null?
+ _.isNull = function(obj) {
+ return obj === null;
+ };
+
+ // Is a given variable undefined?
+ _.isUndefined = function(obj) {
+ return obj === void 0;
+ };
+
+ // Shortcut function for checking if an object has a given property directly
+ // on itself (in other words, not on a prototype).
+ _.has = function(obj, key) {
+ return obj != null && hasOwnProperty.call(obj, key);
+ };
+
+ // Utility Functions
+ // -----------------
+
+ // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
+ // previous owner. Returns a reference to the Underscore object.
+ _.noConflict = function() {
+ root._ = previousUnderscore;
+ return this;
+ };
+
+ // Keep the identity function around for default iteratees.
+ _.identity = function(value) {
+ return value;
+ };
+
+ _.constant = function(value) {
+ return function() {
+ return value;
+ };
+ };
+
+ _.noop = function(){};
+
+ _.property = function(key) {
+ return function(obj) {
+ return obj[key];
+ };
+ };
+
+ // Returns a predicate for checking whether an object has a given set of `key:value` pairs.
+ _.matches = function(attrs) {
+ var pairs = _.pairs(attrs), length = pairs.length;
+ return function(obj) {
+ if (obj == null) return !length;
+ obj = new Object(obj);
+ for (var i = 0; i < length; i++) {
+ var pair = pairs[i], key = pair[0];
+ if (pair[1] !== obj[key] || !(key in obj)) return false;
+ }
+ return true;
+ };
+ };
+
+ // Run a function **n** times.
+ _.times = function(n, iteratee, context) {
+ var accum = Array(Math.max(0, n));
+ iteratee = createCallback(iteratee, context, 1);
+ for (var i = 0; i < n; i++) accum[i] = iteratee(i);
+ return accum;
+ };
+
+ // Return a random integer between min and max (inclusive).
+ _.random = function(min, max) {
+ if (max == null) {
+ max = min;
+ min = 0;
+ }
+ return min + Math.floor(Math.random() * (max - min + 1));
+ };
+
+ // A (possibly faster) way to get the current timestamp as an integer.
+ _.now = Date.now || function() {
+ return new Date().getTime();
+ };
+
+ // List of HTML entities for escaping.
+ var escapeMap = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": ''',
+ '`': '`'
+ };
+ var unescapeMap = _.invert(escapeMap);
+
+ // Functions for escaping and unescaping strings to/from HTML interpolation.
+ var createEscaper = function(map) {
+ var escaper = function(match) {
+ return map[match];
+ };
+ // Regexes for identifying a key that needs to be escaped
+ var source = '(?:' + _.keys(map).join('|') + ')';
+ var testRegexp = RegExp(source);
+ var replaceRegexp = RegExp(source, 'g');
+ return function(string) {
+ string = string == null ? '' : '' + string;
+ return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
+ };
+ };
+ _.escape = createEscaper(escapeMap);
+ _.unescape = createEscaper(unescapeMap);
+
+ // If the value of the named `property` is a function then invoke it with the
+ // `object` as context; otherwise, return it.
+ _.result = function(object, property) {
+ if (object == null) return void 0;
+ var value = object[property];
+ return _.isFunction(value) ? object[property]() : value;
+ };
+
+ // Generate a unique integer id (unique within the entire client session).
+ // Useful for temporary DOM ids.
+ var idCounter = 0;
+ _.uniqueId = function(prefix) {
+ var id = ++idCounter + '';
+ return prefix ? prefix + id : id;
+ };
+
+ // By default, Underscore uses ERB-style template delimiters, change the
+ // following template settings to use alternative delimiters.
+ _.templateSettings = {
+ evaluate : /<%([\s\S]+?)%>/g,
+ interpolate : /<%=([\s\S]+?)%>/g,
+ escape : /<%-([\s\S]+?)%>/g
+ };
+
+ // When customizing `templateSettings`, if you don't want to define an
+ // interpolation, evaluation or escaping regex, we need one that is
+ // guaranteed not to match.
+ var noMatch = /(.)^/;
+
+ // Certain characters need to be escaped so that they can be put into a
+ // string literal.
+ var escapes = {
+ "'": "'",
+ '\\': '\\',
+ '\r': 'r',
+ '\n': 'n',
+ '\u2028': 'u2028',
+ '\u2029': 'u2029'
+ };
+
+ var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
+
+ var escapeChar = function(match) {
+ return '\\' + escapes[match];
+ };
+
+ // JavaScript micro-templating, similar to John Resig's implementation.
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
+ // and correctly escapes quotes within interpolated code.
+ // NB: `oldSettings` only exists for backwards compatibility.
+ _.template = function(text, settings, oldSettings) {
+ if (!settings && oldSettings) settings = oldSettings;
+ settings = _.defaults({}, settings, _.templateSettings);
+
+ // Combine delimiters into one regular expression via alternation.
+ var matcher = RegExp([
+ (settings.escape || noMatch).source,
+ (settings.interpolate || noMatch).source,
+ (settings.evaluate || noMatch).source
+ ].join('|') + '|$', 'g');
+
+ // Compile the template source, escaping string literals appropriately.
+ var index = 0;
+ var source = "__p+='";
+ text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
+ source += text.slice(index, offset).replace(escaper, escapeChar);
+ index = offset + match.length;
+
+ if (escape) {
+ source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
+ } else if (interpolate) {
+ source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
+ } else if (evaluate) {
+ source += "';\n" + evaluate + "\n__p+='";
+ }
+
+ // Adobe VMs need the match returned to produce the correct offest.
+ return match;
+ });
+ source += "';\n";
+
+ // If a variable is not specified, place data values in local scope.
+ if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
+
+ source = "var __t,__p='',__j=Array.prototype.join," +
+ "print=function(){__p+=__j.call(arguments,'');};\n" +
+ source + 'return __p;\n';
+
+ try {
+ var render = new Function(settings.variable || 'obj', '_', source);
+ } catch (e) {
+ e.source = source;
+ throw e;
+ }
+
+ var template = function(data) {
+ return render.call(this, data, _);
+ };
+
+ // Provide the compiled source as a convenience for precompilation.
+ var argument = settings.variable || 'obj';
+ template.source = 'function(' + argument + '){\n' + source + '}';
+
+ return template;
+ };
+
+ // Add a "chain" function. Start chaining a wrapped Underscore object.
+ _.chain = function(obj) {
+ var instance = _(obj);
+ instance._chain = true;
+ return instance;
+ };
+
+ // OOP
+ // ---------------
+ // If Underscore is called as a function, it returns a wrapped object that
+ // can be used OO-style. This wrapper holds altered versions of all the
+ // underscore functions. Wrapped objects may be chained.
+
+ // Helper function to continue chaining intermediate results.
+ var result = function(obj) {
+ return this._chain ? _(obj).chain() : obj;
+ };
+
+ // Add your own custom functions to the Underscore object.
+ _.mixin = function(obj) {
+ _.each(_.functions(obj), function(name) {
+ var func = _[name] = obj[name];
+ _.prototype[name] = function() {
+ var args = [this._wrapped];
+ push.apply(args, arguments);
+ return result.call(this, func.apply(_, args));
+ };
+ });
+ };
+
+ // Add all of the Underscore functions to the wrapper object.
+ _.mixin(_);
+
+ // Add all mutator Array functions to the wrapper.
+ _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ var obj = this._wrapped;
+ method.apply(obj, arguments);
+ if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
+ return result.call(this, obj);
+ };
+ });
+
+ // Add all accessor Array functions to the wrapper.
+ _.each(['concat', 'join', 'slice'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ return result.call(this, method.apply(this._wrapped, arguments));
+ };
+ });
+
+ // Extracts the result from a wrapped and chained object.
+ _.prototype.value = function() {
+ return this._wrapped;
+ };
+
+ // AMD registration happens at the end for compatibility with AMD loaders
+ // that may not enforce next-turn semantics on modules. Even though general
+ // practice for AMD registration is to be anonymous, underscore registers
+ // as a named module because, like jQuery, it is a base library that is
+ // popular enough to be bundled in a third party lib, but not be part of
+ // an AMD load request. Those cases could generate an error when an
+ // anonymous define() is called outside of a loader request.
+ if (typeof define === 'function' && define.amd) {
+ define('underscore', [], function() {
+ return _;
+ });
+ }
+}.call(this));