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