Merge pull request #430 from rzurad/nsdocfix
[raphael] / raphael.core.js
1 // ┌─────────────────────────────────────────────────────────────────────┐ \\
2 // │ "Raphaël 2.0" - JavaScript Vector Library                           │ \\
3 // ├─────────────────────────────────────────────────────────────────────┤ \\
4 // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com)   │ \\
5 // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com)             │ \\
6 // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
7 // └─────────────────────────────────────────────────────────────────────┘ \\
8 (function () {
9     /*\
10      * Raphael
11      [ method ]
12      **
13      * Creates a canvas object on which to draw.
14      * You must do this first, as all future calls to drawing methods
15      * from this instance will be bound to this canvas.
16      > Parameters
17      **
18      - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
19      - width (number)
20      - height (number)
21      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
22      * or
23      - x (number)
24      - y (number)
25      - width (number)
26      - height (number)
27      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
28      * or
29      - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>})
30      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
31      * or
32      - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
33      = (object) @Paper
34      > Usage
35      | // Each of the following examples create a canvas
36      | // that is 320px wide by 200px high.
37      | // Canvas is created at the viewport’s 10,50 coordinate.
38      | var paper = Raphael(10, 50, 320, 200);
39      | // Canvas is created at the top left corner of the #notepad element
40      | // (or its top right corner in dir="rtl" elements)
41      | var paper = Raphael(document.getElementById("notepad"), 320, 200);
42      | // Same as above
43      | var paper = Raphael("notepad", 320, 200);
44      | // Image dump
45      | var set = Raphael(["notepad", 320, 200, {
46      |     type: "rect",
47      |     x: 10,
48      |     y: 10,
49      |     width: 25,
50      |     height: 25,
51      |     stroke: "#f00"
52      | }, {
53      |     type: "text",
54      |     x: 30,
55      |     y: 40,
56      |     text: "Dump"
57      | }]);
58     \*/
59     function R(first) {
60         if (R.is(first, "function")) {
61             return loaded ? first() : eve.on("DOMload", first);
62         } else if (R.is(first, array)) {
63             var a = first,
64                 cnv = R._engine.create[apply](R, a.splice(0, 3 + R.is(a[0], nu))),
65                 res = cnv.set(),
66                 i = 0,
67                 ii = a.length,
68                 j;
69             for (; i < ii; i++) {
70                 j = a[i] || {};
71                 elements[has](j.type) && res.push(cnv[j.type]().attr(j));
72             }
73             return res;
74         } else {
75             var args = Array.prototype.slice.call(arguments, 0);
76             if (R.is(args[args.length - 1], "function")) {
77                 var f = args.pop();
78                 return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("DOMload", function () {
79                     f.call(R._engine.create[apply](R, args));
80                 });
81             } else {
82                 return R._engine.create[apply](R, arguments);
83             }
84         }
85     }
86     R.version = "2.0.0";
87     R.eve = eve;
88     var loaded,
89         separator = /[, ]+/,
90         elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
91         formatrg = /\{(\d+)\}/g,
92         proto = "prototype",
93         has = "hasOwnProperty",
94         g = {
95             doc: document,
96             win: window
97         },
98         oldRaphael = {
99             was: Object.prototype[has].call(g.win, "Raphael"),
100             is: g.win.Raphael
101         },
102         Paper = function () {
103             /*\
104              * Paper.ca
105              [ property (object) ]
106              **
107              * Shortcut for @Paper.customAttributes
108             \*/
109             /*\
110              * Paper.customAttributes
111              [ property (object) ]
112              **
113              * If you have a set of attributes that you would like to represent
114              * as a function of some number you can do it easily with custom attributes:
115              > Usage
116              | paper.customAttributes.hue = function (num) {
117              |     num = num % 1;
118              |     return {fill: "hsb(" + num + ", 0.75, 1)"};
119              | };
120              | // Custom attribute “hue” will change fill
121              | // to be given hue with fixed saturation and brightness.
122              | // Now you can use it like this:
123              | var c = paper.circle(10, 10, 10).attr({hue: .45});
124              | // or even like this:
125              | c.animate({hue: 1}, 1e3);
126              | 
127              | // You could also create custom attribute
128              | // with multiple parameters:
129              | paper.customAttributes.hsb = function (h, s, b) {
130              |     return {fill: "hsb(" + [h, s, b].join(",") + ")"};
131              | };
132              | c.attr({hsb: "0.5 .8 1"});
133              | c.animate({hsb: [1, 0, 0.5]}, 1e3);
134             \*/
135             this.ca = this.customAttributes = {};
136         },
137         paperproto,
138         appendChild = "appendChild",
139         apply = "apply",
140         concat = "concat",
141         supportsTouch = "createTouch" in g.doc,
142         E = "",
143         S = " ",
144         Str = String,
145         split = "split",
146         events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[split](S),
147         touchMap = {
148             mousedown: "touchstart",
149             mousemove: "touchmove",
150             mouseup: "touchend"
151         },
152         lowerCase = Str.prototype.toLowerCase,
153         math = Math,
154         mmax = math.max,
155         mmin = math.min,
156         abs = math.abs,
157         pow = math.pow,
158         PI = math.PI,
159         nu = "number",
160         string = "string",
161         array = "array",
162         toString = "toString",
163         fillString = "fill",
164         objectToString = Object.prototype.toString,
165         paper = {},
166         push = "push",
167         ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
168         colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
169         isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
170         bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
171         round = math.round,
172         setAttribute = "setAttribute",
173         toFloat = parseFloat,
174         toInt = parseInt,
175         upperCase = Str.prototype.toUpperCase,
176         availableAttrs = R._availableAttrs = {
177             "arrow-end": "none",
178             "arrow-start": "none",
179             blur: 0,
180             "clip-rect": "0 0 1e9 1e9",
181             cursor: "default",
182             cx: 0,
183             cy: 0,
184             fill: "#fff",
185             "fill-opacity": 1,
186             font: '10px "Arial"',
187             "font-family": '"Arial"',
188             "font-size": "10",
189             "font-style": "normal",
190             "font-weight": 400,
191             gradient: 0,
192             height: 0,
193             href: "http://raphaeljs.com/",
194             opacity: 1,
195             path: "M0,0",
196             r: 0,
197             rx: 0,
198             ry: 0,
199             src: "",
200             stroke: "#000",
201             "stroke-dasharray": "",
202             "stroke-linecap": "butt",
203             "stroke-linejoin": "butt",
204             "stroke-miterlimit": 0,
205             "stroke-opacity": 1,
206             "stroke-width": 1,
207             target: "_blank",
208             "text-anchor": "middle",
209             title: "Raphael",
210             transform: "",
211             width: 0,
212             x: 0,
213             y: 0
214         },
215         availableAnimAttrs = R._availableAnimAttrs = {
216             blur: nu,
217             "clip-rect": "csv",
218             cx: nu,
219             cy: nu,
220             fill: "colour",
221             "fill-opacity": nu,
222             "font-size": nu,
223             height: nu,
224             opacity: nu,
225             path: "path",
226             r: nu,
227             rx: nu,
228             ry: nu,
229             stroke: "colour",
230             "stroke-opacity": nu,
231             "stroke-width": nu,
232             transform: "transform",
233             width: nu,
234             x: nu,
235             y: nu
236         },
237         commaSpaces = /\s*,\s*/,
238         hsrg = {hs: 1, rg: 1},
239         p2s = /,?([achlmqrstvxz]),?/gi,
240         pathCommand = /([achlmrqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
241         tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
242         pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
243         radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
244         eldata = {},
245         sortByKey = function (a, b) {
246             return a.key - b.key;
247         },
248         sortByNumber = function (a, b) {
249             return toFloat(a) - toFloat(b);
250         },
251         fun = function () {},
252         pipe = function (x) {
253             return x;
254         },
255         rectPath = R._rectPath = function (x, y, w, h, r) {
256             if (r) {
257                 return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
258             }
259             return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
260         },
261         ellipsePath = function (x, y, rx, ry) {
262             if (ry == null) {
263                 ry = rx;
264             }
265             return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
266         },
267         getPath = R._getPath = {
268             path: function (el) {
269                 return el.attr("path");
270             },
271             circle: function (el) {
272                 var a = el.attrs;
273                 return ellipsePath(a.cx, a.cy, a.r);
274             },
275             ellipse: function (el) {
276                 var a = el.attrs;
277                 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
278             },
279             rect: function (el) {
280                 var a = el.attrs;
281                 return rectPath(a.x, a.y, a.width, a.height, a.r);
282             },
283             image: function (el) {
284                 var a = el.attrs;
285                 return rectPath(a.x, a.y, a.width, a.height);
286             },
287             text: function (el) {
288                 var bbox = el._getBBox();
289                 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
290             }
291         },
292         mapPath = R.mapPath = function (path, matrix) {
293             if (!matrix) {
294                 return path;
295             }
296             var x, y, i, j, pathi;
297             path = path2curve(path);
298             for (i = 0, ii = path.length; i < ii; i++) {
299                 pathi = path[i];
300                 for (j = 1, jj = pathi.length; j < jj; j += 2) {
301                     x = matrix.x(pathi[j], pathi[j + 1]);
302                     y = matrix.y(pathi[j], pathi[j + 1]);
303                     pathi[j] = x;
304                     pathi[j + 1] = y;
305                 }
306             }
307             return path;
308         };
309
310     R._g = g;
311     /*\
312      * Raphael.type
313      [ property (string) ]
314      **
315      * Can be “SVG”, “VML” or empty, depending on browser support.
316     \*/
317     R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
318     if (R.type == "VML") {
319         var d = g.doc.createElement("div"),
320             b;
321         d.innerHTML = '<v:shape adj="1"/>';
322         b = d.firstChild;
323         b.style.behavior = "url(#default#VML)";
324         if (!(b && typeof b.adj == "object")) {
325             return (R.type = E);
326         }
327         d = null;
328     }
329     /*\
330      * Raphael.svg
331      [ property (boolean) ]
332      **
333      * `true` if browser supports SVG.
334     \*/
335     /*\
336      * Raphael.vml
337      [ property (boolean) ]
338      **
339      * `true` if browser supports VML.
340     \*/
341     R.svg = !(R.vml = R.type == "VML");
342     R._Paper = Paper;
343     /*\
344      * Raphael.fn
345      [ property (object) ]
346      **
347      * You can add your own method to the canvas. For example if you want to draw a pie chart,
348      * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
349      * you need to extend the `Raphael.fn` object. You should modify the `fn` object before a
350      * Raphaël instance is created, otherwise it will take no effect. Please note that the
351      * ability for namespaced plugins was removed in Raphael 2.0. It is up to the plugin to
352      * ensure any namespacing ensures proper context.
353      > Usage
354      | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
355      |     return this.path( ... );
356      | };
357      | // or create namespace
358      | Raphael.fn.mystuff = {
359      |     arrow: function () {…},
360      |     star: function () {…},
361      |     // etc…
362      | };
363      | var paper = Raphael(10, 10, 630, 480);
364      | // then use it
365      | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
366      | paper.mystuff.arrow();
367      | paper.mystuff.star();
368     \*/
369     R.fn = paperproto = Paper.prototype = R.prototype;
370     R._id = 0;
371     R._oid = 0;
372     /*\
373      * Raphael.is
374      [ method ]
375      **
376      * Handfull replacement for `typeof` operator.
377      > Parameters
378      - o (…) any object or primitive
379      - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
380      = (boolean) is given value is of given type
381     \*/
382     R.is = function (o, type) {
383         type = lowerCase.call(type);
384         if (type == "finite") {
385             return !isnan[has](+o);
386         }
387         if (type == "array") {
388             return o instanceof Array;
389         }
390         return  (type == "null" && o === null) ||
391                 (type == typeof o && o !== null) ||
392                 (type == "object" && o === Object(o)) ||
393                 (type == "array" && Array.isArray && Array.isArray(o)) ||
394                 objectToString.call(o).slice(8, -1).toLowerCase() == type;
395     };
396     /*\
397      * Raphael.angle
398      [ method ]
399      **
400      * Returns angle between two or three points
401      > Parameters
402      - x1 (number) x coord of first point
403      - y1 (number) y coord of first point
404      - x2 (number) x coord of second point
405      - y2 (number) y coord of second point
406      - x3 (number) #optional x coord of third point
407      - y3 (number) #optional y coord of third point
408      = (number) angle in degrees.
409     \*/
410     R.angle = function (x1, y1, x2, y2, x3, y3) {
411         if (x3 == null) {
412             var x = x1 - x2,
413                 y = y1 - y2;
414             if (!x && !y) {
415                 return 0;
416             }
417             return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
418         } else {
419             return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
420         }
421     };
422     /*\
423      * Raphael.rad
424      [ method ]
425      **
426      * Transform angle to radians
427      > Parameters
428      - deg (number) angle in degrees
429      = (number) angle in radians.
430     \*/
431     R.rad = function (deg) {
432         return deg % 360 * PI / 180;
433     };
434     /*\
435      * Raphael.deg
436      [ method ]
437      **
438      * Transform angle to degrees
439      > Parameters
440      - deg (number) angle in radians
441      = (number) angle in degrees.
442     \*/
443     R.deg = function (rad) {
444         return rad * 180 / PI % 360;
445     };
446     /*\
447      * Raphael.snapTo
448      [ method ]
449      **
450      * Snaps given value to given grid.
451      > Parameters
452      - values (array|number) given array of values or step of the grid
453      - value (number) value to adjust
454      - tolerance (number) #optional tolerance for snapping. Default is `10`.
455      = (number) adjusted value.
456     \*/
457     R.snapTo = function (values, value, tolerance) {
458         tolerance = R.is(tolerance, "finite") ? tolerance : 10;
459         if (R.is(values, array)) {
460             var i = values.length;
461             while (i--) if (abs(values[i] - value) <= tolerance) {
462                 return values[i];
463             }
464         } else {
465             values = +values;
466             var rem = value % values;
467             if (rem < tolerance) {
468                 return value - rem;
469             }
470             if (rem > values - tolerance) {
471                 return value - rem + values;
472             }
473         }
474         return value;
475     };
476     
477     /*\
478      * Raphael.createUUID
479      [ method ]
480      **
481      * Returns RFC4122, version 4 ID
482     \*/
483     var createUUID = R.createUUID = (function (uuidRegEx, uuidReplacer) {
484         return function () {
485             return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
486         };
487     })(/[xy]/g, function (c) {
488         var r = math.random() * 16 | 0,
489             v = c == "x" ? r : (r & 3 | 8);
490         return v.toString(16);
491     });
492
493     /*\
494      * Raphael.setWindow
495      [ method ]
496      **
497      * Used when you need to draw in `&lt;iframe>`. Switched window to the iframe one.
498      > Parameters
499      - newwin (window) new window object
500     \*/
501     R.setWindow = function (newwin) {
502         eve("setWindow", R, g.win, newwin);
503         g.win = newwin;
504         g.doc = g.win.document;
505         if (initWin) {
506             initWin(g.win);
507         }
508     };
509     var toHex = function (color) {
510         if (R.vml) {
511             // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
512             var trim = /^\s+|\s+$/g;
513             var bod;
514             try {
515                 var docum = new ActiveXObject("htmlfile");
516                 docum.write("<body>");
517                 docum.close();
518                 bod = docum.body;
519             } catch(e) {
520                 bod = createPopup().document.body;
521             }
522             var range = bod.createTextRange();
523             toHex = cacher(function (color) {
524                 try {
525                     bod.style.color = Str(color).replace(trim, E);
526                     var value = range.queryCommandValue("ForeColor");
527                     value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
528                     return "#" + ("000000" + value.toString(16)).slice(-6);
529                 } catch(e) {
530                     return "none";
531                 }
532             });
533         } else {
534             var i = g.doc.createElement("i");
535             i.title = "Rapha\xebl Colour Picker";
536             i.style.display = "none";
537             g.doc.body.appendChild(i);
538             toHex = cacher(function (color) {
539                 i.style.color = color;
540                 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
541             });
542         }
543         return toHex(color);
544     },
545     hsbtoString = function () {
546         return "hsb(" + [this.h, this.s, this.b] + ")";
547     },
548     hsltoString = function () {
549         return "hsl(" + [this.h, this.s, this.l] + ")";
550     },
551     rgbtoString = function () {
552         return this.hex;
553     },
554     prepareRGB = function (r, g, b) {
555         if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
556             b = r.b;
557             g = r.g;
558             r = r.r;
559         }
560         if (g == null && R.is(r, string)) {
561             var clr = R.getRGB(r);
562             r = clr.r;
563             g = clr.g;
564             b = clr.b;
565         }
566         if (r > 1 || g > 1 || b > 1) {
567             r /= 255;
568             g /= 255;
569             b /= 255;
570         }
571         
572         return [r, g, b];
573     },
574     packageRGB = function (r, g, b, o) {
575         r *= 255;
576         g *= 255;
577         b *= 255;
578         var rgb = {
579             r: r,
580             g: g,
581             b: b,
582             hex: R.rgb(r, g, b),
583             toString: rgbtoString
584         };
585         R.is(o, "finite") && (rgb.opacity = o);
586         return rgb;
587     };
588     
589     /*\
590      * Raphael.color
591      [ method ]
592      **
593      * Parses the color string and returns object with all values for the given color.
594      > Parameters
595      - clr (string) color string in one of the supported formats (see @Raphael.getRGB)
596      = (object) Combined RGB & HSB object in format:
597      o {
598      o     r (number) red,
599      o     g (number) green,
600      o     b (number) blue,
601      o     hex (string) color in HTML/CSS format: #••••••,
602      o     error (boolean) `true` if string can’t be parsed,
603      o     h (number) hue,
604      o     s (number) saturation,
605      o     v (number) value (brightness),
606      o     l (number) lightness
607      o }
608     \*/
609     R.color = function (clr) {
610         var rgb;
611         if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
612             rgb = R.hsb2rgb(clr);
613             clr.r = rgb.r;
614             clr.g = rgb.g;
615             clr.b = rgb.b;
616             clr.hex = rgb.hex;
617         } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
618             rgb = R.hsl2rgb(clr);
619             clr.r = rgb.r;
620             clr.g = rgb.g;
621             clr.b = rgb.b;
622             clr.hex = rgb.hex;
623         } else {
624             if (R.is(clr, "string")) {
625                 clr = R.getRGB(clr);
626             }
627             if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
628                 rgb = R.rgb2hsl(clr);
629                 clr.h = rgb.h;
630                 clr.s = rgb.s;
631                 clr.l = rgb.l;
632                 rgb = R.rgb2hsb(clr);
633                 clr.v = rgb.b;
634             } else {
635                 clr = {hex: "none"};
636                 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
637             }
638         }
639         clr.toString = rgbtoString;
640         return clr;
641     };
642     /*\
643      * Raphael.hsb2rgb
644      [ method ]
645      **
646      * Converts HSB values to RGB object.
647      > Parameters
648      - h (number) hue
649      - s (number) saturation
650      - v (number) value or brightness
651      = (object) RGB object in format:
652      o {
653      o     r (number) red,
654      o     g (number) green,
655      o     b (number) blue,
656      o     hex (string) color in HTML/CSS format: #••••••
657      o }
658     \*/
659     R.hsb2rgb = function (h, s, v, o) {
660         if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
661             v = h.b;
662             s = h.s;
663             h = h.h;
664             o = h.o;
665         }
666         h *= 360;
667         var R, G, B, X, C;
668         h = (h % 360) / 60;
669         C = v * s;
670         X = C * (1 - abs(h % 2 - 1));
671         R = G = B = v - C;
672
673         h = ~~h;
674         R += [C, X, 0, 0, X, C][h];
675         G += [X, C, C, X, 0, 0][h];
676         B += [0, 0, X, C, C, X][h];
677         return packageRGB(R, G, B, o);
678     };
679     /*\
680      * Raphael.hsl2rgb
681      [ method ]
682      **
683      * Converts HSL values to RGB object.
684      > Parameters
685      - h (number) hue
686      - s (number) saturation
687      - l (number) luminosity
688      = (object) RGB object in format:
689      o {
690      o     r (number) red,
691      o     g (number) green,
692      o     b (number) blue,
693      o     hex (string) color in HTML/CSS format: #••••••
694      o }
695     \*/
696     R.hsl2rgb = function (h, s, l, o) {
697         if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
698             l = h.l;
699             s = h.s;
700             h = h.h;
701         }
702         if (h > 1 || s > 1 || l > 1) {
703             h /= 360;
704             s /= 100;
705             l /= 100;
706         }
707         h *= 360;
708         var R, G, B, X, C;
709         h = (h % 360) / 60;
710         C = 2 * s * (l < .5 ? l : 1 - l);
711         X = C * (1 - abs(h % 2 - 1));
712         R = G = B = l - C / 2;
713
714         h = ~~h;
715         R += [C, X, 0, 0, X, C][h];
716         G += [X, C, C, X, 0, 0][h];
717         B += [0, 0, X, C, C, X][h];
718         return packageRGB(R, G, B, o);
719     };
720     /*\
721      * Raphael.rgb2hsb
722      [ method ]
723      **
724      * Converts RGB values to HSB object.
725      > Parameters
726      - r (number) red
727      - g (number) green
728      - b (number) blue
729      = (object) HSB object in format:
730      o {
731      o     h (number) hue
732      o     s (number) saturation
733      o     b (number) brightness
734      o }
735     \*/
736     R.rgb2hsb = function (r, g, b) {
737         b = prepareRGB(r, g, b);
738         r = b[0];
739         g = b[1];
740         b = b[2];
741
742         var H, S, V, C;
743         V = mmax(r, g, b);
744         C = V - mmin(r, g, b);
745         H = (C == 0 ? null :
746              V == r ? (g - b) / C :
747              V == g ? (b - r) / C + 2 :
748                       (r - g) / C + 4
749             );
750         H = ((H + 360) % 6) * 60 / 360;
751         S = C == 0 ? 0 : C / V;
752         return {h: H, s: S, b: V, toString: hsbtoString};
753     };
754     /*\
755      * Raphael.rgb2hsl
756      [ method ]
757      **
758      * Converts RGB values to HSL object.
759      > Parameters
760      - r (number) red
761      - g (number) green
762      - b (number) blue
763      = (object) HSL object in format:
764      o {
765      o     h (number) hue
766      o     s (number) saturation
767      o     l (number) luminosity
768      o }
769     \*/
770     R.rgb2hsl = function (r, g, b) {
771         b = prepareRGB(r, g, b);
772         r = b[0];
773         g = b[1];
774         b = b[2];
775
776         var H, S, L, M, m, C;
777         M = mmax(r, g, b);
778         m = mmin(r, g, b);
779         C = M - m;
780         H = (C == 0 ? null :
781              M == r ? (g - b) / C :
782              M == g ? (b - r) / C + 2 :
783                       (r - g) / C + 4);
784         H = ((H + 360) % 6) * 60 / 360;
785         L = (M + m) / 2;
786         S = (C == 0 ? 0 :
787              L < .5 ? C / (2 * L) :
788                       C / (2 - 2 * L));
789         return {h: H, s: S, l: L, toString: hsltoString};
790     };
791     R._path2string = function () {
792         return this.join(",").replace(p2s, "$1");
793     };
794     function repush(array, item) {
795         for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
796             return array.push(array.splice(i, 1)[0]);
797         }
798     }
799     function cacher(f, scope, postprocessor) {
800         function newf() {
801             var arg = Array.prototype.slice.call(arguments, 0),
802                 args = arg.join("\u2400"),
803                 cache = newf.cache = newf.cache || {},
804                 count = newf.count = newf.count || [];
805             if (cache[has](args)) {
806                 repush(count, args);
807                 return postprocessor ? postprocessor(cache[args]) : cache[args];
808             }
809             count.length >= 1e3 && delete cache[count.shift()];
810             count.push(args);
811             cache[args] = f[apply](scope, arg);
812             return postprocessor ? postprocessor(cache[args]) : cache[args];
813         }
814         return newf;
815     }
816
817     var preload = R._preload = function (src, f) {
818         var img = g.doc.createElement("img");
819         img.style.cssText = "position:absolute;left:-9999em;top-9999em";
820         img.onload = function () {
821             f.call(this);
822             this.onload = null;
823             g.doc.body.removeChild(this);
824         };
825         img.onerror = function () {
826             g.doc.body.removeChild(this);
827         };
828         g.doc.body.appendChild(img);
829         img.src = src;
830     };
831     
832     function clrToString() {
833         return this.hex;
834     }
835
836     /*\
837      * Raphael.getRGB
838      [ method ]
839      **
840      * Parses colour string as RGB object
841      > Parameters
842      - colour (string) colour string in one of formats:
843      # <ul>
844      #     <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
845      #     <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
846      #     <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
847      #     <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200,&nbsp;100,&nbsp;0)</code>”)</li>
848      #     <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>”)</li>
849      #     <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>”)</li>
850      #     <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
851      #     <li>hsl(•••, •••, •••) — same as hsb</li>
852      #     <li>hsl(•••%, •••%, •••%) — same as hsb</li>
853      # </ul>
854      = (object) RGB object in format:
855      o {
856      o     r (number) red,
857      o     g (number) green,
858      o     b (number) blue
859      o     hex (string) color in HTML/CSS format: #••••••,
860      o     error (boolean) true if string can’t be parsed
861      o }
862     \*/
863     R.getRGB = cacher(function (colour) {
864         if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
865             return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
866         }
867         if (colour == "none") {
868             return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
869         }
870         !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
871         var res,
872             red,
873             green,
874             blue,
875             opacity,
876             t,
877             values,
878             rgb = colour.match(colourRegExp);
879         if (rgb) {
880             if (rgb[2]) {
881                 blue = toInt(rgb[2].substring(5), 16);
882                 green = toInt(rgb[2].substring(3, 5), 16);
883                 red = toInt(rgb[2].substring(1, 3), 16);
884             }
885             if (rgb[3]) {
886                 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
887                 green = toInt((t = rgb[3].charAt(2)) + t, 16);
888                 red = toInt((t = rgb[3].charAt(1)) + t, 16);
889             }
890             if (rgb[4]) {
891                 values = rgb[4][split](commaSpaces);
892                 red = toFloat(values[0]);
893                 values[0].slice(-1) == "%" && (red *= 2.55);
894                 green = toFloat(values[1]);
895                 values[1].slice(-1) == "%" && (green *= 2.55);
896                 blue = toFloat(values[2]);
897                 values[2].slice(-1) == "%" && (blue *= 2.55);
898                 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
899                 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
900             }
901             if (rgb[5]) {
902                 values = rgb[5][split](commaSpaces);
903                 red = toFloat(values[0]);
904                 values[0].slice(-1) == "%" && (red *= 2.55);
905                 green = toFloat(values[1]);
906                 values[1].slice(-1) == "%" && (green *= 2.55);
907                 blue = toFloat(values[2]);
908                 values[2].slice(-1) == "%" && (blue *= 2.55);
909                 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
910                 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
911                 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
912                 return R.hsb2rgb(red, green, blue, opacity);
913             }
914             if (rgb[6]) {
915                 values = rgb[6][split](commaSpaces);
916                 red = toFloat(values[0]);
917                 values[0].slice(-1) == "%" && (red *= 2.55);
918                 green = toFloat(values[1]);
919                 values[1].slice(-1) == "%" && (green *= 2.55);
920                 blue = toFloat(values[2]);
921                 values[2].slice(-1) == "%" && (blue *= 2.55);
922                 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
923                 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
924                 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
925                 return R.hsl2rgb(red, green, blue, opacity);
926             }
927             rgb = {r: red, g: green, b: blue, toString: clrToString};
928             rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
929             R.is(opacity, "finite") && (rgb.opacity = opacity);
930             return rgb;
931         }
932         return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
933     }, R);
934     /*\
935      * Raphael.hsb
936      [ method ]
937      **
938      * Converts HSB values to hex representation of the colour.
939      > Parameters
940      - h (number) hue
941      - s (number) saturation
942      - b (number) value or brightness
943      = (string) hex representation of the colour.
944     \*/
945     R.hsb = cacher(function (h, s, b) {
946         return R.hsb2rgb(h, s, b).hex;
947     });
948     /*\
949      * Raphael.hsl
950      [ method ]
951      **
952      * Converts HSL values to hex representation of the colour.
953      > Parameters
954      - h (number) hue
955      - s (number) saturation
956      - l (number) luminosity
957      = (string) hex representation of the colour.
958     \*/
959     R.hsl = cacher(function (h, s, l) {
960         return R.hsl2rgb(h, s, l).hex;
961     });
962     /*\
963      * Raphael.rgb
964      [ method ]
965      **
966      * Converts RGB values to hex representation of the colour.
967      > Parameters
968      - r (number) red
969      - g (number) green
970      - b (number) blue
971      = (string) hex representation of the colour.
972     \*/
973     R.rgb = cacher(function (r, g, b) {
974         return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
975     });
976     /*\
977      * Raphael.getColor
978      [ method ]
979      **
980      * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
981      > Parameters
982      - value (number) #optional brightness, default is `0.75`
983      = (string) hex representation of the colour.
984     \*/
985     R.getColor = function (value) {
986         var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
987             rgb = this.hsb2rgb(start.h, start.s, start.b);
988         start.h += .075;
989         if (start.h > 1) {
990             start.h = 0;
991             start.s -= .2;
992             start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
993         }
994         return rgb.hex;
995     };
996     /*\
997      * Raphael.getColor.reset
998      [ method ]
999      **
1000      * Resets spectrum position for @Raphael.getColor back to red.
1001     \*/
1002     R.getColor.reset = function () {
1003         delete this.start;
1004     };
1005
1006     // http://schepers.cc/getting-to-the-point
1007     function catmullRom2bezier(crp) {
1008         var d = [];
1009         for (var i = 0, iLen = crp.length; iLen - 2 > i; i += 2) {
1010             var p = [{x: +crp[i],     y: +crp[i + 1]},
1011                      {x: +crp[i],     y: +crp[i + 1]},
1012                      {x: +crp[i + 2], y: +crp[i + 3]},
1013                      {x: +crp[i + 4], y: +crp[i + 5]}];
1014             if (iLen - 4 == i) {
1015                 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1016                 p[3] = p[2];
1017             } else if (i) {
1018                 p[0] = {x: +crp[i - 2], y: +crp[i - 1]};
1019             }
1020             d.push(["C",
1021                 (-p[0].x + 6 * p[1].x + p[2].x) / 6,
1022                 (-p[0].y + 6 * p[1].y + p[2].y) / 6,
1023                 (p[1].x + 6 * p[2].x - p[3].x) / 6,
1024                 (p[1].y + 6*p[2].y - p[3].y) / 6,
1025                 p[2].x,
1026                 p[2].y
1027             ]);
1028         }
1029
1030         return d;
1031     }
1032     /*\
1033      * Raphael.parsePathString
1034      [ method ]
1035      **
1036      * Utility method
1037      **
1038      * Parses given path string into an array of arrays of path segments.
1039      > Parameters
1040      - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
1041      = (array) array of segments.
1042     \*/
1043     R.parsePathString = cacher(function (pathString) {
1044         if (!pathString) {
1045             return null;
1046         }
1047         var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0},
1048             data = [];
1049         if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
1050             data = pathClone(pathString);
1051         }
1052         if (!data.length) {
1053             Str(pathString).replace(pathCommand, function (a, b, c) {
1054                 var params = [],
1055                     name = b.toLowerCase();
1056                 c.replace(pathValues, function (a, b) {
1057                     b && params.push(+b);
1058                 });
1059                 if (name == "m" && params.length > 2) {
1060                     data.push([b][concat](params.splice(0, 2)));
1061                     name = "l";
1062                     b = b == "m" ? "l" : "L";
1063                 }
1064                 if (name == "r") {
1065                     data.push([b][concat](params));
1066                 } else while (params.length >= paramCounts[name]) {
1067                     data.push([b][concat](params.splice(0, paramCounts[name])));
1068                     if (!paramCounts[name]) {
1069                         break;
1070                     }
1071                 }
1072             });
1073         }
1074         data.toString = R._path2string;
1075         return data;
1076     });
1077     /*\
1078      * Raphael.parseTransformString
1079      [ method ]
1080      **
1081      * Utility method
1082      **
1083      * Parses given path string into an array of transformations.
1084      > Parameters
1085      - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
1086      = (array) array of transformations.
1087     \*/
1088     R.parseTransformString = cacher(function (TString) {
1089         if (!TString) {
1090             return null;
1091         }
1092         var paramCounts = {r: 3, s: 4, t: 2, m: 6},
1093             data = [];
1094         if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
1095             data = pathClone(TString);
1096         }
1097         if (!data.length) {
1098             Str(TString).replace(tCommand, function (a, b, c) {
1099                 var params = [],
1100                     name = lowerCase.call(b);
1101                 c.replace(pathValues, function (a, b) {
1102                     b && params.push(+b);
1103                 });
1104                 data.push([b][concat](params));
1105             });
1106         }
1107         data.toString = R._path2string;
1108         return data;
1109     });
1110     /*\
1111      * Raphael.findDotsAtSegment
1112      [ method ]
1113      **
1114      * Utility method
1115      **
1116      * Find dot coordinates on the given cubic bezier curve at the given t.
1117      > Parameters
1118      - p1x (number) x of the first point of the curve
1119      - p1y (number) y of the first point of the curve
1120      - c1x (number) x of the first anchor of the curve
1121      - c1y (number) y of the first anchor of the curve
1122      - c2x (number) x of the second anchor of the curve
1123      - c2y (number) y of the second anchor of the curve
1124      - p2x (number) x of the second point of the curve
1125      - p2y (number) y of the second point of the curve
1126      - t (number) position on the curve (0..1)
1127      = (object) point information in format:
1128      o {
1129      o     x: (number) x coordinate of the point
1130      o     y: (number) y coordinate of the point
1131      o     m: {
1132      o         x: (number) x coordinate of the left anchor
1133      o         y: (number) y coordinate of the left anchor
1134      o     }
1135      o     n: {
1136      o         x: (number) x coordinate of the right anchor
1137      o         y: (number) y coordinate of the right anchor
1138      o     }
1139      o     start: {
1140      o         x: (number) x coordinate of the start of the curve
1141      o         y: (number) y coordinate of the start of the curve
1142      o     }
1143      o     end: {
1144      o         x: (number) x coordinate of the end of the curve
1145      o         y: (number) y coordinate of the end of the curve
1146      o     }
1147      o     alpha: (number) angle of the curve derivative at the point
1148      o }
1149     \*/
1150     R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1151         var t1 = 1 - t,
1152             t13 = pow(t1, 3),
1153             t12 = pow(t1, 2),
1154             t2 = t * t,
1155             t3 = t2 * t,
1156             x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
1157             y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
1158             mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
1159             my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
1160             nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
1161             ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
1162             ax = t1 * p1x + t * c1x,
1163             ay = t1 * p1y + t * c1y,
1164             cx = t1 * c2x + t * p2x,
1165             cy = t1 * c2y + t * p2y,
1166             alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1167         (mx > nx || my < ny) && (alpha += 180);
1168         return {
1169             x: x,
1170             y: y,
1171             m: {x: mx, y: my},
1172             n: {x: nx, y: ny},
1173             start: {x: ax, y: ay},
1174             end: {x: cx, y: cy},
1175             alpha: alpha
1176         };
1177     };
1178     var pathDimensions = cacher(function (path) {
1179         if (!path) {
1180             return {x: 0, y: 0, width: 0, height: 0};
1181         }
1182         path = path2curve(path);
1183         var x = 0, 
1184             y = 0,
1185             X = [],
1186             Y = [],
1187             p;
1188         for (var i = 0, ii = path.length; i < ii; i++) {
1189             p = path[i];
1190             if (p[0] == "M") {
1191                 x = p[1];
1192                 y = p[2];
1193                 X.push(x);
1194                 Y.push(y);
1195             } else {
1196                 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1197                 X = X[concat](dim.min.x, dim.max.x);
1198                 Y = Y[concat](dim.min.y, dim.max.y);
1199                 x = p[5];
1200                 y = p[6];
1201             }
1202         }
1203         var xmin = mmin[apply](0, X),
1204             ymin = mmin[apply](0, Y);
1205         return {
1206             x: xmin,
1207             y: ymin,
1208             width: mmax[apply](0, X) - xmin,
1209             height: mmax[apply](0, Y) - ymin
1210         };
1211     }, null, function (o) {
1212         return {
1213             x: o.x,
1214             y: o.y,
1215             width: o.width,
1216             height: o.height
1217         };
1218     }),
1219         pathClone = function (pathArray) {
1220             var res = [];
1221             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1222                 pathArray = R.parsePathString(pathArray);
1223             }
1224             for (var i = 0, ii = pathArray.length; i < ii; i++) {
1225                 res[i] = [];
1226                 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1227                     res[i][j] = pathArray[i][j];
1228                 }
1229             }
1230             res.toString = R._path2string;
1231             return res;
1232         },
1233         pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1234             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1235                 pathArray = R.parsePathString(pathArray);
1236             }
1237             var res = [],
1238                 x = 0,
1239                 y = 0,
1240                 mx = 0,
1241                 my = 0,
1242                 start = 0;
1243             if (pathArray[0][0] == "M") {
1244                 x = pathArray[0][1];
1245                 y = pathArray[0][2];
1246                 mx = x;
1247                 my = y;
1248                 start++;
1249                 res.push(["M", x, y]);
1250             }
1251             for (var i = start, ii = pathArray.length; i < ii; i++) {
1252                 var r = res[i] = [],
1253                     pa = pathArray[i];
1254                 if (pa[0] != lowerCase.call(pa[0])) {
1255                     r[0] = lowerCase.call(pa[0]);
1256                     switch (r[0]) {
1257                         case "a":
1258                             r[1] = pa[1];
1259                             r[2] = pa[2];
1260                             r[3] = pa[3];
1261                             r[4] = pa[4];
1262                             r[5] = pa[5];
1263                             r[6] = +(pa[6] - x).toFixed(3);
1264                             r[7] = +(pa[7] - y).toFixed(3);
1265                             break;
1266                         case "v":
1267                             r[1] = +(pa[1] - y).toFixed(3);
1268                             break;
1269                         case "m":
1270                             mx = pa[1];
1271                             my = pa[2];
1272                         default:
1273                             for (var j = 1, jj = pa.length; j < jj; j++) {
1274                                 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1275                             }
1276                     }
1277                 } else {
1278                     r = res[i] = [];
1279                     if (pa[0] == "m") {
1280                         mx = pa[1] + x;
1281                         my = pa[2] + y;
1282                     }
1283                     for (var k = 0, kk = pa.length; k < kk; k++) {
1284                         res[i][k] = pa[k];
1285                     }
1286                 }
1287                 var len = res[i].length;
1288                 switch (res[i][0]) {
1289                     case "z":
1290                         x = mx;
1291                         y = my;
1292                         break;
1293                     case "h":
1294                         x += +res[i][len - 1];
1295                         break;
1296                     case "v":
1297                         y += +res[i][len - 1];
1298                         break;
1299                     default:
1300                         x += +res[i][len - 2];
1301                         y += +res[i][len - 1];
1302                 }
1303             }
1304             res.toString = R._path2string;
1305             return res;
1306         }, 0, pathClone),
1307         pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1308             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1309                 pathArray = R.parsePathString(pathArray);
1310             }
1311             if (!pathArray || !pathArray.length) {
1312                 return [["M", 0, 0]];
1313             }
1314             var res = [],
1315                 x = 0,
1316                 y = 0,
1317                 mx = 0,
1318                 my = 0,
1319                 start = 0;
1320             if (pathArray[0][0] == "M") {
1321                 x = +pathArray[0][1];
1322                 y = +pathArray[0][2];
1323                 mx = x;
1324                 my = y;
1325                 start++;
1326                 res[0] = ["M", x, y];
1327             }
1328             for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
1329                 res.push(r = []);
1330                 pa = pathArray[i];
1331                 if (pa[0] != upperCase.call(pa[0])) {
1332                     r[0] = upperCase.call(pa[0]);
1333                     switch (r[0]) {
1334                         case "A":
1335                             r[1] = pa[1];
1336                             r[2] = pa[2];
1337                             r[3] = pa[3];
1338                             r[4] = pa[4];
1339                             r[5] = pa[5];
1340                             r[6] = +(pa[6] + x);
1341                             r[7] = +(pa[7] + y);
1342                             break;
1343                         case "V":
1344                             r[1] = +pa[1] + y;
1345                             break;
1346                         case "H":
1347                             r[1] = +pa[1] + x;
1348                             break;
1349                         case "R":
1350                             var dots = [x, y][concat](pa.slice(1));
1351                             for (var j = 2, jj = dots.length; j < jj; j++) {
1352                                 dots[j] = +dots[j] + x;
1353                                 dots[++j] = +dots[j] + y;
1354                             }
1355                             res.pop();
1356                             res = res[concat](catmullRom2bezier(dots));
1357                             break;
1358                         case "M":
1359                             mx = +pa[1] + x;
1360                             my = +pa[2] + y;
1361                         default:
1362                             for (j = 1, jj = pa.length; j < jj; j++) {
1363                                 r[j] = +pa[j] + ((j % 2) ? x : y);
1364                             }
1365                     }
1366                 } else if (pa[0] == "R") {
1367                     dots = [x, y][concat](pa.slice(1));
1368                     res.pop();
1369                     res = res[concat](catmullRom2bezier(dots));
1370                     r = ["R"][concat](pa.slice(-2));
1371                 } else {
1372                     for (var k = 0, kk = pa.length; k < kk; k++) {
1373                         r[k] = pa[k];
1374                     }
1375                 }
1376                 switch (r[0]) {
1377                     case "Z":
1378                         x = mx;
1379                         y = my;
1380                         break;
1381                     case "H":
1382                         x = r[1];
1383                         break;
1384                     case "V":
1385                         y = r[1];
1386                         break;
1387                     case "M":
1388                         mx = r[r.length - 2];
1389                         my = r[r.length - 1];
1390                     default:
1391                         x = r[r.length - 2];
1392                         y = r[r.length - 1];
1393                 }
1394             }
1395             res.toString = R._path2string;
1396             return res;
1397         }, null, pathClone),
1398         l2c = function (x1, y1, x2, y2) {
1399             return [x1, y1, x2, y2, x2, y2];
1400         },
1401         q2c = function (x1, y1, ax, ay, x2, y2) {
1402             var _13 = 1 / 3,
1403                 _23 = 2 / 3;
1404             return [
1405                     _13 * x1 + _23 * ax,
1406                     _13 * y1 + _23 * ay,
1407                     _13 * x2 + _23 * ax,
1408                     _13 * y2 + _23 * ay,
1409                     x2,
1410                     y2
1411                 ];
1412         },
1413         a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1414             // for more information of where this math came from visit:
1415             // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1416             var _120 = PI * 120 / 180,
1417                 rad = PI / 180 * (+angle || 0),
1418                 res = [],
1419                 xy,
1420                 rotate = cacher(function (x, y, rad) {
1421                     var X = x * math.cos(rad) - y * math.sin(rad),
1422                         Y = x * math.sin(rad) + y * math.cos(rad);
1423                     return {x: X, y: Y};
1424                 });
1425             if (!recursive) {
1426                 xy = rotate(x1, y1, -rad);
1427                 x1 = xy.x;
1428                 y1 = xy.y;
1429                 xy = rotate(x2, y2, -rad);
1430                 x2 = xy.x;
1431                 y2 = xy.y;
1432                 var cos = math.cos(PI / 180 * angle),
1433                     sin = math.sin(PI / 180 * angle),
1434                     x = (x1 - x2) / 2,
1435                     y = (y1 - y2) / 2;
1436                 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1437                 if (h > 1) {
1438                     h = math.sqrt(h);
1439                     rx = h * rx;
1440                     ry = h * ry;
1441                 }
1442                 var rx2 = rx * rx,
1443                     ry2 = ry * ry,
1444                     k = (large_arc_flag == sweep_flag ? -1 : 1) *
1445                         math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1446                     cx = k * rx * y / ry + (x1 + x2) / 2,
1447                     cy = k * -ry * x / rx + (y1 + y2) / 2,
1448                     f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1449                     f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1450
1451                 f1 = x1 < cx ? PI - f1 : f1;
1452                 f2 = x2 < cx ? PI - f2 : f2;
1453                 f1 < 0 && (f1 = PI * 2 + f1);
1454                 f2 < 0 && (f2 = PI * 2 + f2);
1455                 if (sweep_flag && f1 > f2) {
1456                     f1 = f1 - PI * 2;
1457                 }
1458                 if (!sweep_flag && f2 > f1) {
1459                     f2 = f2 - PI * 2;
1460                 }
1461             } else {
1462                 f1 = recursive[0];
1463                 f2 = recursive[1];
1464                 cx = recursive[2];
1465                 cy = recursive[3];
1466             }
1467             var df = f2 - f1;
1468             if (abs(df) > _120) {
1469                 var f2old = f2,
1470                     x2old = x2,
1471                     y2old = y2;
1472                 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1473                 x2 = cx + rx * math.cos(f2);
1474                 y2 = cy + ry * math.sin(f2);
1475                 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1476             }
1477             df = f2 - f1;
1478             var c1 = math.cos(f1),
1479                 s1 = math.sin(f1),
1480                 c2 = math.cos(f2),
1481                 s2 = math.sin(f2),
1482                 t = math.tan(df / 4),
1483                 hx = 4 / 3 * rx * t,
1484                 hy = 4 / 3 * ry * t,
1485                 m1 = [x1, y1],
1486                 m2 = [x1 + hx * s1, y1 - hy * c1],
1487                 m3 = [x2 + hx * s2, y2 - hy * c2],
1488                 m4 = [x2, y2];
1489             m2[0] = 2 * m1[0] - m2[0];
1490             m2[1] = 2 * m1[1] - m2[1];
1491             if (recursive) {
1492                 return [m2, m3, m4][concat](res);
1493             } else {
1494                 res = [m2, m3, m4][concat](res).join()[split](",");
1495                 var newres = [];
1496                 for (var i = 0, ii = res.length; i < ii; i++) {
1497                     newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1498                 }
1499                 return newres;
1500             }
1501         },
1502         findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1503             var t1 = 1 - t;
1504             return {
1505                 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1506                 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1507             };
1508         },
1509         curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1510             var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1511                 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1512                 c = p1x - c1x,
1513                 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1514                 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1515                 y = [p1y, p2y],
1516                 x = [p1x, p2x],
1517                 dot;
1518             abs(t1) > "1e12" && (t1 = .5);
1519             abs(t2) > "1e12" && (t2 = .5);
1520             if (t1 > 0 && t1 < 1) {
1521                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1522                 x.push(dot.x);
1523                 y.push(dot.y);
1524             }
1525             if (t2 > 0 && t2 < 1) {
1526                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1527                 x.push(dot.x);
1528                 y.push(dot.y);
1529             }
1530             a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1531             b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1532             c = p1y - c1y;
1533             t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1534             t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1535             abs(t1) > "1e12" && (t1 = .5);
1536             abs(t2) > "1e12" && (t2 = .5);
1537             if (t1 > 0 && t1 < 1) {
1538                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1539                 x.push(dot.x);
1540                 y.push(dot.y);
1541             }
1542             if (t2 > 0 && t2 < 1) {
1543                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1544                 x.push(dot.x);
1545                 y.push(dot.y);
1546             }
1547             return {
1548                 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1549                 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1550             };
1551         }),
1552         path2curve = R._path2curve = cacher(function (path, path2) {
1553             var p = pathToAbsolute(path),
1554                 p2 = path2 && pathToAbsolute(path2),
1555                 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1556                 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1557                 processPath = function (path, d) {
1558                     var nx, ny;
1559                     if (!path) {
1560                         return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1561                     }
1562                     !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1563                     switch (path[0]) {
1564                         case "M":
1565                             d.X = path[1];
1566                             d.Y = path[2];
1567                             break;
1568                         case "A":
1569                             path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1570                             break;
1571                         case "S":
1572                             nx = d.x + (d.x - (d.bx || d.x));
1573                             ny = d.y + (d.y - (d.by || d.y));
1574                             path = ["C", nx, ny][concat](path.slice(1));
1575                             break;
1576                         case "T":
1577                             d.qx = d.x + (d.x - (d.qx || d.x));
1578                             d.qy = d.y + (d.y - (d.qy || d.y));
1579                             path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1580                             break;
1581                         case "Q":
1582                             d.qx = path[1];
1583                             d.qy = path[2];
1584                             path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1585                             break;
1586                         case "L":
1587                             path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1588                             break;
1589                         case "H":
1590                             path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1591                             break;
1592                         case "V":
1593                             path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1594                             break;
1595                         case "Z":
1596                             path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1597                             break;
1598                     }
1599                     return path;
1600                 },
1601                 fixArc = function (pp, i) {
1602                     if (pp[i].length > 7) {
1603                         pp[i].shift();
1604                         var pi = pp[i];
1605                         while (pi.length) {
1606                             pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1607                         }
1608                         pp.splice(i, 1);
1609                         ii = mmax(p.length, p2 && p2.length || 0);
1610                     }
1611                 },
1612                 fixM = function (path1, path2, a1, a2, i) {
1613                     if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1614                         path2.splice(i, 0, ["M", a2.x, a2.y]);
1615                         a1.bx = 0;
1616                         a1.by = 0;
1617                         a1.x = path1[i][1];
1618                         a1.y = path1[i][2];
1619                         ii = mmax(p.length, p2 && p2.length || 0);
1620                     }
1621                 };
1622             for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1623                 p[i] = processPath(p[i], attrs);
1624                 fixArc(p, i);
1625                 p2 && (p2[i] = processPath(p2[i], attrs2));
1626                 p2 && fixArc(p2, i);
1627                 fixM(p, p2, attrs, attrs2, i);
1628                 fixM(p2, p, attrs2, attrs, i);
1629                 var seg = p[i],
1630                     seg2 = p2 && p2[i],
1631                     seglen = seg.length,
1632                     seg2len = p2 && seg2.length;
1633                 attrs.x = seg[seglen - 2];
1634                 attrs.y = seg[seglen - 1];
1635                 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1636                 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1637                 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1638                 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1639                 attrs2.x = p2 && seg2[seg2len - 2];
1640                 attrs2.y = p2 && seg2[seg2len - 1];
1641             }
1642             return p2 ? [p, p2] : p;
1643         }, null, pathClone),
1644         parseDots = R._parseDots = cacher(function (gradient) {
1645             var dots = [];
1646             for (var i = 0, ii = gradient.length; i < ii; i++) {
1647                 var dot = {},
1648                     par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1649                 dot.color = R.getRGB(par[1]);
1650                 if (dot.color.error) {
1651                     return null;
1652                 }
1653                 dot.color = dot.color.hex;
1654                 par[2] && (dot.offset = par[2] + "%");
1655                 dots.push(dot);
1656             }
1657             for (i = 1, ii = dots.length - 1; i < ii; i++) {
1658                 if (!dots[i].offset) {
1659                     var start = toFloat(dots[i - 1].offset || 0),
1660                         end = 0;
1661                     for (var j = i + 1; j < ii; j++) {
1662                         if (dots[j].offset) {
1663                             end = dots[j].offset;
1664                             break;
1665                         }
1666                     }
1667                     if (!end) {
1668                         end = 100;
1669                         j = ii;
1670                     }
1671                     end = toFloat(end);
1672                     var d = (end - start) / (j - i + 1);
1673                     for (; i < j; i++) {
1674                         start += d;
1675                         dots[i].offset = start + "%";
1676                     }
1677                 }
1678             }
1679             return dots;
1680         }),
1681         tear = R._tear = function (el, paper) {
1682             el == paper.top && (paper.top = el.prev);
1683             el == paper.bottom && (paper.bottom = el.next);
1684             el.next && (el.next.prev = el.prev);
1685             el.prev && (el.prev.next = el.next);
1686         },
1687         tofront = R._tofront = function (el, paper) {
1688             if (paper.top === el) {
1689                 return;
1690             }
1691             tear(el, paper);
1692             el.next = null;
1693             el.prev = paper.top;
1694             paper.top.next = el;
1695             paper.top = el;
1696         },
1697         toback = R._toback = function (el, paper) {
1698             if (paper.bottom === el) {
1699                 return;
1700             }
1701             tear(el, paper);
1702             el.next = paper.bottom;
1703             el.prev = null;
1704             paper.bottom.prev = el;
1705             paper.bottom = el;
1706         },
1707         insertafter = R._insertafter = function (el, el2, paper) {
1708             tear(el, paper);
1709             el2 == paper.top && (paper.top = el);
1710             el2.next && (el2.next.prev = el);
1711             el.next = el2.next;
1712             el.prev = el2;
1713             el2.next = el;
1714         },
1715         insertbefore = R._insertbefore = function (el, el2, paper) {
1716             tear(el, paper);
1717             el2 == paper.bottom && (paper.bottom = el);
1718             el2.prev && (el2.prev.next = el);
1719             el.prev = el2.prev;
1720             el2.prev = el;
1721             el.next = el2;
1722         },
1723         removed = function (methodname) {
1724             return function () {
1725                 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1726             };
1727         },
1728         extractTransform = R._extractTransform = function (el, tstr) {
1729             if (tstr == null) {
1730                 return el._.transform;
1731             }
1732             tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1733             var tdata = R.parseTransformString(tstr),
1734                 deg = 0,
1735                 dx = 0,
1736                 dy = 0,
1737                 sx = 1,
1738                 sy = 1,
1739                 _ = el._,
1740                 m = new Matrix;
1741             _.transform = tdata || [];
1742             if (tdata) {
1743                 for (var i = 0, ii = tdata.length; i < ii; i++) {
1744                     var t = tdata[i],
1745                         tlen = t.length,
1746                         command = Str(t[0]).toLowerCase(),
1747                         absolute = t[0] != command,
1748                         inver = absolute ? m.invert() : 0,
1749                         x1,
1750                         y1,
1751                         x2,
1752                         y2,
1753                         bb;
1754                     if (command == "t" && tlen == 3) {
1755                         if (absolute) {
1756                             x1 = inver.x(0, 0);
1757                             y1 = inver.y(0, 0);
1758                             x2 = inver.x(t[1], t[2]);
1759                             y2 = inver.y(t[1], t[2]);
1760                             m.translate(x2 - x1, y2 - y1);
1761                         } else {
1762                             m.translate(t[1], t[2]);
1763                         }
1764                     } else if (command == "r") {
1765                         if (tlen == 2) {
1766                             bb = bb || el.getBBox(1);
1767                             m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1768                             deg += t[1];
1769                         } else if (tlen == 4) {
1770                             if (absolute) {
1771                                 x2 = inver.x(t[2], t[3]);
1772                                 y2 = inver.y(t[2], t[3]);
1773                                 m.rotate(t[1], x2, y2);
1774                             } else {
1775                                 m.rotate(t[1], t[2], t[3]);
1776                             }
1777                             deg += t[1];
1778                         }
1779                     } else if (command == "s") {
1780                         if (tlen == 2 || tlen == 3) {
1781                             bb = bb || el.getBBox(1);
1782                             m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1783                             sx *= t[1];
1784                             sy *= t[tlen - 1];
1785                         } else if (tlen == 5) {
1786                             if (absolute) {
1787                                 x2 = inver.x(t[3], t[4]);
1788                                 y2 = inver.y(t[3], t[4]);
1789                                 m.scale(t[1], t[2], x2, y2);
1790                             } else {
1791                                 m.scale(t[1], t[2], t[3], t[4]);
1792                             }
1793                             sx *= t[1];
1794                             sy *= t[2];
1795                         }
1796                     } else if (command == "m" && tlen == 7) {
1797                         m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1798                     }
1799                     _.dirtyT = 1;
1800                     el.matrix = m;
1801                 }
1802             }
1803
1804             el.matrix = m;
1805
1806             _.sx = sx;
1807             _.sy = sy;
1808             _.deg = deg;
1809             _.dx = dx = m.e;
1810             _.dy = dy = m.f;
1811
1812             if (sx == 1 && sy == 1 && !deg && _.bbox) {
1813                 _.bbox.x += +dx;
1814                 _.bbox.y += +dy;
1815             } else {
1816                 _.dirtyT = 1;
1817             }
1818         },
1819         getEmpty = function (item) {
1820             var l = item[0];
1821             switch (l.toLowerCase()) {
1822                 case "t": return [l, 0, 0];
1823                 case "m": return [l, 1, 0, 0, 1, 0, 0];
1824                 case "r": if (item.length == 4) {
1825                     return [l, 0, item[2], item[3]];
1826                 } else {
1827                     return [l, 0];
1828                 }
1829                 case "s": if (item.length == 5) {
1830                     return [l, 1, 1, item[3], item[4]];
1831                 } else if (item.length == 3) {
1832                     return [l, 1, 1];
1833                 } else {
1834                     return [l, 1];
1835                 }
1836             }
1837         },
1838         equaliseTransform = R._equaliseTransform = function (t1, t2) {
1839             t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1840             t1 = R.parseTransformString(t1) || [];
1841             t2 = R.parseTransformString(t2) || [];
1842             var maxlength = mmax(t1.length, t2.length),
1843                 from = [],
1844                 to = [],
1845                 i = 0, j, jj,
1846                 tt1, tt2;
1847             for (; i < maxlength; i++) {
1848                 tt1 = t1[i] || getEmpty(t2[i]);
1849                 tt2 = t2[i] || getEmpty(tt1);
1850                 if ((tt1[0] != tt2[0]) ||
1851                     (tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1852                     (tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1853                     ) {
1854                     return;
1855                 }
1856                 from[i] = [];
1857                 to[i] = [];
1858                 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1859                     j in tt1 && (from[i][j] = tt1[j]);
1860                     j in tt2 && (to[i][j] = tt2[j]);
1861                 }
1862             }
1863             return {
1864                 from: from,
1865                 to: to
1866             };
1867         };
1868     R._getContainer = function (x, y, w, h) {
1869         var container;
1870         container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1871         if (container == null) {
1872             return;
1873         }
1874         if (container.tagName) {
1875             if (y == null) {
1876                 return {
1877                     container: container,
1878                     width: container.style.pixelWidth || container.offsetWidth,
1879                     height: container.style.pixelHeight || container.offsetHeight
1880                 };
1881             } else {
1882                 return {
1883                     container: container,
1884                     width: y,
1885                     height: w
1886                 };
1887             }
1888         }
1889         return {
1890             container: 1,
1891             x: x,
1892             y: y,
1893             width: w,
1894             height: h
1895         };
1896     };
1897     /*\
1898      * Raphael.pathToRelative
1899      [ method ]
1900      **
1901      * Utility method
1902      **
1903      * Converts path to relative form
1904      > Parameters
1905      - pathString (string|array) path string or array of segments
1906      = (array) array of segments.
1907     \*/
1908     R.pathToRelative = pathToRelative;
1909     R._engine = {};
1910     /*\
1911      * Raphael.path2curve
1912      [ method ]
1913      **
1914      * Utility method
1915      **
1916      * Converts path to a new path where all segments are cubic bezier curves.
1917      > Parameters
1918      - pathString (string|array) path string or array of segments
1919      = (array) array of segments.
1920     \*/
1921     R.path2curve = path2curve;
1922     /*\
1923      * Raphael.matrix
1924      [ method ]
1925      **
1926      * Utility method
1927      **
1928      * Returns matrix based on given parameters.
1929      > Parameters
1930      - a (number)
1931      - b (number)
1932      - c (number)
1933      - d (number)
1934      - e (number)
1935      - f (number)
1936      = (object) @Matrix
1937     \*/
1938     R.matrix = function (a, b, c, d, e, f) {
1939         return new Matrix(a, b, c, d, e, f);
1940     };
1941     function Matrix(a, b, c, d, e, f) {
1942         if (a != null) {
1943             this.a = +a;
1944             this.b = +b;
1945             this.c = +c;
1946             this.d = +d;
1947             this.e = +e;
1948             this.f = +f;
1949         } else {
1950             this.a = 1;
1951             this.b = 0;
1952             this.c = 0;
1953             this.d = 1;
1954             this.e = 0;
1955             this.f = 0;
1956         }
1957     }
1958     (function (matrixproto) {
1959         /*\
1960          * Matrix.add
1961          [ method ]
1962          **
1963          * Adds given matrix to existing one.
1964          > Parameters
1965          - a (number)
1966          - b (number)
1967          - c (number)
1968          - d (number)
1969          - e (number)
1970          - f (number)
1971          or
1972          - matrix (object) @Matrix
1973         \*/
1974         matrixproto.add = function (a, b, c, d, e, f) {
1975             var out = [[], [], []],
1976                 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1977                 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1978                 x, y, z, res;
1979
1980             if (a && a instanceof Matrix) {
1981                 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1982             }
1983
1984             for (x = 0; x < 3; x++) {
1985                 for (y = 0; y < 3; y++) {
1986                     res = 0;
1987                     for (z = 0; z < 3; z++) {
1988                         res += m[x][z] * matrix[z][y];
1989                     }
1990                     out[x][y] = res;
1991                 }
1992             }
1993             this.a = out[0][0];
1994             this.b = out[1][0];
1995             this.c = out[0][1];
1996             this.d = out[1][1];
1997             this.e = out[0][2];
1998             this.f = out[1][2];
1999         };
2000         /*\
2001          * Matrix.invert
2002          [ method ]
2003          **
2004          * Returns inverted version of the matrix
2005          = (object) @Matrix
2006         \*/
2007         matrixproto.invert = function () {
2008             var me = this,
2009                 x = me.a * me.d - me.b * me.c;
2010             return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x);
2011         };
2012         /*\
2013          * Matrix.clone
2014          [ method ]
2015          **
2016          * Returns copy of the matrix
2017          = (object) @Matrix
2018         \*/
2019         matrixproto.clone = function () {
2020             return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
2021         };
2022         /*\
2023          * Matrix.translate
2024          [ method ]
2025          **
2026          * Translate the matrix
2027          > Parameters
2028          - x (number)
2029          - y (number)
2030         \*/
2031         matrixproto.translate = function (x, y) {
2032             this.add(1, 0, 0, 1, x, y);
2033         };
2034         /*\
2035          * Matrix.scale
2036          [ method ]
2037          **
2038          * Scales the matrix
2039          > Parameters
2040          - x (number)
2041          - y (number) #optional
2042          - cx (number) #optional
2043          - cy (number) #optional
2044         \*/
2045         matrixproto.scale = function (x, y, cx, cy) {
2046             y == null && (y = x);
2047             (cx || cy) && this.add(1, 0, 0, 1, cx, cy);
2048             this.add(x, 0, 0, y, 0, 0);
2049             (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy);
2050         };
2051         /*\
2052          * Matrix.rotate
2053          [ method ]
2054          **
2055          * Rotates the matrix
2056          > Parameters
2057          - a (number)
2058          - x (number)
2059          - y (number)
2060         \*/
2061         matrixproto.rotate = function (a, x, y) {
2062             a = R.rad(a);
2063             x = x || 0;
2064             y = y || 0;
2065             var cos = +math.cos(a).toFixed(9),
2066                 sin = +math.sin(a).toFixed(9);
2067             this.add(cos, sin, -sin, cos, x, y);
2068             this.add(1, 0, 0, 1, -x, -y);
2069         };
2070         /*\
2071          * Matrix.x
2072          [ method ]
2073          **
2074          * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
2075          > Parameters
2076          - x (number)
2077          - y (number)
2078          = (number) x
2079         \*/
2080         matrixproto.x = function (x, y) {
2081             return x * this.a + y * this.c + this.e;
2082         };
2083         /*\
2084          * Matrix.y
2085          [ method ]
2086          **
2087          * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
2088          > Parameters
2089          - x (number)
2090          - y (number)
2091          = (number) y
2092         \*/
2093         matrixproto.y = function (x, y) {
2094             return x * this.b + y * this.d + this.f;
2095         };
2096         matrixproto.get = function (i) {
2097             return +this[Str.fromCharCode(97 + i)].toFixed(4);
2098         };
2099         matrixproto.toString = function () {
2100             return R.svg ?
2101                 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
2102                 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
2103         };
2104         matrixproto.toFilter = function () {
2105             return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
2106                 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
2107                 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
2108         };
2109         matrixproto.offset = function () {
2110             return [this.e.toFixed(4), this.f.toFixed(4)];
2111         };
2112         function norm(a) {
2113             return a[0] * a[0] + a[1] * a[1];
2114         }
2115         function normalize(a) {
2116             var mag = math.sqrt(norm(a));
2117             a[0] && (a[0] /= mag);
2118             a[1] && (a[1] /= mag);
2119         }
2120         /*\
2121          * Matrix.split
2122          [ method ]
2123          **
2124          * Splits matrix into primitive transformations
2125          = (object) in format:
2126          o dx (number) translation by x
2127          o dy (number) translation by y
2128          o scalex (number) scale by x
2129          o scaley (number) scale by y
2130          o shear (number) shear
2131          o rotate (number) rotation in deg
2132          o isSimple (boolean) could it be represented via simple transformations
2133         \*/
2134         matrixproto.split = function () {
2135             var out = {};
2136             // translation
2137             out.dx = this.e;
2138             out.dy = this.f;
2139
2140             // scale and shear
2141             var row = [[this.a, this.c], [this.b, this.d]];
2142             out.scalex = math.sqrt(norm(row[0]));
2143             normalize(row[0]);
2144
2145             out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
2146             row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
2147
2148             out.scaley = math.sqrt(norm(row[1]));
2149             normalize(row[1]);
2150             out.shear /= out.scaley;
2151
2152             // rotation
2153             var sin = -row[0][1],
2154                 cos = row[1][1];
2155             if (cos < 0) {
2156                 out.rotate = R.deg(math.acos(cos));
2157                 if (sin < 0) {
2158                     out.rotate = 360 - out.rotate;
2159                 }
2160             } else {
2161                 out.rotate = R.deg(math.asin(sin));
2162             }
2163
2164             out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
2165             out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
2166             out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
2167             return out;
2168         };
2169         /*\
2170          * Matrix.toTransformString
2171          [ method ]
2172          **
2173          * Return transform string that represents given matrix
2174          = (string) transform string
2175         \*/
2176         matrixproto.toTransformString = function (shorter) {
2177             var s = shorter || this[split]();
2178             if (s.isSimple) {
2179                 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
2180             } else {
2181                 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
2182             }
2183         };
2184     })(Matrix.prototype);
2185
2186     // WebKit rendering bug workaround method
2187     var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
2188     if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2189         (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2190         /*\
2191          * Paper.safari
2192          [ method ]
2193          **
2194          * There is an inconvenient rendering bug in Safari (WebKit):
2195          * sometimes the rendering should be forced.
2196          * This method should help with dealing with this bug.
2197         \*/
2198         paperproto.safari = function () {
2199             var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2200             setTimeout(function () {rect.remove();});
2201         };
2202     } else {
2203         paperproto.safari = fun;
2204     }
2205  
2206     var preventDefault = function () {
2207         this.returnValue = false;
2208     },
2209     preventTouch = function () {
2210         return this.originalEvent.preventDefault();
2211     },
2212     stopPropagation = function () {
2213         this.cancelBubble = true;
2214     },
2215     stopTouch = function () {
2216         return this.originalEvent.stopPropagation();
2217     },
2218     addEvent = (function () {
2219         if (g.doc.addEventListener) {
2220             return function (obj, type, fn, element) {
2221                 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2222                     f = function (e) {
2223                         var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2224                             scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2225                             x = e.clientX + scrollX,
2226                             y = e.clientY + scrollY;
2227                     if (supportsTouch && touchMap[has](type)) {
2228                         for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2229                             if (e.targetTouches[i].target == obj) {
2230                                 var olde = e;
2231                                 e = e.targetTouches[i];
2232                                 e.originalEvent = olde;
2233                                 e.preventDefault = preventTouch;
2234                                 e.stopPropagation = stopTouch;
2235                                 break;
2236                             }
2237                         }
2238                     }
2239                     return fn.call(element, e, x, y);
2240                 };
2241                 obj.addEventListener(realName, f, false);
2242                 return function () {
2243                     obj.removeEventListener(realName, f, false);
2244                     return true;
2245                 };
2246             };
2247         } else if (g.doc.attachEvent) {
2248             return function (obj, type, fn, element) {
2249                 var f = function (e) {
2250                     e = e || g.win.event;
2251                     var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2252                         scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2253                         x = e.clientX + scrollX,
2254                         y = e.clientY + scrollY;
2255                     e.preventDefault = e.preventDefault || preventDefault;
2256                     e.stopPropagation = e.stopPropagation || stopPropagation;
2257                     return fn.call(element, e, x, y);
2258                 };
2259                 obj.attachEvent("on" + type, f);
2260                 var detacher = function () {
2261                     obj.detachEvent("on" + type, f);
2262                     return true;
2263                 };
2264                 return detacher;
2265             };
2266         }
2267     })(),
2268     drag = [],
2269     dragMove = function (e) {
2270         var x = e.clientX,
2271             y = e.clientY,
2272             scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2273             scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2274             dragi,
2275             j = drag.length;
2276         while (j--) {
2277             dragi = drag[j];
2278             if (supportsTouch) {
2279                 var i = e.touches.length,
2280                     touch;
2281                 while (i--) {
2282                     touch = e.touches[i];
2283                     if (touch.identifier == dragi.el._drag.id) {
2284                         x = touch.clientX;
2285                         y = touch.clientY;
2286                         (e.originalEvent ? e.originalEvent : e).preventDefault();
2287                         break;
2288                     }
2289                 }
2290             } else {
2291                 e.preventDefault();
2292             }
2293             var node = dragi.el.node,
2294                 o,
2295                 next = node.nextSibling,
2296                 parent = node.parentNode,
2297                 display = node.style.display;
2298             g.win.opera && parent.removeChild(node);
2299             node.style.display = "none";
2300             o = dragi.el.paper.getElementByPoint(x, y);
2301             node.style.display = display;
2302             g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2303             o && eve("drag.over." + dragi.el.id, dragi.el, o);
2304             x += scrollX;
2305             y += scrollY;
2306             eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2307         }
2308     },
2309     dragUp = function (e) {
2310         R.unmousemove(dragMove).unmouseup(dragUp);
2311         var i = drag.length,
2312             dragi;
2313         while (i--) {
2314             dragi = drag[i];
2315             dragi.el._drag = {};
2316             eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2317         }
2318         drag = [];
2319     },
2320     /*\
2321      * Raphael.el
2322      [ property (object) ]
2323      **
2324      * You can add your own method to elements. This is usefull when you want to hack default functionality or
2325      * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2326      * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2327      > Usage
2328      | Raphael.el.red = function () {
2329      |     this.attr({fill: "#f00"});
2330      | };
2331      | // then use it
2332      | paper.circle(100, 100, 20).red();
2333     \*/
2334     elproto = R.el = {};
2335     /*\
2336      * Element.click
2337      [ method ]
2338      **
2339      * Adds event handler for click for the element.
2340      > Parameters
2341      - handler (function) handler for the event
2342      = (object) @Element
2343     \*/
2344     /*\
2345      * Element.unclick
2346      [ method ]
2347      **
2348      * Removes event handler for click for the element.
2349      > Parameters
2350      - handler (function) handler for the event
2351      = (object) @Element
2352     \*/
2353     
2354     /*\
2355      * Element.dblclick
2356      [ method ]
2357      **
2358      * Adds event handler for double click for the element.
2359      > Parameters
2360      - handler (function) handler for the event
2361      = (object) @Element
2362     \*/
2363     /*\
2364      * Element.undblclick
2365      [ method ]
2366      **
2367      * Removes event handler for double click for the element.
2368      > Parameters
2369      - handler (function) handler for the event
2370      = (object) @Element
2371     \*/
2372     
2373     /*\
2374      * Element.mousedown
2375      [ method ]
2376      **
2377      * Adds event handler for mousedown for the element.
2378      > Parameters
2379      - handler (function) handler for the event
2380      = (object) @Element
2381     \*/
2382     /*\
2383      * Element.unmousedown
2384      [ method ]
2385      **
2386      * Removes event handler for mousedown for the element.
2387      > Parameters
2388      - handler (function) handler for the event
2389      = (object) @Element
2390     \*/
2391     
2392     /*\
2393      * Element.mousemove
2394      [ method ]
2395      **
2396      * Adds event handler for mousemove for the element.
2397      > Parameters
2398      - handler (function) handler for the event
2399      = (object) @Element
2400     \*/
2401     /*\
2402      * Element.unmousemove
2403      [ method ]
2404      **
2405      * Removes event handler for mousemove for the element.
2406      > Parameters
2407      - handler (function) handler for the event
2408      = (object) @Element
2409     \*/
2410     
2411     /*\
2412      * Element.mouseout
2413      [ method ]
2414      **
2415      * Adds event handler for mouseout for the element.
2416      > Parameters
2417      - handler (function) handler for the event
2418      = (object) @Element
2419     \*/
2420     /*\
2421      * Element.unmouseout
2422      [ method ]
2423      **
2424      * Removes event handler for mouseout for the element.
2425      > Parameters
2426      - handler (function) handler for the event
2427      = (object) @Element
2428     \*/
2429     
2430     /*\
2431      * Element.mouseover
2432      [ method ]
2433      **
2434      * Adds event handler for mouseover for the element.
2435      > Parameters
2436      - handler (function) handler for the event
2437      = (object) @Element
2438     \*/
2439     /*\
2440      * Element.unmouseover
2441      [ method ]
2442      **
2443      * Removes event handler for mouseover for the element.
2444      > Parameters
2445      - handler (function) handler for the event
2446      = (object) @Element
2447     \*/
2448     
2449     /*\
2450      * Element.mouseup
2451      [ method ]
2452      **
2453      * Adds event handler for mouseup for the element.
2454      > Parameters
2455      - handler (function) handler for the event
2456      = (object) @Element
2457     \*/
2458     /*\
2459      * Element.unmouseup
2460      [ method ]
2461      **
2462      * Removes event handler for mouseup for the element.
2463      > Parameters
2464      - handler (function) handler for the event
2465      = (object) @Element
2466     \*/
2467     
2468     /*\
2469      * Element.touchstart
2470      [ method ]
2471      **
2472      * Adds event handler for touchstart for the element.
2473      > Parameters
2474      - handler (function) handler for the event
2475      = (object) @Element
2476     \*/
2477     /*\
2478      * Element.untouchstart
2479      [ method ]
2480      **
2481      * Removes event handler for touchstart for the element.
2482      > Parameters
2483      - handler (function) handler for the event
2484      = (object) @Element
2485     \*/
2486     
2487     /*\
2488      * Element.touchmove
2489      [ method ]
2490      **
2491      * Adds event handler for touchmove for the element.
2492      > Parameters
2493      - handler (function) handler for the event
2494      = (object) @Element
2495     \*/
2496     /*\
2497      * Element.untouchmove
2498      [ method ]
2499      **
2500      * Removes event handler for touchmove for the element.
2501      > Parameters
2502      - handler (function) handler for the event
2503      = (object) @Element
2504     \*/
2505     
2506     /*\
2507      * Element.touchend
2508      [ method ]
2509      **
2510      * Adds event handler for touchend for the element.
2511      > Parameters
2512      - handler (function) handler for the event
2513      = (object) @Element
2514     \*/
2515     /*\
2516      * Element.untouchend
2517      [ method ]
2518      **
2519      * Removes event handler for touchend for the element.
2520      > Parameters
2521      - handler (function) handler for the event
2522      = (object) @Element
2523     \*/
2524     
2525     /*\
2526      * Element.touchcancel
2527      [ method ]
2528      **
2529      * Adds event handler for touchcancel for the element.
2530      > Parameters
2531      - handler (function) handler for the event
2532      = (object) @Element
2533     \*/
2534     /*\
2535      * Element.untouchcancel
2536      [ method ]
2537      **
2538      * Removes event handler for touchcancel for the element.
2539      > Parameters
2540      - handler (function) handler for the event
2541      = (object) @Element
2542     \*/
2543     for (var i = events.length; i--;) {
2544         (function (eventName) {
2545             R[eventName] = elproto[eventName] = function (fn, scope) {
2546                 if (R.is(fn, "function")) {
2547                     this.events = this.events || [];
2548                     this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2549                 }
2550                 return this;
2551             };
2552             R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2553                 var events = this.events,
2554                     l = events.length;
2555                 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2556                     events[l].unbind();
2557                     events.splice(l, 1);
2558                     !events.length && delete this.events;
2559                     return this;
2560                 }
2561                 return this;
2562             };
2563         })(events[i]);
2564     }
2565     
2566     /*\
2567      * Element.data
2568      [ method ]
2569      **
2570      * Adds or retrieves given value asociated with given key.
2571      ** 
2572      * See also @Element.removeData
2573      > Parameters
2574      - key (string) key to store data
2575      - value (any) #optional value to store
2576      = (object) @Element
2577      * or, if value is not specified:
2578      = (any) value
2579      > Usage
2580      | for (var i = 0, i < 5, i++) {
2581      |     paper.circle(10 + 15 * i, 10, 10)
2582      |          .attr({fill: "#000"})
2583      |          .data("i", i)
2584      |          .click(function () {
2585      |             alert(this.data("i"));
2586      |          });
2587      | }
2588     \*/
2589     elproto.data = function (key, value) {
2590         var data = eldata[this.id] = eldata[this.id] || {};
2591         if (arguments.length == 1) {
2592             if (R.is(key, "object")) {
2593                 for (var i in key) if (key[has](i)) {
2594                     this.data(i, key[i]);
2595                 }
2596                 return this;
2597             }
2598             eve("data.get." + this.id, this, data[key], key);
2599             return data[key];
2600         }
2601         data[key] = value;
2602         eve("data.set." + this.id, this, value, key);
2603         return this;
2604     };
2605     /*\
2606      * Element.removeData
2607      [ method ]
2608      **
2609      * Removes value associated with an element by given key.
2610      * If key is not provided, removes all the data of the element.
2611      > Parameters
2612      - key (string) #optional key
2613      = (object) @Element
2614     \*/
2615     elproto.removeData = function (key) {
2616         if (key == null) {
2617             eldata[this.id] = {};
2618         } else {
2619             eldata[this.id] && delete eldata[this.id][key];
2620         }
2621         return this;
2622     };
2623     /*\
2624      * Element.hover
2625      [ method ]
2626      **
2627      * Adds event handlers for hover for the element.
2628      > Parameters
2629      - f_in (function) handler for hover in
2630      - f_out (function) handler for hover out
2631      - icontext (object) #optional context for hover in handler
2632      - ocontext (object) #optional context for hover out handler
2633      = (object) @Element
2634     \*/
2635     elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2636         return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2637     };
2638     /*\
2639      * Element.unhover
2640      [ method ]
2641      **
2642      * Removes event handlers for hover for the element.
2643      > Parameters
2644      - f_in (function) handler for hover in
2645      - f_out (function) handler for hover out
2646      = (object) @Element
2647     \*/
2648     elproto.unhover = function (f_in, f_out) {
2649         return this.unmouseover(f_in).unmouseout(f_out);
2650     };
2651     /*\
2652      * Element.drag
2653      [ method ]
2654      **
2655      * Adds event handlers for drag of the element.
2656      > Parameters
2657      - onmove (function) handler for moving
2658      - onstart (function) handler for drag start
2659      - onend (function) handler for drag end
2660      - mcontext (object) #optional context for moving handler
2661      - scontext (object) #optional context for drag start handler
2662      - econtext (object) #optional context for drag end handler
2663      * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start, 
2664      * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element 
2665      * `drag.over.<id>` will be fired as well.
2666      *
2667      * Start event and start handler will be called in specified context or in context of the element with following parameters:
2668      o x (number) x position of the mouse
2669      o y (number) y position of the mouse
2670      o event (object) DOM event object
2671      * Move event and move handler will be called in specified context or in context of the element with following parameters:
2672      o dx (number) shift by x from the start point
2673      o dy (number) shift by y from the start point
2674      o x (number) x position of the mouse
2675      o y (number) y position of the mouse
2676      o event (object) DOM event object
2677      * End event and end handler will be called in specified context or in context of the element with following parameters:
2678      o event (object) DOM event object
2679      = (object) @Element
2680     \*/
2681     elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2682         function start(e) {
2683             (e.originalEvent || e).preventDefault();
2684             var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2685                 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2686             this._drag.x = e.clientX + scrollX;
2687             this._drag.y = e.clientY + scrollY;
2688             this._drag.id = e.identifier;
2689             !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2690             drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2691             onstart && eve.on("drag.start." + this.id, onstart);
2692             onmove && eve.on("drag.move." + this.id, onmove);
2693             onend && eve.on("drag.end." + this.id, onend);
2694             eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2695         }
2696         this._drag = {};
2697         this.mousedown(start);
2698         return this;
2699     };
2700     /*\
2701      * Element.onDragOver
2702      [ method ]
2703      **
2704      * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2705      > Parameters
2706      - f (function) handler for event, first argument would be the element you are dragging over
2707     \*/
2708     elproto.onDragOver = function (f) {
2709         f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2710     };
2711     /*\
2712      * Element.undrag
2713      [ method ]
2714      **
2715      * Removes all drag event handlers from given element.
2716     \*/
2717     elproto.undrag = function () {
2718         var i = drag.length;
2719         while (i--) if (drag[i].el == this) {
2720             R.unmousedown(drag[i].start);
2721             drag.splice(i++, 1);
2722             eve.unbind("drag.*." + this.id);
2723         }
2724         !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2725     };
2726     /*\
2727      * Paper.circle
2728      [ method ]
2729      **
2730      * Draws a circle.
2731      **
2732      > Parameters
2733      **
2734      - x (number) x coordinate of the centre
2735      - y (number) y coordinate of the centre
2736      - r (number) radius
2737      = (object) Raphaël element object with type “circle”
2738      **
2739      > Usage
2740      | var c = paper.circle(50, 50, 40);
2741     \*/
2742     paperproto.circle = function (x, y, r) {
2743         var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2744         this.__set__ && this.__set__.push(out);
2745         return out;
2746     };
2747     /*\
2748      * Paper.rect
2749      [ method ]
2750      *
2751      * Draws a rectangle.
2752      **
2753      > Parameters
2754      **
2755      - x (number) x coordinate of the top left corner
2756      - y (number) y coordinate of the top left corner
2757      - width (number) width
2758      - height (number) height
2759      - r (number) #optional radius for rounded corners, default is 0
2760      = (object) Raphaël element object with type “rect”
2761      **
2762      > Usage
2763      | // regular rectangle
2764      | var c = paper.rect(10, 10, 50, 50);
2765      | // rectangle with rounded corners
2766      | var c = paper.rect(40, 40, 50, 50, 10);
2767     \*/
2768     paperproto.rect = function (x, y, w, h, r) {
2769         var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2770         this.__set__ && this.__set__.push(out);
2771         return out;
2772     };
2773     /*\
2774      * Paper.ellipse
2775      [ method ]
2776      **
2777      * Draws an ellipse.
2778      **
2779      > Parameters
2780      **
2781      - x (number) x coordinate of the centre
2782      - y (number) y coordinate of the centre
2783      - rx (number) horizontal radius
2784      - ry (number) vertical radius
2785      = (object) Raphaël element object with type “ellipse”
2786      **
2787      > Usage
2788      | var c = paper.ellipse(50, 50, 40, 20);
2789     \*/
2790     paperproto.ellipse = function (x, y, rx, ry) {
2791         var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2792         this.__set__ && this.__set__.push(out);
2793         return out;
2794     };
2795     /*\
2796      * Paper.path
2797      [ method ]
2798      **
2799      * Creates a path element by given path data string.
2800      > Parameters
2801      - pathString (string) #optional path string in SVG format.
2802      * Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example:
2803      | "M10,20L30,40"
2804      * Here we can see two commands: “M”, with arguments `(10, 20)` and “L” with arguments `(30, 40)`. Upper case letter mean command is absolute, lower case—relative.
2805      *
2806      # <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a>.</p>
2807      # <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
2808      # <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
2809      # <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
2810      # <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
2811      # <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
2812      # <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
2813      # <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
2814      # <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
2815      # <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
2816      # <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
2817      # <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
2818      # <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table>
2819      * * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier.
2820      > Usage
2821      | var c = paper.path("M10 10L90 90");
2822      | // draw a diagonal line:
2823      | // move to 10,10, line to 90,90
2824     \*/
2825     paperproto.path = function (pathString) {
2826         pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2827         var out = R._engine.path(R.format[apply](R, arguments), this);
2828         this.__set__ && this.__set__.push(out);
2829         return out;
2830     };
2831     /*\
2832      * Paper.image
2833      [ method ]
2834      **
2835      * Embeds an image into the surface.
2836      **
2837      > Parameters
2838      **
2839      - src (string) URI of the source image
2840      - x (number) x coordinate position
2841      - y (number) y coordinate position
2842      - width (number) width of the image
2843      - height (number) height of the image
2844      = (object) Raphaël element object with type “image”
2845      **
2846      > Usage
2847      | var c = paper.image("apple.png", 10, 10, 80, 80);
2848     \*/
2849     paperproto.image = function (src, x, y, w, h) {
2850         var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2851         this.__set__ && this.__set__.push(out);
2852         return out;
2853     };
2854     /*\
2855      * Paper.text
2856      [ method ]
2857      **
2858      * Draws a text string. If you need line breaks, put “\n” in the string.
2859      **
2860      > Parameters
2861      **
2862      - x (number) x coordinate position
2863      - y (number) y coordinate position
2864      - text (string) The text string to draw
2865      = (object) Raphaël element object with type “text”
2866      **
2867      > Usage
2868      | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2869     \*/
2870     paperproto.text = function (x, y, text) {
2871         var out = R._engine.text(this, x || 0, y || 0, Str(text));
2872         this.__set__ && this.__set__.push(out);
2873         return out;
2874     };
2875     /*\
2876      * Paper.set
2877      [ method ]
2878      **
2879      * Creates array-like object to keep and operate several elements at once.
2880      * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2881      * Sets act as pseudo elements — all methods available to an element can be used on a set.
2882      = (object) array-like object that represents set of elements
2883      **
2884      > Usage
2885      | var st = paper.set();
2886      | st.push(
2887      |     paper.circle(10, 10, 5),
2888      |     paper.circle(30, 10, 5)
2889      | );
2890      | st.attr({fill: "red"}); // changes the fill of both circles
2891     \*/
2892     paperproto.set = function (itemsArray) {
2893         !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2894         var out = new Set(itemsArray);
2895         this.__set__ && this.__set__.push(out);
2896         return out;
2897     };
2898     /*\
2899      * Paper.setStart
2900      [ method ]
2901      **
2902      * Creates @Paper.set. All elements that will be created after calling this method and before calling
2903      * @Paper.setFinish will be added to the set.
2904      **
2905      > Usage
2906      | paper.setStart();
2907      | paper.circle(10, 10, 5),
2908      | paper.circle(30, 10, 5)
2909      | var st = paper.setFinish();
2910      | st.attr({fill: "red"}); // changes the fill of both circles
2911     \*/
2912     paperproto.setStart = function (set) {
2913         this.__set__ = set || this.set();
2914     };
2915     /*\
2916      * Paper.setFinish
2917      [ method ]
2918      **
2919      * See @Paper.setStart. This method finishes catching and returns resulting set.
2920      **
2921      = (object) set
2922     \*/
2923     paperproto.setFinish = function (set) {
2924         var out = this.__set__;
2925         delete this.__set__;
2926         return out;
2927     };
2928     /*\
2929      * Paper.setSize
2930      [ method ]
2931      **
2932      * If you need to change dimensions of the canvas call this method
2933      **
2934      > Parameters
2935      **
2936      - width (number) new width of the canvas
2937      - height (number) new height of the canvas
2938      > Usage
2939      | var st = paper.set();
2940      | st.push(
2941      |     paper.circle(10, 10, 5),
2942      |     paper.circle(30, 10, 5)
2943      | );
2944      | st.attr({fill: "red"});
2945     \*/
2946     paperproto.setSize = function (width, height) {
2947         return R._engine.setSize.call(this, width, height);
2948     };
2949     /*\
2950      * Paper.setViewBox
2951      [ method ]
2952      **
2953      * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by 
2954      * specifying new boundaries.
2955      **
2956      > Parameters
2957      **
2958      - x (number) new x position, default is `0`
2959      - y (number) new y position, default is `0`
2960      - w (number) new width of the canvas
2961      - h (number) new height of the canvas
2962      - fit (boolean) `true` if you want graphics to fit into new boundary box
2963     \*/
2964     paperproto.setViewBox = function (x, y, w, h, fit) {
2965         return R._engine.setViewBox.call(this, x, y, w, h, fit);
2966     };
2967     /*\
2968      * Paper.top
2969      [ property ]
2970      **
2971      * Points to the topmost element on the paper
2972     \*/
2973     /*\
2974      * Paper.bottom
2975      [ property ]
2976      **
2977      * Points to the bottom element on the paper
2978     \*/
2979     paperproto.top = paperproto.bottom = null;
2980     /*\
2981      * Paper.raphael
2982      [ property ]
2983      **
2984      * Points to the @Raphael object/function
2985     \*/
2986     paperproto.raphael = R;
2987     var getOffset = function (elem) {
2988         var box = elem.getBoundingClientRect(),
2989             doc = elem.ownerDocument,
2990             body = doc.body,
2991             docElem = doc.documentElement,
2992             clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2993             top  = box.top  + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2994             left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
2995         return {
2996             y: top,
2997             x: left
2998         };
2999     };
3000     /*\
3001      * Paper.getElementByPoint
3002      [ method ]
3003      **
3004      * Returns you topmost element under given point.
3005      **
3006      = (object) Raphaël element object
3007      > Parameters
3008      **
3009      - x (number) x coordinate from the top left corner of the window
3010      - y (number) y coordinate from the top left corner of the window
3011      > Usage
3012      | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
3013     \*/
3014     paperproto.getElementByPoint = function (x, y) {
3015         var paper = this,
3016             svg = paper.canvas,
3017             target = g.doc.elementFromPoint(x, y);
3018         if (g.win.opera && target.tagName == "svg") {
3019             var so = getOffset(svg),
3020                 sr = svg.createSVGRect();
3021             sr.x = x - so.x;
3022             sr.y = y - so.y;
3023             sr.width = sr.height = 1;
3024             var hits = svg.getIntersectionList(sr, null);
3025             if (hits.length) {
3026                 target = hits[hits.length - 1];
3027             }
3028         }
3029         if (!target) {
3030             return null;
3031         }
3032         while (target.parentNode && target != svg.parentNode && !target.raphael) {
3033             target = target.parentNode;
3034         }
3035         target == paper.canvas.parentNode && (target = svg);
3036         target = target && target.raphael ? paper.getById(target.raphaelid) : null;
3037         return target;
3038     };
3039     /*\
3040      * Paper.getById
3041      [ method ]
3042      **
3043      * Returns you element by its internal ID.
3044      **
3045      > Parameters
3046      **
3047      - id (number) id
3048      = (object) Raphaël element object
3049     \*/
3050     paperproto.getById = function (id) {
3051         var bot = this.bottom;
3052         while (bot) {
3053             if (bot.id == id) {
3054                 return bot;
3055             }
3056             bot = bot.next;
3057         }
3058         return null;
3059     };
3060     /*\
3061      * Paper.forEach
3062      [ method ]
3063      **
3064      * Executes given function for each element on the paper
3065      *
3066      * If callback function returns `false` it will stop loop running.
3067      **
3068      > Parameters
3069      **
3070      - callback (function) function to run
3071      - thisArg (object) context object for the callback
3072      = (object) Paper object
3073     \*/
3074     paperproto.forEach = function (callback, thisArg) {
3075         var bot = this.bottom;
3076         while (bot) {
3077             if (callback.call(thisArg, bot) === false) {
3078                 return this;
3079             }
3080             bot = bot.next;
3081         }
3082         return this;
3083     };
3084     function x_y() {
3085         return this.x + S + this.y;
3086     }
3087     function x_y_w_h() {
3088         return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
3089     }
3090     /*\
3091      * Element.getBBox
3092      [ method ]
3093      **
3094      * Return bounding box for a given element
3095      **
3096      > Parameters
3097      **
3098      - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
3099      = (object) Bounding box object:
3100      o {
3101      o     x: (number) top left corner x
3102      o     y: (number) top left corner y
3103      o     width: (number) width
3104      o     height: (number) height
3105      o }
3106     \*/
3107     elproto.getBBox = function (isWithoutTransform) {
3108         if (this.removed) {
3109             return {};
3110         }
3111         var _ = this._;
3112         if (isWithoutTransform) {
3113             if (_.dirty || !_.bboxwt) {
3114                 this.realPath = getPath[this.type](this);
3115                 _.bboxwt = pathDimensions(this.realPath);
3116                 _.bboxwt.toString = x_y_w_h;
3117                 _.dirty = 0;
3118             }
3119             return _.bboxwt;
3120         }
3121         if (_.dirty || _.dirtyT || !_.bbox) {
3122             if (_.dirty || !this.realPath) {
3123                 _.bboxwt = 0;
3124                 this.realPath = getPath[this.type](this);
3125             }
3126             _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
3127             _.bbox.toString = x_y_w_h;
3128             _.dirty = _.dirtyT = 0;
3129         }
3130         return _.bbox;
3131     };
3132     /*\
3133      * Element.clone
3134      [ method ]
3135      **
3136      = (object) clone of a given element
3137      **
3138     \*/
3139     elproto.clone = function () {
3140         if (this.removed) {
3141             return null;
3142         }
3143         var out = this.paper[this.type]().attr(this.attr());
3144         this.__set__ && this.__set__.push(out);
3145         return out;
3146     };
3147     /*\
3148      * Element.glow
3149      [ method ]
3150      **
3151      * Return set of elements that create glow-like effect around given element. See @Paper.set.
3152      *
3153      * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
3154      **
3155      > Parameters
3156      **
3157      - glow (object) #optional parameters object with all properties optional:
3158      o {
3159      o     width (number) size of the glow, default is `10`
3160      o     fill (boolean) will it be filled, default is `false`
3161      o     opacity (number) opacity, default is `0.5`
3162      o     offsetx (number) horizontal offset, default is `0`
3163      o     offsety (number) vertical offset, default is `0`
3164      o     color (string) glow colour, default is `black`
3165      o }
3166      = (object) @Paper.set of elements that represents glow
3167     \*/
3168     elproto.glow = function (glow) {
3169         if (this.type == "text") {
3170             return null;
3171         }
3172         glow = glow || {};
3173         var s = {
3174             width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
3175             fill: glow.fill || false,
3176             opacity: glow.opacity || .5,
3177             offsetx: glow.offsetx || 0,
3178             offsety: glow.offsety || 0,
3179             color: glow.color || "#000"
3180         },
3181             c = s.width / 2,
3182             r = this.paper,
3183             out = r.set(),
3184             path = this.realPath || getPath[this.type](this);
3185         path = this.matrix ? mapPath(path, this.matrix) : path;
3186         for (var i = 1; i < c + 1; i++) {
3187             out.push(r.path(path).attr({
3188                 stroke: s.color,
3189                 fill: s.fill ? s.color : "none",
3190                 "stroke-linejoin": "round",
3191                 "stroke-linecap": "round",
3192                 "stroke-width": +(s.width / c * i).toFixed(3),
3193                 opacity: +(s.opacity / c).toFixed(3)
3194             }));
3195         }
3196         return out.insertBefore(this).translate(s.offsetx, s.offsety);
3197     };
3198     var curveslengths = {},
3199     getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
3200         var len = 0,
3201             precision = 100,
3202             name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
3203             cache = curveslengths[name],
3204             old, dot;
3205         !cache && (curveslengths[name] = cache = {data: []});
3206         cache.timer && clearTimeout(cache.timer);
3207         cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
3208         if (length != null && !cache.precision) {
3209             var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
3210             cache.precision = ~~total * 10;
3211             cache.data = [];
3212         }
3213         precision = cache.precision || precision;
3214         for (var i = 0; i < precision + 1; i++) {
3215             if (cache.data[i * precision]) {
3216                 dot = cache.data[i * precision];
3217             } else {
3218                 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
3219                 cache.data[i * precision] = dot;
3220             }
3221             i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
3222             if (length != null && len >= length) {
3223                 return dot;
3224             }
3225             old = dot;
3226         }
3227         if (length == null) {
3228             return len;
3229         }
3230     },
3231     getLengthFactory = function (istotal, subpath) {
3232         return function (path, length, onlystart) {
3233             path = path2curve(path);
3234             var x, y, p, l, sp = "", subpaths = {}, point,
3235                 len = 0;
3236             for (var i = 0, ii = path.length; i < ii; i++) {
3237                 p = path[i];
3238                 if (p[0] == "M") {
3239                     x = +p[1];
3240                     y = +p[2];
3241                 } else {
3242                     l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
3243                     if (len + l > length) {
3244                         if (subpath && !subpaths.start) {
3245                             point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3246                             sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
3247                             if (onlystart) {return sp;}
3248                             subpaths.start = sp;
3249                             sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
3250                             len += l;
3251                             x = +p[5];
3252                             y = +p[6];
3253                             continue;
3254                         }
3255                         if (!istotal && !subpath) {
3256                             point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
3257                             return {x: point.x, y: point.y, alpha: point.alpha};
3258                         }
3259                     }
3260                     len += l;
3261                     x = +p[5];
3262                     y = +p[6];
3263                 }
3264                 sp += p.shift() + p;
3265             }
3266             subpaths.end = sp;
3267             point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
3268             point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
3269             return point;
3270         };
3271     };
3272     var getTotalLength = getLengthFactory(1),
3273         getPointAtLength = getLengthFactory(),
3274         getSubpathsAtLength = getLengthFactory(0, 1);
3275     /*\
3276      * Raphael.getTotalLength
3277      [ method ]
3278      **
3279      * Returns length of the given path in pixels.
3280      **
3281      > Parameters
3282      **
3283      - path (string) SVG path string.
3284      **
3285      = (number) length.
3286     \*/
3287     R.getTotalLength = getTotalLength;
3288     /*\
3289      * Raphael.getPointAtLength
3290      [ method ]
3291      **
3292      * Return coordinates of the point located at the given length on the given path.
3293      **
3294      > Parameters
3295      **
3296      - path (string) SVG path string
3297      - length (number)
3298      **
3299      = (object) representation of the point:
3300      o {
3301      o     x: (number) x coordinate
3302      o     y: (number) y coordinate
3303      o     alpha: (number) angle of derivative
3304      o }
3305     \*/
3306     R.getPointAtLength = getPointAtLength;
3307     /*\
3308      * Raphael.getSubpath
3309      [ method ]
3310      **
3311      * Return subpath of a given path from given length to given length.
3312      **
3313      > Parameters
3314      **
3315      - path (string) SVG path string
3316      - from (number) position of the start of the segment
3317      - to (number) position of the end of the segment
3318      **
3319      = (string) pathstring for the segment
3320     \*/
3321     R.getSubpath = function (path, from, to) {
3322         if (this.getTotalLength(path) - to < 1e-6) {
3323             return getSubpathsAtLength(path, from).end;
3324         }
3325         var a = getSubpathsAtLength(path, to, 1);
3326         return from ? getSubpathsAtLength(a, from).end : a;
3327     };
3328     /*\
3329      * Element.getTotalLength
3330      [ method ]
3331      **
3332      * Returns length of the path in pixels. Only works for element of “path” type.
3333      = (number) length.
3334     \*/
3335     elproto.getTotalLength = function () {
3336         if (this.type != "path") {return;}
3337         if (this.node.getTotalLength) {
3338             return this.node.getTotalLength();
3339         }
3340         return getTotalLength(this.attrs.path);
3341     };
3342     /*\
3343      * Element.getPointAtLength
3344      [ method ]
3345      **
3346      * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
3347      **
3348      > Parameters
3349      **
3350      - length (number)
3351      **
3352      = (object) representation of the point:
3353      o {
3354      o     x: (number) x coordinate
3355      o     y: (number) y coordinate
3356      o     alpha: (number) angle of derivative
3357      o }
3358     \*/
3359     elproto.getPointAtLength = function (length) {
3360         if (this.type != "path") {return;}
3361         return getPointAtLength(this.attrs.path, length);
3362     };
3363     /*\
3364      * Element.getSubpath
3365      [ method ]
3366      **
3367      * Return subpath of a given element from given length to given length. Only works for element of “path” type.
3368      **
3369      > Parameters
3370      **
3371      - from (number) position of the start of the segment
3372      - to (number) position of the end of the segment
3373      **
3374      = (string) pathstring for the segment
3375     \*/
3376     elproto.getSubpath = function (from, to) {
3377         if (this.type != "path") {return;}
3378         return R.getSubpath(this.attrs.path, from, to);
3379     };
3380     /*\
3381      * Raphael.easing_formulas
3382      [ property ]
3383      **
3384      * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
3385      # <ul>
3386      #     <li>“linear”</li>
3387      #     <li>“&lt;” or “easeIn” or “ease-in”</li>
3388      #     <li>“>” or “easeOut” or “ease-out”</li>
3389      #     <li>“&lt;>” or “easeInOut” or “ease-in-out”</li>
3390      #     <li>“backIn” or “back-in”</li>
3391      #     <li>“backOut” or “back-out”</li>
3392      #     <li>“elastic”</li>
3393      #     <li>“bounce”</li>
3394      # </ul>
3395      # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
3396     \*/
3397     var ef = R.easing_formulas = {
3398         linear: function (n) {
3399             return n;
3400         },
3401         "<": function (n) {
3402             return pow(n, 1.7);
3403         },
3404         ">": function (n) {
3405             return pow(n, .48);
3406         },
3407         "<>": function (n) {
3408             var q = .48 - n / 1.04,
3409                 Q = math.sqrt(.1734 + q * q),
3410                 x = Q - q,
3411                 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
3412                 y = -Q - q,
3413                 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
3414                 t = X + Y + .5;
3415             return (1 - t) * 3 * t * t + t * t * t;
3416         },
3417         backIn: function (n) {
3418             var s = 1.70158;
3419             return n * n * ((s + 1) * n - s);
3420         },
3421         backOut: function (n) {
3422             n = n - 1;
3423             var s = 1.70158;
3424             return n * n * ((s + 1) * n + s) + 1;
3425         },
3426         elastic: function (n) {
3427             if (n == !!n) {
3428                 return n;
3429             }
3430             return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
3431         },
3432         bounce: function (n) {
3433             var s = 7.5625,
3434                 p = 2.75,
3435                 l;
3436             if (n < (1 / p)) {
3437                 l = s * n * n;
3438             } else {
3439                 if (n < (2 / p)) {
3440                     n -= (1.5 / p);
3441                     l = s * n * n + .75;
3442                 } else {
3443                     if (n < (2.5 / p)) {
3444                         n -= (2.25 / p);
3445                         l = s * n * n + .9375;
3446                     } else {
3447                         n -= (2.625 / p);
3448                         l = s * n * n + .984375;
3449                     }
3450                 }
3451             }
3452             return l;
3453         }
3454     };
3455     ef.easeIn = ef["ease-in"] = ef["<"];
3456     ef.easeOut = ef["ease-out"] = ef[">"];
3457     ef.easeInOut = ef["ease-in-out"] = ef["<>"];
3458     ef["back-in"] = ef.backIn;
3459     ef["back-out"] = ef.backOut;
3460
3461     var animationElements = [],
3462         requestAnimFrame = window.requestAnimationFrame       ||
3463                            window.webkitRequestAnimationFrame ||
3464                            window.mozRequestAnimationFrame    ||
3465                            window.oRequestAnimationFrame      ||
3466                            window.msRequestAnimationFrame     ||
3467                            function (callback) {
3468                                setTimeout(callback, 16);
3469                            },
3470         animation = function () {
3471             var Now = +new Date,
3472                 l = 0;
3473             for (; l < animationElements.length; l++) {
3474                 var e = animationElements[l];
3475                 if (e.el.removed || e.paused) {
3476                     continue;
3477                 }
3478                 var time = Now - e.start,
3479                     ms = e.ms,
3480                     easing = e.easing,
3481                     from = e.from,
3482                     diff = e.diff,
3483                     to = e.to,
3484                     t = e.t,
3485                     that = e.el,
3486                     set = {},
3487                     now,
3488                     init = {},
3489                     key;
3490                 if (e.initstatus) {
3491                     time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3492                     e.status = e.initstatus;
3493                     delete e.initstatus;
3494                     e.stop && animationElements.splice(l--, 1);
3495                 } else {
3496                     e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3497                 }
3498                 if (time < 0) {
3499                     continue;
3500                 }
3501                 if (time < ms) {
3502                     var pos = easing(time / ms);
3503                     for (var attr in from) if (from[has](attr)) {
3504                         switch (availableAnimAttrs[attr]) {
3505                             case nu:
3506                                 now = +from[attr] + pos * ms * diff[attr];
3507                                 break;
3508                             case "colour":
3509                                 now = "rgb(" + [
3510                                     upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3511                                     upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3512                                     upto255(round(from[attr].b + pos * ms * diff[attr].b))
3513                                 ].join(",") + ")";
3514                                 break;
3515                             case "path":
3516                                 now = [];
3517                                 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3518                                     now[i] = [from[attr][i][0]];
3519                                     for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3520                                         now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3521                                     }
3522                                     now[i] = now[i].join(S);
3523                                 }
3524                                 now = now.join(S);
3525                                 break;
3526                             case "transform":
3527                                 if (diff[attr].real) {
3528                                     now = [];
3529                                     for (i = 0, ii = from[attr].length; i < ii; i++) {
3530                                         now[i] = [from[attr][i][0]];
3531                                         for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3532                                             now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3533                                         }
3534                                     }
3535                                 } else {
3536                                     var get = function (i) {
3537                                         return +from[attr][i] + pos * ms * diff[attr][i];
3538                                     };
3539                                     // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3540                                     now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3541                                 }
3542                                 break;
3543                             case "csv":
3544                                 if (attr == "clip-rect") {
3545                                     now = [];
3546                                     i = 4;
3547                                     while (i--) {
3548                                         now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3549                                     }
3550                                 }
3551                                 break;
3552                             default:
3553                                 var from2 = [][concat](from[attr]);
3554                                 now = [];
3555                                 i = that.paper.customAttributes[attr].length;
3556                                 while (i--) {
3557                                     now[i] = +from2[i] + pos * ms * diff[attr][i];
3558                                 }
3559                                 break;
3560                         }
3561                         set[attr] = now;
3562                     }
3563                     that.attr(set);
3564                     (function (id, that, anim) {
3565                         setTimeout(function () {
3566                             eve("anim.frame." + id, that, anim);
3567                         });
3568                     })(that.id, that, e.anim);
3569                 } else {
3570                     (function(f, el, a) {
3571                         setTimeout(function() {
3572                             eve("anim.frame." + el.id, el, a);
3573                             eve("anim.finish." + el.id, el, a);
3574                             R.is(f, "function") && f.call(el);
3575                         });
3576                     })(e.callback, that, e.anim);
3577                     that.attr(to);
3578                     animationElements.splice(l--, 1);
3579                     if (e.repeat > 1 && !e.next) {
3580                         for (key in to) if (to[has](key)) {
3581                             init[key] = e.totalOrigin[key];
3582                         }
3583                         e.el.attr(init);
3584                         runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3585                     }
3586                     if (e.next && !e.stop) {
3587                         runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3588                     }
3589                 }
3590             }
3591             R.svg && that && that.paper && that.paper.safari();
3592             animationElements.length && requestAnimFrame(animation);
3593         },
3594         upto255 = function (color) {
3595             return color > 255 ? 255 : color < 0 ? 0 : color;
3596         };
3597     /*\
3598      * Element.animateWith
3599      [ method ]
3600      **
3601      * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3602      **
3603      > Parameters
3604      **
3605      - element (object) element to sync with
3606      - anim (object) animation to sync with
3607      - params (object) #optional final attributes for the element, see also @Element.attr
3608      - ms (number) #optional number of milliseconds for animation to run
3609      - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
3610      - callback (function) #optional callback function. Will be called at the end of animation.
3611      * or
3612      - element (object) element to sync with
3613      - anim (object) animation to sync with
3614      - animation (object) #optional animation object, see @Raphael.animation
3615      **
3616      = (object) original element
3617     \*/
3618     elproto.animateWith = function (element, anim, params, ms, easing, callback) {
3619         var a = params ? R.animation(params, ms, easing, callback) : anim;
3620             status = element.status(anim);
3621         return this.animate(a).status(a, status * anim.ms / a.ms);
3622     };
3623     function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3624         var cx = 3 * p1x,
3625             bx = 3 * (p2x - p1x) - cx,
3626             ax = 1 - cx - bx,
3627             cy = 3 * p1y,
3628             by = 3 * (p2y - p1y) - cy,
3629             ay = 1 - cy - by;
3630         function sampleCurveX(t) {
3631             return ((ax * t + bx) * t + cx) * t;
3632         }
3633         function solve(x, epsilon) {
3634             var t = solveCurveX(x, epsilon);
3635             return ((ay * t + by) * t + cy) * t;
3636         }
3637         function solveCurveX(x, epsilon) {
3638             var t0, t1, t2, x2, d2, i;
3639             for(t2 = x, i = 0; i < 8; i++) {
3640                 x2 = sampleCurveX(t2) - x;
3641                 if (abs(x2) < epsilon) {
3642                     return t2;
3643                 }
3644                 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3645                 if (abs(d2) < 1e-6) {
3646                     break;
3647                 }
3648                 t2 = t2 - x2 / d2;
3649             }
3650             t0 = 0;
3651             t1 = 1;
3652             t2 = x;
3653             if (t2 < t0) {
3654                 return t0;
3655             }
3656             if (t2 > t1) {
3657                 return t1;
3658             }
3659             while (t0 < t1) {
3660                 x2 = sampleCurveX(t2);
3661                 if (abs(x2 - x) < epsilon) {
3662                     return t2;
3663                 }
3664                 if (x > x2) {
3665                     t0 = t2;
3666                 } else {
3667                     t1 = t2;
3668                 }
3669                 t2 = (t1 - t0) / 2 + t0;
3670             }
3671             return t2;
3672         }
3673         return solve(t, 1 / (200 * duration));
3674     }
3675     elproto.onAnimation = function (f) {
3676         f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3677         return this;
3678     };
3679     function Animation(anim, ms) {
3680         var percents = [],
3681             newAnim = {};
3682         this.ms = ms;
3683         this.times = 1;
3684         if (anim) {
3685             for (var attr in anim) if (anim[has](attr)) {
3686                 newAnim[toFloat(attr)] = anim[attr];
3687                 percents.push(toFloat(attr));
3688             }
3689             percents.sort(sortByNumber);
3690         }
3691         this.anim = newAnim;
3692         this.top = percents[percents.length - 1];
3693         this.percents = percents;
3694     }
3695     /*\
3696      * Animation.delay
3697      [ method ]
3698      **
3699      * Creates a copy of existing animation object with given delay.
3700      **
3701      > Parameters
3702      **
3703      - delay (number) number of ms to pass between animation start and actual animation
3704      **
3705      = (object) new altered Animation object
3706      | var anim = Raphael.animation({cx: 10, cy: 20}, 2e3);
3707      | circle1.animate(anim); // run the given animation immediately
3708      | circle2.animate(anim.delay(500)); // run the given animation after 500 ms
3709     \*/
3710     Animation.prototype.delay = function (delay) {
3711         var a = new Animation(this.anim, this.ms);
3712         a.times = this.times;
3713         a.del = +delay || 0;
3714         return a;
3715     };
3716     /*\
3717      * Animation.repeat
3718      [ method ]
3719      **
3720      * Creates a copy of existing animation object with given repetition.
3721      **
3722      > Parameters
3723      **
3724      - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3725      **
3726      = (object) new altered Animation object
3727     \*/
3728     Animation.prototype.repeat = function (times) { 
3729         var a = new Animation(this.anim, this.ms);
3730         a.del = this.del;
3731         a.times = math.floor(mmax(times, 0)) || 1;
3732         return a;
3733     };
3734     function runAnimation(anim, element, percent, status, totalOrigin, times) {
3735         percent = toFloat(percent);
3736         var params,
3737             isInAnim,
3738             isInAnimSet,
3739             percents = [],
3740             next,
3741             prev,
3742             timestamp,
3743             ms = anim.ms,
3744             from = {},
3745             to = {},
3746             diff = {};
3747         if (status) {
3748             for (i = 0, ii = animationElements.length; i < ii; i++) {
3749                 var e = animationElements[i];
3750                 if (e.el.id == element.id && e.anim == anim) {
3751                     if (e.percent != percent) {
3752                         animationElements.splice(i, 1);
3753                         isInAnimSet = 1;
3754                     } else {
3755                         isInAnim = e;
3756                     }
3757                     element.attr(e.totalOrigin);
3758                     break;
3759                 }
3760             }
3761         } else {
3762             status = +to; // NaN
3763         }
3764         for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3765             if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3766                 percent = anim.percents[i];
3767                 prev = anim.percents[i - 1] || 0;
3768                 ms = ms / anim.top * (percent - prev);
3769                 next = anim.percents[i + 1];
3770                 params = anim.anim[percent];
3771                 break;
3772             } else if (status) {
3773                 element.attr(anim.anim[anim.percents[i]]);
3774             }
3775         }
3776         if (!params) {
3777             return;
3778         }
3779         if (!isInAnim) {
3780             for (attr in params) if (params[has](attr)) {
3781                 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3782                     from[attr] = element.attr(attr);
3783                     (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3784                     to[attr] = params[attr];
3785                     switch (availableAnimAttrs[attr]) {
3786                         case nu:
3787                             diff[attr] = (to[attr] - from[attr]) / ms;
3788                             break;
3789                         case "colour":
3790                             from[attr] = R.getRGB(from[attr]);
3791                             var toColour = R.getRGB(to[attr]);
3792                             diff[attr] = {
3793                                 r: (toColour.r - from[attr].r) / ms,
3794                                 g: (toColour.g - from[attr].g) / ms,
3795                                 b: (toColour.b - from[attr].b) / ms
3796                             };
3797                             break;
3798                         case "path":
3799                             var pathes = path2curve(from[attr], to[attr]),
3800                                 toPath = pathes[1];
3801                             from[attr] = pathes[0];
3802                             diff[attr] = [];
3803                             for (i = 0, ii = from[attr].length; i < ii; i++) {
3804                                 diff[attr][i] = [0];
3805                                 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3806                                     diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3807                                 }
3808                             }
3809                             break;
3810                         case "transform":
3811                             var _ = element._,
3812                                 eq = equaliseTransform(_[attr], to[attr]);
3813                             if (eq) {
3814                                 from[attr] = eq.from;
3815                                 to[attr] = eq.to;
3816                                 diff[attr] = [];
3817                                 diff[attr].real = true;
3818                                 for (i = 0, ii = from[attr].length; i < ii; i++) {
3819                                     diff[attr][i] = [from[attr][i][0]];
3820                                     for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3821                                         diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3822                                     }
3823                                 }
3824                             } else {
3825                                 var m = (element.matrix || new Matrix),
3826                                     to2 = {
3827                                         _: {transform: _.transform},
3828                                         getBBox: function () {
3829                                             return element.getBBox(1);
3830                                         }
3831                                     };
3832                                 from[attr] = [
3833                                     m.a,
3834                                     m.b,
3835                                     m.c,
3836                                     m.d,
3837                                     m.e,
3838                                     m.f
3839                                 ];
3840                                 extractTransform(to2, to[attr]);
3841                                 to[attr] = to2._.transform;
3842                                 diff[attr] = [
3843                                     (to2.matrix.a - m.a) / ms,
3844                                     (to2.matrix.b - m.b) / ms,
3845                                     (to2.matrix.c - m.c) / ms,
3846                                     (to2.matrix.d - m.d) / ms,
3847                                     (to2.matrix.e - m.e) / ms,
3848                                     (to2.matrix.e - m.f) / ms
3849                                 ];
3850                                 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3851                                 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3852                                 // extractTransform(to2, to[attr]);
3853                                 // diff[attr] = [
3854                                 //     (to2._.sx - _.sx) / ms,
3855                                 //     (to2._.sy - _.sy) / ms,
3856                                 //     (to2._.deg - _.deg) / ms,
3857                                 //     (to2._.dx - _.dx) / ms,
3858                                 //     (to2._.dy - _.dy) / ms
3859                                 // ];
3860                             }
3861                             break;
3862                         case "csv":
3863                             var values = Str(params[attr])[split](separator),
3864                                 from2 = Str(from[attr])[split](separator);
3865                             if (attr == "clip-rect") {
3866                                 from[attr] = from2;
3867                                 diff[attr] = [];
3868                                 i = from2.length;
3869                                 while (i--) {
3870                                     diff[attr][i] = (values[i] - from[attr][i]) / ms;
3871                                 }
3872                             }
3873                             to[attr] = values;
3874                             break;
3875                         default:
3876                             values = [][concat](params[attr]);
3877                             from2 = [][concat](from[attr]);
3878                             diff[attr] = [];
3879                             i = element.paper.customAttributes[attr].length;
3880                             while (i--) {
3881                                 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3882                             }
3883                             break;
3884                     }
3885                 }
3886             }
3887             var easing = params.easing,
3888                 easyeasy = R.easing_formulas[easing];
3889             if (!easyeasy) {
3890                 easyeasy = Str(easing).match(bezierrg);
3891                 if (easyeasy && easyeasy.length == 5) {
3892                     var curve = easyeasy;
3893                     easyeasy = function (t) {
3894                         return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3895                     };
3896                 } else {
3897                     easyeasy = pipe;
3898                 }
3899             }
3900             timestamp = params.start || anim.start || +new Date;
3901             e = {
3902                 anim: anim,
3903                 percent: percent,
3904                 timestamp: timestamp,
3905                 start: timestamp + (anim.del || 0),
3906                 status: 0,
3907                 initstatus: status || 0,
3908                 stop: false,
3909                 ms: ms,
3910                 easing: easyeasy,
3911                 from: from,
3912                 diff: diff,
3913                 to: to,
3914                 el: element,
3915                 callback: params.callback,
3916                 prev: prev,
3917                 next: next,
3918                 repeat: times || anim.times,
3919                 origin: element.attr(),
3920                 totalOrigin: totalOrigin
3921             };
3922             animationElements.push(e);
3923             if (status && !isInAnim && !isInAnimSet) {
3924                 e.stop = true;
3925                 e.start = new Date - ms * status;
3926                 if (animationElements.length == 1) {
3927                     return animation();
3928                 }
3929             }
3930             if (isInAnimSet) {
3931                 e.start = new Date - e.ms * status;
3932             }
3933             animationElements.length == 1 && requestAnimFrame(animation);
3934         } else {
3935             isInAnim.initstatus = status;
3936             isInAnim.start = new Date - isInAnim.ms * status;
3937         }
3938         eve("anim.start." + element.id, element, anim);
3939     }
3940     /*\
3941      * Raphael.animation
3942      [ method ]
3943      **
3944      * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3945      * See also @Animation.delay and @Animation.repeat methods.
3946      **
3947      > Parameters
3948      **
3949      - params (object) final attributes for the element, see also @Element.attr
3950      - ms (number) number of milliseconds for animation to run
3951      - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
3952      - callback (function) #optional callback function. Will be called at the end of animation.
3953      **
3954      = (object) @Animation
3955     \*/
3956     R.animation = function (params, ms, easing, callback) {
3957         if (params instanceof Animation) {
3958             return params;
3959         }
3960         if (R.is(easing, "function") || !easing) {
3961             callback = callback || easing || null;
3962             easing = null;
3963         }
3964         params = Object(params);
3965         ms = +ms || 0;
3966         var p = {},
3967             json,
3968             attr;
3969         for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) {
3970             json = true;
3971             p[attr] = params[attr];
3972         }
3973         if (!json) {
3974             return new Animation(params, ms);
3975         } else {
3976             easing && (p.easing = easing);
3977             callback && (p.callback = callback);
3978             return new Animation({100: p}, ms);
3979         }
3980     };
3981     /*\
3982      * Element.animate
3983      [ method ]
3984      **
3985      * Creates and starts animation for given element.
3986      **
3987      > Parameters
3988      **
3989      - params (object) final attributes for the element, see also @Element.attr
3990      - ms (number) number of milliseconds for animation to run
3991      - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
3992      - callback (function) #optional callback function. Will be called at the end of animation.
3993      * or
3994      - animation (object) animation object, see @Raphael.animation
3995      **
3996      = (object) original element
3997     \*/
3998     elproto.animate = function (params, ms, easing, callback) {
3999         var element = this;
4000         if (element.removed) {
4001             callback && callback.call(element);
4002             return element;
4003         }
4004         var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
4005         runAnimation(anim, element, anim.percents[0], null, element.attr());
4006         return element;
4007     };
4008     /*\
4009      * Element.setTime
4010      [ method ]
4011      **
4012      * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
4013      **
4014      > Parameters
4015      **
4016      - anim (object) animation object
4017      - value (number) number of milliseconds from the beginning of the animation
4018      **
4019      = (object) original element if `value` is specified
4020      * Note, that during animation following events are triggered:
4021      *
4022      * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
4023     \*/
4024     elproto.setTime = function (anim, value) {
4025         if (anim && value != null) {
4026             this.status(anim, mmin(value, anim.ms) / anim.ms);
4027         }
4028         return this;
4029     };
4030     /*\
4031      * Element.status
4032      [ method ]
4033      **
4034      * Gets or sets the status of animation of the element.
4035      **
4036      > Parameters
4037      **
4038      - anim (object) #optional animation object
4039      - value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position.
4040      **
4041      = (number) status
4042      * or
4043      = (array) status if `anim` is not specified. Array of objects in format:
4044      o {
4045      o     anim: (object) animation object
4046      o     status: (number) status
4047      o }
4048      * or
4049      = (object) original element if `value` is specified
4050     \*/
4051     elproto.status = function (anim, value) {
4052         var out = [],
4053             i = 0,
4054             len,
4055             e;
4056         if (value != null) {
4057             runAnimation(anim, this, -1, mmin(value, 1));
4058             return this;
4059         } else {
4060             len = animationElements.length;
4061             for (; i < len; i++) {
4062                 e = animationElements[i];
4063                 if (e.el.id == this.id && (!anim || e.anim == anim)) {
4064                     if (anim) {
4065                         return e.status;
4066                     }
4067                     out.push({
4068                         anim: e.anim,
4069                         status: e.status
4070                     });
4071                 }
4072             }
4073             if (anim) {
4074                 return 0;
4075             }
4076             return out;
4077         }
4078     };
4079     /*\
4080      * Element.pause
4081      [ method ]
4082      **
4083      * Stops animation of the element with ability to resume it later on.
4084      **
4085      > Parameters
4086      **
4087      - anim (object) #optional animation object
4088      **
4089      = (object) original element
4090     \*/
4091     elproto.pause = function (anim) {
4092         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4093             if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
4094                 animationElements[i].paused = true;
4095             }
4096         }
4097         return this;
4098     };
4099     /*\
4100      * Element.resume
4101      [ method ]
4102      **
4103      * Resumes animation if it was paused with @Element.pause method.
4104      **
4105      > Parameters
4106      **
4107      - anim (object) #optional animation object
4108      **
4109      = (object) original element
4110     \*/
4111     elproto.resume = function (anim) {
4112         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4113             var e = animationElements[i];
4114             if (eve("anim.resume." + this.id, this, e.anim) !== false) {
4115                 delete e.paused;
4116                 this.status(e.anim, e.status);
4117             }
4118         }
4119         return this;
4120     };
4121     /*\
4122      * Element.stop
4123      [ method ]
4124      **
4125      * Stops animation of the element.
4126      **
4127      > Parameters
4128      **
4129      - anim (object) #optional animation object
4130      **
4131      = (object) original element
4132     \*/
4133     elproto.stop = function (anim) {
4134         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
4135             if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
4136                 animationElements.splice(i--, 1);
4137             }
4138         }
4139         return this;
4140     };
4141     elproto.toString = function () {
4142         return "Rapha\xebl\u2019s object";
4143     };
4144
4145     // Set
4146     var Set = function (items) {
4147         this.items = [];
4148         this.length = 0;
4149         this.type = "set";
4150         if (items) {
4151             for (var i = 0, ii = items.length; i < ii; i++) {
4152                 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
4153                     this[this.items.length] = this.items[this.items.length] = items[i];
4154                     this.length++;
4155                 }
4156             }
4157         }
4158     },
4159     setproto = Set.prototype;
4160     /*\
4161      * Set.push
4162      [ method ]
4163      **
4164      * Adds each argument to the current set.
4165      = (object) original element
4166     \*/
4167     setproto.push = function () {
4168         var item,
4169             len;
4170         for (var i = 0, ii = arguments.length; i < ii; i++) {
4171             item = arguments[i];
4172             if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
4173                 len = this.items.length;
4174                 this[len] = this.items[len] = item;
4175                 this.length++;
4176             }
4177         }
4178         return this;
4179     };
4180     /*\
4181      * Set.pop
4182      [ method ]
4183      **
4184      * Removes last element and returns it.
4185      = (object) element
4186     \*/
4187     setproto.pop = function () {
4188         this.length && delete this[this.length--];
4189         return this.items.pop();
4190     };
4191     /*\
4192      * Set.forEach
4193      [ method ]
4194      **
4195      * Executes given function for each element in the set.
4196      *
4197      * If function returns `false` it will stop loop running.
4198      **
4199      > Parameters
4200      **
4201      - callback (function) function to run
4202      - thisArg (object) context object for the callback
4203      = (object) Set object
4204     \*/
4205     setproto.forEach = function (callback, thisArg) {
4206         for (var i = 0, ii = this.items.length; i < ii; i++) {
4207             if (callback.call(thisArg, this.items[i], i) === false) {
4208                 return this;
4209             }
4210         }
4211         return this;
4212     };
4213     for (var method in elproto) if (elproto[has](method)) {
4214         setproto[method] = (function (methodname) {
4215             return function () {
4216                 var arg = arguments;
4217                 return this.forEach(function (el) {
4218                     el[methodname][apply](el, arg);
4219                 });
4220             };
4221         })(method);
4222     }
4223     setproto.attr = function (name, value) {
4224         if (name && R.is(name, array) && R.is(name[0], "object")) {
4225             for (var j = 0, jj = name.length; j < jj; j++) {
4226                 this.items[j].attr(name[j]);
4227             }
4228         } else {
4229             for (var i = 0, ii = this.items.length; i < ii; i++) {
4230                 this.items[i].attr(name, value);
4231             }
4232         }
4233         return this;
4234     };
4235     /*\
4236      * Set.clear
4237      [ method ]
4238      **
4239      * Removeds all elements from the set
4240     \*/
4241     setproto.clear = function () {
4242         while (this.length) {
4243             this.pop();
4244         }
4245     };
4246     /*\
4247      * Set.splice
4248      [ method ]
4249      **
4250      * Removes given element from the set
4251      **
4252      > Parameters
4253      **
4254      - index (number) position of the deletion
4255      - count (number) number of element to remove
4256      - insertion… (object) #optional elements to insert
4257      = (object) set elements that were deleted
4258     \*/
4259     setproto.splice = function (index, count, insertion) {
4260         index = index < 0 ? mmax(this.length + index, 0) : index;
4261         count = mmax(0, mmin(this.length - index, count));
4262         var tail = [],
4263             todel = [],
4264             args = [],
4265             i;
4266         for (i = 2; i < arguments.length; i++) {
4267             args.push(arguments[i]);
4268         }
4269         for (i = 0; i < count; i++) {
4270             todel.push(this[index + i]);
4271         }
4272         for (; i < this.length - index; i++) {
4273             tail.push(this[index + i]);
4274         }
4275         var arglen = args.length;
4276         for (i = 0; i < arglen + tail.length; i++) {
4277             this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen];
4278         }
4279         i = this.items.length = this.length -= count - arglen;
4280         while (this[i]) {
4281             delete this[i++];
4282         }
4283         return new Set(todel);
4284     };
4285     /*\
4286      * Set.exclude
4287      [ method ]
4288      **
4289      * Removes given element from the set
4290      **
4291      > Parameters
4292      **
4293      - element (object) element to remove
4294      = (boolean) `true` if object was found & removed from the set
4295     \*/
4296     setproto.exclude = function (el) {
4297         for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) {
4298             this.splice(i, 1);
4299             return true;
4300         }
4301     };
4302     setproto.animate = function (params, ms, easing, callback) {
4303         (R.is(easing, "function") || !easing) && (callback = easing || null);
4304         var len = this.items.length,
4305             i = len,
4306             item,
4307             set = this,
4308             collector;
4309         if (!len) {
4310             return this;
4311         }
4312         callback && (collector = function () {
4313             !--len && callback.call(set);
4314         });
4315         easing = R.is(easing, string) ? easing : collector;
4316         var anim = R.animation(params, ms, easing, collector);
4317         item = this.items[--i].animate(anim);
4318         while (i--) {
4319             this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
4320         }
4321         return this;
4322     };
4323     setproto.insertAfter = function (el) {
4324         var i = this.items.length;
4325         while (i--) {
4326             this.items[i].insertAfter(el);
4327         }
4328         return this;
4329     };
4330     setproto.getBBox = function () {
4331         var x = [],
4332             y = [],
4333             w = [],
4334             h = [];
4335         for (var i = this.items.length; i--;) if (!this.items[i].removed) {
4336             var box = this.items[i].getBBox();
4337             x.push(box.x);
4338             y.push(box.y);
4339             w.push(box.x + box.width);
4340             h.push(box.y + box.height);
4341         }
4342         x = mmin[apply](0, x);
4343         y = mmin[apply](0, y);
4344         return {
4345             x: x,
4346             y: y,
4347             width: mmax[apply](0, w) - x,
4348             height: mmax[apply](0, h) - y
4349         };
4350     };
4351     setproto.clone = function (s) {
4352         s = new Set;
4353         for (var i = 0, ii = this.items.length; i < ii; i++) {
4354             s.push(this.items[i].clone());
4355         }
4356         return s;
4357     };
4358     setproto.toString = function () {
4359         return "Rapha\xebl\u2018s set";
4360     };
4361
4362     /*\
4363      * Raphael.registerFont
4364      [ method ]
4365      **
4366      * Adds given font to the registered set of fonts for Raphaël. Should be used as an internal call from within Cufón’s font file.
4367      * Returns original parameter, so it could be used with chaining.
4368      # <a href="http://wiki.github.com/sorccu/cufon/about">More about Cufón and how to convert your font form TTF, OTF, etc to JavaScript file.</a>
4369      **
4370      > Parameters
4371      **
4372      - font (object) the font to register
4373      = (object) the font you passed in
4374      > Usage
4375      | Cufon.registerFont(Raphael.registerFont({…}));
4376     \*/
4377     R.registerFont = function (font) {
4378         if (!font.face) {
4379             return font;
4380         }
4381         this.fonts = this.fonts || {};
4382         var fontcopy = {
4383                 w: font.w,
4384                 face: {},
4385                 glyphs: {}
4386             },
4387             family = font.face["font-family"];
4388         for (var prop in font.face) if (font.face[has](prop)) {
4389             fontcopy.face[prop] = font.face[prop];
4390         }
4391         if (this.fonts[family]) {
4392             this.fonts[family].push(fontcopy);
4393         } else {
4394             this.fonts[family] = [fontcopy];
4395         }
4396         if (!font.svg) {
4397             fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
4398             for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
4399                 var path = font.glyphs[glyph];
4400                 fontcopy.glyphs[glyph] = {
4401                     w: path.w,
4402                     k: {},
4403                     d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
4404                             return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
4405                         }) + "z"
4406                 };
4407                 if (path.k) {
4408                     for (var k in path.k) if (path[has](k)) {
4409                         fontcopy.glyphs[glyph].k[k] = path.k[k];
4410                     }
4411                 }
4412             }
4413         }
4414         return font;
4415     };
4416     /*\
4417      * Paper.getFont
4418      [ method ]
4419      **
4420      * Finds font object in the registered fonts by given parameters. You could specify only one word from the font name, like “Myriad” for “Myriad Pro”.
4421      **
4422      > Parameters
4423      **
4424      - family (string) font family name or any word from it
4425      - weight (string) #optional font weight
4426      - style (string) #optional font style
4427      - stretch (string) #optional font stretch
4428      = (object) the font object
4429      > Usage
4430      | paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
4431     \*/
4432     paperproto.getFont = function (family, weight, style, stretch) {
4433         stretch = stretch || "normal";
4434         style = style || "normal";
4435         weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
4436         if (!R.fonts) {
4437             return;
4438         }
4439         var font = R.fonts[family];
4440         if (!font) {
4441             var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
4442             for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
4443                 if (name.test(fontName)) {
4444                     font = R.fonts[fontName];
4445                     break;
4446                 }
4447             }
4448         }
4449         var thefont;
4450         if (font) {
4451             for (var i = 0, ii = font.length; i < ii; i++) {
4452                 thefont = font[i];
4453                 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
4454                     break;
4455                 }
4456             }
4457         }
4458         return thefont;
4459     };
4460     /*\
4461      * Paper.print
4462      [ method ]
4463      **
4464      * Creates set of shapes to represent given font at given position with given size.
4465      * Result of the method is set object (see @Paper.set) which contains each letter as separate path object.
4466      **
4467      > Parameters
4468      **
4469      - x (number) x position of the text
4470      - y (number) y position of the text
4471      - text (string) text to print
4472      - font (object) font object, see @Paper.getFont
4473      - size (number) #optional size of the font, default is `16`
4474      - origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"`
4475      - letter_spacing (number) #optional number in range `-1..1`, default is `0`
4476      = (object) resulting set of letters
4477      > Usage
4478      | var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
4479      | // following line will paint first letter in red
4480      | txt[0].attr({fill: "#f00"});
4481     \*/
4482     paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
4483         origin = origin || "middle"; // baseline|middle
4484         letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
4485         var out = this.set(),
4486             letters = Str(string)[split](E),
4487             shift = 0,
4488             path = E,
4489             scale;
4490         R.is(font, string) && (font = this.getFont(font));
4491         if (font) {
4492             scale = (size || 16) / font.face["units-per-em"];
4493             var bb = font.face.bbox[split](separator),
4494                 top = +bb[0],
4495                 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
4496             for (var i = 0, ii = letters.length; i < ii; i++) {
4497                 var prev = i && font.glyphs[letters[i - 1]] || {},
4498                     curr = font.glyphs[letters[i]];
4499                 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
4500                 curr && curr.d && out.push(this.path(curr.d).attr({
4501                     fill: "#000",
4502                     stroke: "none",
4503                     transform: [["t", shift * scale, 0]]
4504                 }));
4505             }
4506             out.transform(["...s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
4507         }
4508         return out;
4509     };
4510
4511     /*\
4512      * Raphael.format
4513      [ method ]
4514      **
4515      * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
4516      **
4517      > Parameters
4518      **
4519      - token (string) string to format
4520      - … (string) rest of arguments will be treated as parameters for replacement
4521      = (string) formated string
4522      > Usage
4523      | var x = 10,
4524      |     y = 20,
4525      |     width = 40,
4526      |     height = 50;
4527      | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4528      | paper.path(Raphael.format("M{0},{1}h{2}v{3}h{4}z", x, y, width, height, -width));
4529     \*/
4530     R.format = function (token, params) {
4531         var args = R.is(params, array) ? [0][concat](params) : arguments;
4532         token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
4533             return args[++i] == null ? E : args[i];
4534         }));
4535         return token || E;
4536     };
4537     /*\
4538      * Raphael.fullfill
4539      [ method ]
4540      **
4541      * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
4542      **
4543      > Parameters
4544      **
4545      - token (string) string to format
4546      - json (object) object which properties will be used as a replacement
4547      = (string) formated string
4548      > Usage
4549      | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4550      | paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
4551      |     x: 10,
4552      |     y: 20,
4553      |     dim: {
4554      |         width: 40,
4555      |         height: 50,
4556      |         "negative width": -40
4557      |     }
4558      | }));
4559     \*/
4560     R.fullfill = (function () {
4561         var tokenRegex = /\{([^\}]+)\}/g,
4562             objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
4563             replacer = function (all, key, obj) {
4564                 var res = obj;
4565                 key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
4566                     name = name || quotedName;
4567                     if (res) {
4568                         if (name in res) {
4569                             res = res[name];
4570                         }
4571                         typeof res == "function" && isFunc && (res = res());
4572                     }
4573                 });
4574                 res = (res == null || res == obj ? all : res) + "";
4575                 return res;
4576             };
4577         return function (str, obj) {
4578             return String(str).replace(tokenRegex, function (all, key) {
4579                 return replacer(all, key, obj);
4580             });
4581         };
4582     })();
4583     /*\
4584      * Raphael.ninja
4585      [ method ]
4586      **
4587      * If you want to leave no trace of Raphaël (Well, Raphaël creates only one global variable `Raphael`, but anyway.) You can use `ninja` method.
4588      * Beware, that in this case plugins could stop working, because they are depending on global variable existance.
4589      **
4590      = (object) Raphael object
4591      > Usage
4592      | (function (local_raphael) {
4593      |     var paper = local_raphael(10, 10, 320, 200);
4594      |     …
4595      | })(Raphael.ninja());
4596     \*/
4597     R.ninja = function () {
4598         oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
4599         return R;
4600     };
4601     /*\
4602      * Raphael.st
4603      [ property (object) ]
4604      **
4605      * You can add your own method to elements and sets. It is wise to add a set method for each element method
4606      * you added, so you will be able to call the same method on sets too.
4607      **
4608      * See also @Raphael.el.
4609      > Usage
4610      | Raphael.el.red = function () {
4611      |     this.attr({fill: "#f00"});
4612      | };
4613      | Raphael.st.red = function () {
4614      |     this.forEach(function () {
4615      |         this.red();
4616      |     });
4617      | };
4618      | // then use it
4619      | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
4620     \*/
4621     R.st = setproto;
4622     // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
4623     (function (doc, loaded, f) {
4624         if (doc.readyState == null && doc.addEventListener){
4625             doc.addEventListener(loaded, f = function () {
4626                 doc.removeEventListener(loaded, f, false);
4627                 doc.readyState = "complete";
4628             }, false);
4629             doc.readyState = "loading";
4630         }
4631         function isLoaded() {
4632             (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
4633         }
4634         isLoaded();
4635     })(document, "DOMContentLoaded");
4636
4637     oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
4638     
4639     eve.on("DOMload", function () {
4640         loaded = true;
4641     });
4642 })();