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