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