Documentation fixes
[raphael] / raphael.core.js
1 // ┌─────────────────────────────────────────────────────────────────────┐ \\
2 // │ "Raphaël 2.0" - JavaScript Vector Library                           │ \\
3 // ├─────────────────────────────────────────────────────────────────────┤ \\
4 // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com)   │ \\
5 // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com)             │ \\
6 // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
7 // └─────────────────────────────────────────────────────────────────────┘ \\
8 (function () {
9     /*\
10      * Raphael
11      [ method ]
12      **
13      * Creates a canvas object on which to draw.
14      * You must do this first, as all future calls to drawing methods
15      * from this instance will be bound to this canvas.
16      > Parameters
17      **
18      - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
19      - width (number)
20      - height (number)
21      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
22      * or
23      - x (number)
24      - y (number)
25      - width (number)
26      - height (number)
27      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
28      * or
29      - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>})
30      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
31      * or
32      - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
33      = (object) @Paper
34      > Usage
35      | // Each of the following examples create a canvas
36      | // that is 320px wide by 200px high.
37      | // Canvas is created at the viewport’s 10,50 coordinate.
38      | var paper = Raphael(10, 50, 320, 200);
39      | // Canvas is created at the top left corner of the #notepad element
40      | // (or its top right corner in dir="rtl" elements)
41      | var paper = Raphael(document.getElementById("notepad"), 320, 200);
42      | // Same as above
43      | var paper = Raphael("notepad", 320, 200);
44      | // Image dump
45      | var set = Raphael(["notepad", 320, 200, {
46      |     type: "rect",
47      |     x: 10,
48      |     y: 10,
49      |     width: 25,
50      |     height: 25,
51      |     stroke: "#f00"
52      | }, {
53      |     type: "text",
54      |     x: 30,
55      |     y: 40,
56      |     text: "Dump"
57      | }]);
58     \*/
59     function R(first) {
60         if (R.is(first, "function")) {
61             return loaded ? first() : eve.on("DOMload", first);
62         } else if (R.is(first, array)) {
63             var a = first,
64                 cnv = R._engine.create[apply](R, a.splice(0, 3 + R.is(a[0], nu))),
65                 res = cnv.set(),
66                 i = 0,
67                 ii = a.length,
68                 j;
69             for (; i < ii; i++) {
70                 j = a[i] || {};
71                 elements[has](j.type) && res.push(cnv[j.type]().attr(j));
72             }
73             return res;
74         } else {
75             var args = Array.prototype.slice.call(arguments, 0);
76             if (R.is(args[args.length - 1], "function")) {
77                 var f = args.pop();
78                 return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("DOMload", function () {
79                     f.call(R._engine.create[apply](R, args));
80                 });
81             } else {
82                 return R._engine.create[apply](R, arguments);
83             }
84         }
85     }
86     R.version = "2.0.0";
87     R.eve = eve;
88     var loaded,
89         separator = /[, ]+/,
90         elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
91         formatrg = /\{(\d+)\}/g,
92         proto = "prototype",
93         has = "hasOwnProperty",
94         g = {
95             doc: document,
96             win: window
97         },
98         oldRaphael = {
99             was: Object.prototype[has].call(g.win, "Raphael"),
100             is: g.win.Raphael
101         },
102         Paper = function () {},
103         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 orientationchange touchcancel gesturestart gesturechange gestureend".split(S),
113         touchMap = {
114             mousedown: "touchstart",
115             mousemove: "touchmove",
116             mouseup: "touchend"
117         },
118         lowerCase = Str.prototype.toLowerCase,
119         math = Math,
120         mmax = math.max,
121         mmin = math.min,
122         abs = math.abs,
123         pow = math.pow,
124         PI = math.PI,
125         nu = "number",
126         string = "string",
127         array = "array",
128         toString = "toString",
129         fillString = "fill",
130         objectToString = Object.prototype.toString,
131         paper = {},
132         push = "push",
133         ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
134         colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
135         isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
136         bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
137         round = math.round,
138         setAttribute = "setAttribute",
139         toFloat = parseFloat,
140         toInt = parseInt,
141         ms = " progid:DXImageTransform.Microsoft",
142         upperCase = Str.prototype.toUpperCase,
143         availableAttrs = R._availableAttrs = {
144             "arrow-end": "none",
145             "arrow-start": "none",
146             blur: 0,
147             "clip-rect": "0 0 1e9 1e9",
148             cursor: "default",
149             cx: 0,
150             cy: 0,
151             fill: "#fff",
152             "fill-opacity": 1,
153             font: '10px "Arial"',
154             "font-family": '"Arial"',
155             "font-size": "10",
156             "font-style": "normal",
157             "font-weight": 400,
158             gradient: 0,
159             height: 0,
160             href: "http://raphaeljs.com/",
161             opacity: 1,
162             path: "M0,0",
163             r: 0,
164             rx: 0,
165             ry: 0,
166             src: "",
167             stroke: "#000",
168             "stroke-dasharray": "",
169             "stroke-linecap": "butt",
170             "stroke-linejoin": "butt",
171             "stroke-miterlimit": 0,
172             "stroke-opacity": 1,
173             "stroke-width": 1,
174             target: "_blank",
175             "text-anchor": "middle",
176             title: "Raphael",
177             transform: "",
178             width: 0,
179             x: 0,
180             y: 0
181         },
182         availableAnimAttrs = R._availableAnimAttrs = {
183             blur: nu,
184             "clip-rect": "csv",
185             cx: nu,
186             cy: nu,
187             fill: "colour",
188             "fill-opacity": nu,
189             "font-size": nu,
190             height: nu,
191             opacity: nu,
192             path: "path",
193             r: nu,
194             rx: nu,
195             ry: nu,
196             stroke: "colour",
197             "stroke-opacity": nu,
198             "stroke-width": nu,
199             transform: "transform",
200             width: nu,
201             x: nu,
202             y: nu
203         },
204         commaSpaces = /\s*,\s*/,
205         hsrg = {hs: 1, rg: 1},
206         p2s = /,?([achlmqrstvxz]),?/gi,
207         pathCommand = /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
208         tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
209         pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
210         radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
211         sortByKey = function (a, b) {
212             return a.key - b.key;
213         },
214         sortByNumber = function (a, b) {
215             return a - b;
216         },
217         fun = function () {},
218         pipe = function (x) {
219             return x;
220         },
221         rectPath = R._rectPath = function (x, y, w, h, r) {
222             if (r) {
223                 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"]];
224             }
225             return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
226         },
227         ellipsePath = function (x, y, rx, ry) {
228             if (ry == null) {
229                 ry = rx;
230             }
231             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"]];
232         },
233         getPath = R._getPath = {
234             path: function (el) {
235                 return el.attr("path");
236             },
237             circle: function (el) {
238                 var a = el.attrs;
239                 return ellipsePath(a.cx, a.cy, a.r);
240             },
241             ellipse: function (el) {
242                 var a = el.attrs;
243                 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
244             },
245             rect: function (el) {
246                 var a = el.attrs;
247                 return rectPath(a.x, a.y, a.width, a.height, a.r);
248             },
249             image: function (el) {
250                 var a = el.attrs;
251                 return rectPath(a.x, a.y, a.width, a.height);
252             },
253             text: function (el) {
254                 var bbox = el._getBBox();
255                 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
256             }
257         },
258         mapPath = function (path, matrix) {
259             if (!matrix) {
260                 return path;
261             }
262             var x, y, i, j, pathi;
263             path = path2curve(path);
264             for (i = 0, ii = path.length; i < ii; i++) {
265                 pathi = path[i];
266                 for (j = 1, jj = pathi.length; j < jj; j += 2) {
267                     x = matrix.x(pathi[j], pathi[j + 1]);
268                     y = matrix.y(pathi[j], pathi[j + 1]);
269                     pathi[j] = x;
270                     pathi[j + 1] = y;
271                 }
272             }
273             return path;
274         };
275
276     R._g = g;
277     /*\
278      * Raphael.type
279      [ property (string) ]
280      **
281      * Can be “SVG”, “VML” or empty, depending on browser support.
282     \*/
283     R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
284     if (R.type == "VML") {
285         var d = g.doc.createElement("div"),
286             b;
287         d.innerHTML = '<v:shape adj="1"/>';
288         b = d.firstChild;
289         b.style.behavior = "url(#default#VML)";
290         if (!(b && typeof b.adj == "object")) {
291             return (R.type = E);
292         }
293         d = null;
294     }
295     /*\
296      * Raphael.svg
297      [ property (boolean) ]
298      **
299      * `true` if browser supports SVG.
300     \*/
301     /*\
302      * Raphael.vml
303      [ property (boolean) ]
304      **
305      * `true` if browser supports VML.
306     \*/
307     R.svg = !(R.vml = R.type == "VML");
308     R._Paper = Paper;
309     /*\
310      * Raphael.fn
311      [ property (object) ]
312      **
313      * You can add your own method to the canvas. For example if you want to draw a pie chart,
314      * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
315      * you need to extend the `Raphael.fn` object. Please note that you can create your own namespaces
316      * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
317      * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
318      > Usage
319      | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
320      |     return this.path( ... );
321      | };
322      | // or create namespace
323      | Raphael.fn.mystuff = {
324      |     arrow: function () {…},
325      |     star: function () {…},
326      |     // etc…
327      | };
328      | var paper = Raphael(10, 10, 630, 480);
329      | // then use it
330      | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
331      | paper.mystuff.arrow();
332      | paper.mystuff.star();
333     \*/
334     R.fn = paperproto = Paper.prototype = R.prototype;
335     /*\
336      * Paper.customAttributes
337      [ property (object) ]
338      **
339      * If you have a set of attributes that you would like to represent
340      * as a function of some number you can do it easily with custom attributes:
341      > Usage
342      | paper.customAttributes.hue = function (num) {
343      |     num = num % 1;
344      |     return {fill: "hsb(" + num + ", .75, 1)"};
345      | };
346      | // Custom attribute “hue” will change fill
347      | // to be given hue with fixed saturation and brightness.
348      | // Now you can use it like this:
349      | var c = paper.circle(10, 10, 10).attr({hue: .45});
350      | // or even like this:
351      | c.animate({hue: 1}, 1e3);
352      | 
353      | // You could also create custom attribute
354      | // with multiple parameters:
355      | paper.customAttributes.hsb = function (h, s, b) {
356      |     return {fill: "hsb(" + [h, s, b].join(",") + ")"};
357      | };
358      | c.attr({hsb: ".5 .8 1"});
359      | c.animate({hsb: "1 0 .5"}, 1e3);
360     \*/
361     paperproto.customAttributes = {};
362     R._id = 0;
363     R._oid = 0;
364     /*\
365      * Raphael.is
366      [ method ]
367      **
368      * Handfull replacement for `typeof` operator.
369      > Parameters
370      - o (…) any object or primitive
371      - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
372      = (boolean) is given value is of given type
373     \*/
374     R.is = function (o, type) {
375         type = lowerCase.call(type);
376         if (type == "finite") {
377             return !isnan[has](+o);
378         }
379         if (type == "array") {
380             return o instanceof Array;
381         }
382         return  (type == "null" && o === null) ||
383                 (type == typeof o) ||
384                 (type == "object" && o === Object(o)) ||
385                 (type == "array" && Array.isArray && Array.isArray(o)) ||
386                 objectToString.call(o).slice(8, -1).toLowerCase() == type;
387     };
388     /*\
389      * Raphael.angle
390      [ method ]
391      **
392      * Returns angle between two or three points
393      > Parameters
394      - x1 (number) x coord of first point
395      - y1 (number) y coord of first point
396      - x2 (number) x coord of second point
397      - y2 (number) y coord of second point
398      - x3 (number) #optional x coord of third point
399      - y3 (number) #optional y coord of third point
400      = (number) angle in degrees.
401     \*/
402     R.angle = function (x1, y1, x2, y2, x3, y3) {
403         if (x3 == null) {
404             var x = x1 - x2,
405                 y = y1 - y2;
406             if (!x && !y) {
407                 return 0;
408             }
409             return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
410         } else {
411             return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
412         }
413     };
414     /*\
415      * Raphael.rad
416      [ method ]
417      **
418      * Transform angle to radians
419      > Parameters
420      - deg (number) angle in degrees
421      = (number) angle in radians.
422     \*/
423     R.rad = function (deg) {
424         return deg % 360 * PI / 180;
425     };
426     /*\
427      * Raphael.deg
428      [ method ]
429      **
430      * Transform angle to degrees
431      > Parameters
432      - deg (number) angle in radians
433      = (number) angle in degrees.
434     \*/
435     R.deg = function (rad) {
436         return rad * 180 / PI % 360;
437     };
438     /*\
439      * Raphael.snapTo
440      [ method ]
441      **
442      * Snaps given value to given grid.
443      > Parameters
444      - values (array|number) given array of values or step of the grid
445      - value (number) value to adjust
446      - tolerance (number) #optional tolerance for snapping. Default is `10`.
447      = (number) adjusted value.
448     \*/
449     R.snapTo = function (values, value, tolerance) {
450         tolerance = R.is(tolerance, "finite") ? tolerance : 10;
451         if (R.is(values, array)) {
452             var i = values.length;
453             while (i--) if (abs(values[i] - value) <= tolerance) {
454                 return values[i];
455             }
456         } else {
457             values = +values;
458             var rem = value % values;
459             if (rem < tolerance) {
460                 return value - rem;
461             }
462             if (rem > values - tolerance) {
463                 return value - rem + values;
464             }
465         }
466         return value;
467     };
468     
469     var createUUID = R._createUUID = (function (uuidRegEx, uuidReplacer) {
470         return function () {
471             return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
472         };
473     })(/[xy]/g, function (c) {
474         var r = math.random() * 16 | 0,
475             v = c == "x" ? r : (r & 3 | 8);
476         return v.toString(16);
477     });
478
479     /*\
480      * Raphael.setWindow
481      [ method ]
482      **
483      * Used when you need to draw in `&lt;iframe>`. Switched window to the iframe one.
484      > Parameters
485      - newwin (window) new window object
486     \*/
487     R.setWindow = function (newwin) {
488         eve("setWindow", R, g.win, newwin);
489         g.win = newwin;
490         g.doc = g.win.document;
491         if (initWin) {
492             initWin(g.win);
493         }
494     };
495     // colour utilities
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, 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             x = pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1112             y = pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y,
1113             mx = p1x + 2 * t * (c1x - p1x) + t * t * (c2x - 2 * c1x + p1x),
1114             my = p1y + 2 * t * (c1y - p1y) + t * t * (c2y - 2 * c1y + p1y),
1115             nx = c1x + 2 * t * (c2x - c1x) + t * t * (p2x - 2 * c2x + c1x),
1116             ny = c1y + 2 * t * (c2y - c1y) + t * t * (p2y - 2 * c2y + c1y),
1117             ax = (1 - t) * p1x + t * c1x,
1118             ay = (1 - t) * p1y + t * c1y,
1119             cx = (1 - t) * c2x + t * p2x,
1120             cy = (1 - t) * c2y + t * p2y,
1121             alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1122         (mx > nx || my < ny) && (alpha += 180);
1123         return {
1124             x: x,
1125             y: y,
1126             m: {x: mx, y: my},
1127             n: {x: nx, y: ny},
1128             start: {x: ax, y: ay},
1129             end: {x: cx, y: cy},
1130             alpha: alpha
1131         };
1132     };
1133     var pathDimensions = cacher(function (path) {
1134         if (!path) {
1135             return {x: 0, y: 0, width: 0, height: 0};
1136         }
1137         path = path2curve(path);
1138         var x = 0, 
1139             y = 0,
1140             X = [],
1141             Y = [],
1142             p;
1143         for (var i = 0, ii = path.length; i < ii; i++) {
1144             p = path[i];
1145             if (p[0] == "M") {
1146                 x = p[1];
1147                 y = p[2];
1148                 X.push(x);
1149                 Y.push(y);
1150             } else {
1151                 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1152                 X = X[concat](dim.min.x, dim.max.x);
1153                 Y = Y[concat](dim.min.y, dim.max.y);
1154                 x = p[5];
1155                 y = p[6];
1156             }
1157         }
1158         var xmin = mmin[apply](0, X),
1159             ymin = mmin[apply](0, Y);
1160         return {
1161             x: xmin,
1162             y: ymin,
1163             width: mmax[apply](0, X) - xmin,
1164             height: mmax[apply](0, Y) - ymin
1165         };
1166     }, null, function (o) {
1167         return {
1168             x: o.x,
1169             y: o.y,
1170             width: o.width,
1171             height: o.height
1172         };
1173     }),
1174         pathClone = function (pathArray) {
1175             var res = [];
1176             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1177                 pathArray = R.parsePathString(pathArray);
1178             }
1179             for (var i = 0, ii = pathArray.length; i < ii; i++) {
1180                 res[i] = [];
1181                 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1182                     res[i][j] = pathArray[i][j];
1183                 }
1184             }
1185             res.toString = R._path2string;
1186             return res;
1187         },
1188         pathToRelative = R._pathToRelative = cacher(function (pathArray) {
1189             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1190                 pathArray = R.parsePathString(pathArray);
1191             }
1192             var res = [],
1193                 x = 0,
1194                 y = 0,
1195                 mx = 0,
1196                 my = 0,
1197                 start = 0;
1198             if (pathArray[0][0] == "M") {
1199                 x = pathArray[0][1];
1200                 y = pathArray[0][2];
1201                 mx = x;
1202                 my = y;
1203                 start++;
1204                 res.push(["M", x, y]);
1205             }
1206             for (var i = start, ii = pathArray.length; i < ii; i++) {
1207                 var r = res[i] = [],
1208                     pa = pathArray[i];
1209                 if (pa[0] != lowerCase.call(pa[0])) {
1210                     r[0] = lowerCase.call(pa[0]);
1211                     switch (r[0]) {
1212                         case "a":
1213                             r[1] = pa[1];
1214                             r[2] = pa[2];
1215                             r[3] = pa[3];
1216                             r[4] = pa[4];
1217                             r[5] = pa[5];
1218                             r[6] = +(pa[6] - x).toFixed(3);
1219                             r[7] = +(pa[7] - y).toFixed(3);
1220                             break;
1221                         case "v":
1222                             r[1] = +(pa[1] - y).toFixed(3);
1223                             break;
1224                         case "m":
1225                             mx = pa[1];
1226                             my = pa[2];
1227                         default:
1228                             for (var j = 1, jj = pa.length; j < jj; j++) {
1229                                 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1230                             }
1231                     }
1232                 } else {
1233                     r = res[i] = [];
1234                     if (pa[0] == "m") {
1235                         mx = pa[1] + x;
1236                         my = pa[2] + y;
1237                     }
1238                     for (var k = 0, kk = pa.length; k < kk; k++) {
1239                         res[i][k] = pa[k];
1240                     }
1241                 }
1242                 var len = res[i].length;
1243                 switch (res[i][0]) {
1244                     case "z":
1245                         x = mx;
1246                         y = my;
1247                         break;
1248                     case "h":
1249                         x += +res[i][len - 1];
1250                         break;
1251                     case "v":
1252                         y += +res[i][len - 1];
1253                         break;
1254                     default:
1255                         x += +res[i][len - 2];
1256                         y += +res[i][len - 1];
1257                 }
1258             }
1259             res.toString = R._path2string;
1260             return res;
1261         }, 0, pathClone),
1262         pathToAbsolute = R._pathToAbsolute = cacher(function (pathArray) {
1263             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1264                 pathArray = R.parsePathString(pathArray);
1265             }
1266             if (!pathArray || !pathArray.length) {
1267                 return [["M", 0, 0]];
1268             }
1269             var res = [],
1270                 x = 0,
1271                 y = 0,
1272                 mx = 0,
1273                 my = 0,
1274                 start = 0;
1275             if (pathArray[0][0] == "M") {
1276                 x = +pathArray[0][1];
1277                 y = +pathArray[0][2];
1278                 mx = x;
1279                 my = y;
1280                 start++;
1281                 res[0] = ["M", x, y];
1282             }
1283             for (var i = start, ii = pathArray.length; i < ii; i++) {
1284                 var r = res[i] = [],
1285                     pa = pathArray[i];
1286                 if (pa[0] != upperCase.call(pa[0])) {
1287                     r[0] = upperCase.call(pa[0]);
1288                     switch (r[0]) {
1289                         case "A":
1290                             r[1] = pa[1];
1291                             r[2] = pa[2];
1292                             r[3] = pa[3];
1293                             r[4] = pa[4];
1294                             r[5] = pa[5];
1295                             r[6] = +(pa[6] + x);
1296                             r[7] = +(pa[7] + y);
1297                             break;
1298                         case "V":
1299                             r[1] = +pa[1] + y;
1300                             break;
1301                         case "H":
1302                             r[1] = +pa[1] + x;
1303                             break;
1304                         case "M":
1305                             mx = +pa[1] + x;
1306                             my = +pa[2] + y;
1307                         default:
1308                             for (var j = 1, jj = pa.length; j < jj; j++) {
1309                                 r[j] = +pa[j] + ((j % 2) ? x : y);
1310                             }
1311                     }
1312                 } else {
1313                     for (var k = 0, kk = pa.length; k < kk; k++) {
1314                         res[i][k] = pa[k];
1315                     }
1316                 }
1317                 switch (r[0]) {
1318                     case "Z":
1319                         x = mx;
1320                         y = my;
1321                         break;
1322                     case "H":
1323                         x = r[1];
1324                         break;
1325                     case "V":
1326                         y = r[1];
1327                         break;
1328                     case "M":
1329                         mx = res[i][res[i].length - 2];
1330                         my = res[i][res[i].length - 1];
1331                     default:
1332                         x = res[i][res[i].length - 2];
1333                         y = res[i][res[i].length - 1];
1334                 }
1335             }
1336             res.toString = R._path2string;
1337             return res;
1338         }, null, pathClone),
1339         l2c = function (x1, y1, x2, y2) {
1340             return [x1, y1, x2, y2, x2, y2];
1341         },
1342         q2c = function (x1, y1, ax, ay, x2, y2) {
1343             var _13 = 1 / 3,
1344                 _23 = 2 / 3;
1345             return [
1346                     _13 * x1 + _23 * ax,
1347                     _13 * y1 + _23 * ay,
1348                     _13 * x2 + _23 * ax,
1349                     _13 * y2 + _23 * ay,
1350                     x2,
1351                     y2
1352                 ];
1353         },
1354         a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1355             // for more information of where this math came from visit:
1356             // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1357             var _120 = PI * 120 / 180,
1358                 rad = PI / 180 * (+angle || 0),
1359                 res = [],
1360                 xy,
1361                 rotate = cacher(function (x, y, rad) {
1362                     var X = x * math.cos(rad) - y * math.sin(rad),
1363                         Y = x * math.sin(rad) + y * math.cos(rad);
1364                     return {x: X, y: Y};
1365                 });
1366             if (!recursive) {
1367                 xy = rotate(x1, y1, -rad);
1368                 x1 = xy.x;
1369                 y1 = xy.y;
1370                 xy = rotate(x2, y2, -rad);
1371                 x2 = xy.x;
1372                 y2 = xy.y;
1373                 var cos = math.cos(PI / 180 * angle),
1374                     sin = math.sin(PI / 180 * angle),
1375                     x = (x1 - x2) / 2,
1376                     y = (y1 - y2) / 2;
1377                 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1378                 if (h > 1) {
1379                     h = math.sqrt(h);
1380                     rx = h * rx;
1381                     ry = h * ry;
1382                 }
1383                 var rx2 = rx * rx,
1384                     ry2 = ry * ry,
1385                     k = (large_arc_flag == sweep_flag ? -1 : 1) *
1386                         math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1387                     cx = k * rx * y / ry + (x1 + x2) / 2,
1388                     cy = k * -ry * x / rx + (y1 + y2) / 2,
1389                     f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1390                     f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1391
1392                 f1 = x1 < cx ? PI - f1 : f1;
1393                 f2 = x2 < cx ? PI - f2 : f2;
1394                 f1 < 0 && (f1 = PI * 2 + f1);
1395                 f2 < 0 && (f2 = PI * 2 + f2);
1396                 if (sweep_flag && f1 > f2) {
1397                     f1 = f1 - PI * 2;
1398                 }
1399                 if (!sweep_flag && f2 > f1) {
1400                     f2 = f2 - PI * 2;
1401                 }
1402             } else {
1403                 f1 = recursive[0];
1404                 f2 = recursive[1];
1405                 cx = recursive[2];
1406                 cy = recursive[3];
1407             }
1408             var df = f2 - f1;
1409             if (abs(df) > _120) {
1410                 var f2old = f2,
1411                     x2old = x2,
1412                     y2old = y2;
1413                 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1414                 x2 = cx + rx * math.cos(f2);
1415                 y2 = cy + ry * math.sin(f2);
1416                 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1417             }
1418             df = f2 - f1;
1419             var c1 = math.cos(f1),
1420                 s1 = math.sin(f1),
1421                 c2 = math.cos(f2),
1422                 s2 = math.sin(f2),
1423                 t = math.tan(df / 4),
1424                 hx = 4 / 3 * rx * t,
1425                 hy = 4 / 3 * ry * t,
1426                 m1 = [x1, y1],
1427                 m2 = [x1 + hx * s1, y1 - hy * c1],
1428                 m3 = [x2 + hx * s2, y2 - hy * c2],
1429                 m4 = [x2, y2];
1430             m2[0] = 2 * m1[0] - m2[0];
1431             m2[1] = 2 * m1[1] - m2[1];
1432             if (recursive) {
1433                 return [m2, m3, m4][concat](res);
1434             } else {
1435                 res = [m2, m3, m4][concat](res).join().split(",");
1436                 var newres = [];
1437                 for (var i = 0, ii = res.length; i < ii; i++) {
1438                     newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1439                 }
1440                 return newres;
1441             }
1442         },
1443         findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1444             var t1 = 1 - t;
1445             return {
1446                 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1447                 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1448             };
1449         },
1450         curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1451             var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1452                 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1453                 c = p1x - c1x,
1454                 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1455                 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1456                 y = [p1y, p2y],
1457                 x = [p1x, p2x],
1458                 dot;
1459             abs(t1) > "1e12" && (t1 = .5);
1460             abs(t2) > "1e12" && (t2 = .5);
1461             if (t1 > 0 && t1 < 1) {
1462                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1463                 x.push(dot.x);
1464                 y.push(dot.y);
1465             }
1466             if (t2 > 0 && t2 < 1) {
1467                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1468                 x.push(dot.x);
1469                 y.push(dot.y);
1470             }
1471             a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1472             b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1473             c = p1y - c1y;
1474             t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1475             t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1476             abs(t1) > "1e12" && (t1 = .5);
1477             abs(t2) > "1e12" && (t2 = .5);
1478             if (t1 > 0 && t1 < 1) {
1479                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1480                 x.push(dot.x);
1481                 y.push(dot.y);
1482             }
1483             if (t2 > 0 && t2 < 1) {
1484                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1485                 x.push(dot.x);
1486                 y.push(dot.y);
1487             }
1488             return {
1489                 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1490                 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1491             };
1492         }),
1493         path2curve = cacher(function (path, path2) {
1494             var p = pathToAbsolute(path),
1495                 p2 = path2 && pathToAbsolute(path2),
1496                 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1497                 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1498                 processPath = function (path, d) {
1499                     var nx, ny;
1500                     if (!path) {
1501                         return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1502                     }
1503                     !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1504                     switch (path[0]) {
1505                         case "M":
1506                             d.X = path[1];
1507                             d.Y = path[2];
1508                             break;
1509                         case "A":
1510                             path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1511                             break;
1512                         case "S":
1513                             nx = d.x + (d.x - (d.bx || d.x));
1514                             ny = d.y + (d.y - (d.by || d.y));
1515                             path = ["C", nx, ny][concat](path.slice(1));
1516                             break;
1517                         case "T":
1518                             d.qx = d.x + (d.x - (d.qx || d.x));
1519                             d.qy = d.y + (d.y - (d.qy || d.y));
1520                             path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1521                             break;
1522                         case "Q":
1523                             d.qx = path[1];
1524                             d.qy = path[2];
1525                             path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1526                             break;
1527                         case "L":
1528                             path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1529                             break;
1530                         case "H":
1531                             path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1532                             break;
1533                         case "V":
1534                             path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1535                             break;
1536                         case "Z":
1537                             path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1538                             break;
1539                     }
1540                     return path;
1541                 },
1542                 fixArc = function (pp, i) {
1543                     if (pp[i].length > 7) {
1544                         pp[i].shift();
1545                         var pi = pp[i];
1546                         while (pi.length) {
1547                             pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1548                         }
1549                         pp.splice(i, 1);
1550                         ii = mmax(p.length, p2 && p2.length || 0);
1551                     }
1552                 },
1553                 fixM = function (path1, path2, a1, a2, i) {
1554                     if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1555                         path2.splice(i, 0, ["M", a2.x, a2.y]);
1556                         a1.bx = 0;
1557                         a1.by = 0;
1558                         a1.x = path1[i][1];
1559                         a1.y = path1[i][2];
1560                         ii = mmax(p.length, p2 && p2.length || 0);
1561                     }
1562                 };
1563             for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1564                 p[i] = processPath(p[i], attrs);
1565                 fixArc(p, i);
1566                 p2 && (p2[i] = processPath(p2[i], attrs2));
1567                 p2 && fixArc(p2, i);
1568                 fixM(p, p2, attrs, attrs2, i);
1569                 fixM(p2, p, attrs2, attrs, i);
1570                 var seg = p[i],
1571                     seg2 = p2 && p2[i],
1572                     seglen = seg.length,
1573                     seg2len = p2 && seg2.length;
1574                 attrs.x = seg[seglen - 2];
1575                 attrs.y = seg[seglen - 1];
1576                 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1577                 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1578                 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1579                 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1580                 attrs2.x = p2 && seg2[seg2len - 2];
1581                 attrs2.y = p2 && seg2[seg2len - 1];
1582             }
1583             return p2 ? [p, p2] : p;
1584         }, null, pathClone),
1585         parseDots = R._parseDots = cacher(function (gradient) {
1586             var dots = [];
1587             for (var i = 0, ii = gradient.length; i < ii; i++) {
1588                 var dot = {},
1589                     par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1590                 dot.color = R.getRGB(par[1]);
1591                 if (dot.color.error) {
1592                     return null;
1593                 }
1594                 dot.color = dot.color.hex;
1595                 par[2] && (dot.offset = par[2] + "%");
1596                 dots.push(dot);
1597             }
1598             for (i = 1, ii = dots.length - 1; i < ii; i++) {
1599                 if (!dots[i].offset) {
1600                     var start = toFloat(dots[i - 1].offset || 0),
1601                         end = 0;
1602                     for (var j = i + 1; j < ii; j++) {
1603                         if (dots[j].offset) {
1604                             end = dots[j].offset;
1605                             break;
1606                         }
1607                     }
1608                     if (!end) {
1609                         end = 100;
1610                         j = ii;
1611                     }
1612                     end = toFloat(end);
1613                     var d = (end - start) / (j - i + 1);
1614                     for (; i < j; i++) {
1615                         start += d;
1616                         dots[i].offset = start + "%";
1617                     }
1618                 }
1619             }
1620             return dots;
1621         }),
1622         tear = R._tear = function (el, paper) {
1623             el == paper.top && (paper.top = el.prev);
1624             el == paper.bottom && (paper.bottom = el.next);
1625             el.next && (el.next.prev = el.prev);
1626             el.prev && (el.prev.next = el.next);
1627         },
1628         tofront = R._tofront = function (el, paper) {
1629             if (paper.top === el) {
1630                 return;
1631             }
1632             tear(el, paper);
1633             el.next = null;
1634             el.prev = paper.top;
1635             paper.top.next = el;
1636             paper.top = el;
1637         },
1638         toback = R._toback = function (el, paper) {
1639             if (paper.bottom === el) {
1640                 return;
1641             }
1642             tear(el, paper);
1643             el.next = paper.bottom;
1644             el.prev = null;
1645             paper.bottom.prev = el;
1646             paper.bottom = el;
1647         },
1648         insertafter = R._insertafter = function (el, el2, paper) {
1649             tear(el, paper);
1650             el2 == paper.top && (paper.top = el);
1651             el2.next && (el2.next.prev = el);
1652             el.next = el2.next;
1653             el.prev = el2;
1654             el2.next = el;
1655         },
1656         insertbefore = R._insertbefore = function (el, el2, paper) {
1657             tear(el, paper);
1658             el2 == paper.bottom && (paper.bottom = el);
1659             el2.prev && (el2.prev.next = el);
1660             el.prev = el2.prev;
1661             el2.prev = el;
1662             el.next = el2;
1663         },
1664         removed = function (methodname) {
1665             return function () {
1666                 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1667             };
1668         },
1669         extractTransform = R._extractTransform = function (el, tstr) {
1670             if (tstr == null) {
1671                 return el._.transform;
1672             }
1673             tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1674             var tdata = R.parseTransformString(tstr),
1675                 deg = 0,
1676                 dx = 0,
1677                 dy = 0,
1678                 sx = 1,
1679                 sy = 1,
1680                 _ = el._,
1681                 m = new Matrix;
1682             _.transform = tdata || [];
1683             if (tdata) {
1684                 for (var i = 0, ii = tdata.length; i < ii; i++) {
1685                     var t = tdata[i],
1686                         tlen = t.length,
1687                         bb;
1688                     t[0] = Str(t[0]).toLowerCase();
1689                     if (t[0] == "t" && tlen == 3) {
1690                         m.translate(t[1], t[2]);
1691                     } else if (t[0] == "r") {
1692                         if (tlen == 2) {
1693                             bb = bb || el.getBBox(1);
1694                             m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1695                             deg += t[1];
1696                         } else if (tlen == 4) {
1697                             m.rotate(t[1], t[2], t[3]);
1698                             deg += t[1];
1699                         }
1700                     } else if (t[0] == "s") {
1701                         if (tlen == 2 || tlen == 3) {
1702                             bb = bb || el.getBBox(1);
1703                             m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1704                             sx *= t[1];
1705                             sy *= t[tlen - 1];
1706                         } else if (tlen == 5) {
1707                             m.scale(t[1], t[2], t[3], t[4]);
1708                             sx *= t[1];
1709                             sy *= t[2];
1710                         }
1711                     } else if (t[0] == "m" && tlen == 7) {
1712                         m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1713                     }
1714                     _.dirtyT = 1;
1715                     el.matrix = m;
1716                 }
1717             }
1718
1719             el.matrix = m;
1720
1721             _.sx = sx;
1722             _.sy = sy;
1723             _.deg = deg;
1724             _.dx = dx = m.e;
1725             _.dy = dy = m.f;
1726
1727             if (sx == 1 && sy == 1 && !deg && _.bbox) {
1728                 _.bbox.x += +dx;
1729                 _.bbox.y += +dy;
1730             } else {
1731                 _.dirtyT = 1;
1732             }
1733         },
1734         getEmpty = function (item) {
1735             switch (item[0]) {
1736                 case "t": return ["t", 0, 0];
1737                 case "m": return ["m", 1, 0, 0, 1, 0, 0];
1738                 case "r": if (item.length == 4) {
1739                     return ["r", 0, item[2], item[3]];
1740                 } else {
1741                     return ["r", 0];
1742                 }
1743                 case "s": if (item.length == 5) {
1744                     return ["s", 1, 1, item[3], item[4]];
1745                 } else if (item.length == 3) {
1746                     return ["s", 1, 1];
1747                 } else {
1748                     return ["s", 1];
1749                 }
1750             }
1751         },
1752         equaliseTransform = R._equaliseTransform = function (t1, t2) {
1753             t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1754             t1 = R.parseTransformString(t1) || [];
1755             t2 = R.parseTransformString(t2) || [];
1756             var maxlength = mmax(t1.length, t2.length),
1757                 from = [],
1758                 to = [],
1759                 i = 0, j, jj,
1760                 tt1, tt2;
1761             for (; i < maxlength; i++) {
1762                 tt1 = t1[i] || getEmpty(t2[i]);
1763                 tt2 = t2[i] || getEmpty(tt1);
1764                 if ((tt1[0] != tt2[0]) ||
1765                     (tt1[0] == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1766                     (tt1[0] == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1767                     ) {
1768                     return;
1769                 }
1770                 from[i] = [];
1771                 to[i] = [];
1772                 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1773                     j in tt1 && (from[i][j] = tt1[j]);
1774                     j in tt2 && (to[i][j] = tt2[j]);
1775                 }
1776             }
1777             return {
1778                 from: from,
1779                 to: to
1780             };
1781         };
1782     R._getContainer = function (x, y, w, h) {
1783         var container;
1784         container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1785         if (container == null) {
1786             return;
1787         }
1788         if (container.tagName) {
1789             if (y == null) {
1790                 return {
1791                     container: container,
1792                     width: container.style.pixelWidth || container.offsetWidth,
1793                     height: container.style.pixelHeight || container.offsetHeight
1794                 };
1795             } else {
1796                 return {
1797                     container: container,
1798                     width: y,
1799                     height: w
1800                 };
1801             }
1802         }
1803         return {
1804             container: 1,
1805             x: x,
1806             y: y,
1807             width: w,
1808             height: h
1809         };
1810     };
1811     /*\
1812      * Raphael.pathToRelative
1813      [ method ]
1814      **
1815      * Utility method
1816      **
1817      * Converts path to relative form
1818      > Parameters
1819      - pathString (string|array) path string or array of segments
1820      = (array) array of segments.
1821     \*/
1822     R.pathToRelative = pathToRelative;
1823     R._engine = {};
1824     /*\
1825      * Raphael.path2curve
1826      [ method ]
1827      **
1828      * Utility method
1829      **
1830      * Converts path to a new path where all segments are cubic bezier curves.
1831      > Parameters
1832      - pathString (string|array) path string or array of segments
1833      = (array) array of segments.
1834     \*/
1835     R.path2curve = path2curve;
1836     /*\
1837      * Raphael.matrix
1838      [ method ]
1839      **
1840      * Utility method
1841      **
1842      * Returns matrix based on given parameters.
1843      > Parameters
1844      - a (number)
1845      - b (number)
1846      - c (number)
1847      - d (number)
1848      - e (number)
1849      - f (number)
1850      = (object) @Matrix
1851     \*/
1852     R.matrix = function (a, b, c, d, e, f) {
1853         return new Matrix(a, b, c, d, e, f);
1854     };
1855     function Matrix(a, b, c, d, e, f) {
1856         if (a != null) {
1857             this.a = +a;
1858             this.b = +b;
1859             this.c = +c;
1860             this.d = +d;
1861             this.e = +e;
1862             this.f = +f;
1863         } else {
1864             this.a = 1;
1865             this.b = 0;
1866             this.c = 0;
1867             this.d = 1;
1868             this.e = 0;
1869             this.f = 0;
1870         }
1871     }
1872     (function (matrixproto) {
1873         /*\
1874          * Matrix.add
1875          [ method ]
1876          **
1877          * Adds given matrix to existing one.
1878          > Parameters
1879          - a (number)
1880          - b (number)
1881          - c (number)
1882          - d (number)
1883          - e (number)
1884          - f (number)
1885          or
1886          - matrix (object) @Matrix
1887         \*/
1888         matrixproto.add = function (a, b, c, d, e, f) {
1889             var out = [[], [], []],
1890                 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1891                 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1892                 x, y, z, res;
1893
1894             if (a && a instanceof Matrix) {
1895                 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1896             }
1897
1898             for (x = 0; x < 3; x++) {
1899                 for (y = 0; y < 3; y++) {
1900                     res = 0;
1901                     for (z = 0; z < 3; z++) {
1902                         res += m[x][z] * matrix[z][y];
1903                     }
1904                     out[x][y] = res;
1905                 }
1906             }
1907             this.a = out[0][0];
1908             this.b = out[1][0];
1909             this.c = out[0][1];
1910             this.d = out[1][1];
1911             this.e = out[0][2];
1912             this.f = out[1][2];
1913         };
1914         /*\
1915          * Matrix.invert
1916          [ method ]
1917          **
1918          * Returns inverted version of the matrix
1919          = (object) @Matrix
1920         \*/
1921         matrixproto.invert = function () {
1922             var me = this,
1923                 x = me.a * me.d - me.b * me.c;
1924             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);
1925         };
1926         /*\
1927          * Matrix.clone
1928          [ method ]
1929          **
1930          * Returns copy of the matrix
1931          = (object) @Matrix
1932         \*/
1933         matrixproto.clone = function () {
1934             return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
1935         };
1936         /*\
1937          * Matrix.translate
1938          [ method ]
1939          **
1940          * Translate the matrix
1941          > Parameters
1942          - x (number)
1943          - y (number)
1944         \*/
1945         matrixproto.translate = function (x, y) {
1946             this.add(1, 0, 0, 1, x, y);
1947         };
1948         /*\
1949          * Matrix.scale
1950          [ method ]
1951          **
1952          * Scales the matrix
1953          > Parameters
1954          - x (number)
1955          - y (number) #optional
1956          - cx (number) #optional
1957          - cy (number) #optional
1958         \*/
1959         matrixproto.scale = function (x, y, cx, cy) {
1960             y == null && (y = x);
1961             cx || cy && this.add(1, 0, 0, 1, cx, cy);
1962             this.add(x, 0, 0, y, 0, 0);
1963             cx || cy && this.add(1, 0, 0, 1, -cx, -cy);
1964         };
1965         /*\
1966          * Matrix.rotate
1967          [ method ]
1968          **
1969          * Rotates the matrix
1970          > Parameters
1971          - a (number)
1972          - x (number)
1973          - y (number)
1974         \*/
1975         matrixproto.rotate = function (a, x, y) {
1976             a = R.rad(a);
1977             x = x || 0;
1978             y = y || 0;
1979             var cos = +math.cos(a).toFixed(9),
1980                 sin = +math.sin(a).toFixed(9);
1981             this.add(cos, sin, -sin, cos, x, y);
1982             this.add(1, 0, 0, 1, -x, -y);
1983         };
1984         /*\
1985          * Matrix.x
1986          [ method ]
1987          **
1988          * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y
1989          > Parameters
1990          - x (number)
1991          - y (number)
1992          = (number) x
1993         \*/
1994         matrixproto.x = function (x, y) {
1995             return x * this.a + y * this.c + this.e;
1996         };
1997         /*\
1998          * Matrix.y
1999          [ method ]
2000          **
2001          * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x
2002          > Parameters
2003          - x (number)
2004          - y (number)
2005          = (number) y
2006         \*/
2007         matrixproto.y = function (x, y) {
2008             return x * this.b + y * this.d + this.f;
2009         };
2010         matrixproto.get = function (i) {
2011             return +this[Str.fromCharCode(97 + i)].toFixed(4);
2012         };
2013         matrixproto.toString = function () {
2014             return R.svg ?
2015                 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
2016                 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
2017         };
2018         matrixproto.toFilter = function () {
2019             return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
2020                 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
2021                 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
2022         };
2023         matrixproto.offset = function () {
2024             return [this.e.toFixed(4), this.f.toFixed(4)];
2025         };
2026         function norm(a) {
2027             return a[0] * a[0] + a[1] * a[1];
2028         }
2029         function normalize(a) {
2030             var mag = math.sqrt(norm(a));
2031             a[0] && (a[0] /= mag);
2032             a[1] && (a[1] /= mag);
2033         }
2034         /*\
2035          * Matrix.split
2036          [ method ]
2037          **
2038          * Splits matrix into primitive transformations
2039          = (object) in format:
2040          o dx (number) translation by x
2041          o dy (number) translation by y
2042          o scalex (number) scale by x
2043          o scaley (number) scale by y
2044          o shear (number) shear
2045          o rotate (number) rotation in deg
2046          o isSimple (boolean) could it be represented via simple transformations
2047         \*/
2048         matrixproto.split = function () {
2049             var out = {};
2050             // translation
2051             out.dx = this.e;
2052             out.dy = this.f;
2053
2054             // scale and shear
2055             var row = [[this.a, this.c], [this.b, this.d]];
2056             out.scalex = math.sqrt(norm(row[0]));
2057             normalize(row[0]);
2058
2059             out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
2060             row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
2061
2062             out.scaley = math.sqrt(norm(row[1]));
2063             normalize(row[1]);
2064             out.shear /= out.scaley;
2065
2066             // rotation
2067             var sin = -row[0][1],
2068                 cos = row[1][1];
2069             if (cos < 0) {
2070                 out.rotate = R.deg(math.acos(cos));
2071                 if (sin < 0) {
2072                     out.rotate = 360 - out.rotate;
2073                 }
2074             } else {
2075                 out.rotate = R.deg(math.asin(sin));
2076             }
2077
2078             out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
2079             out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
2080             out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
2081             return out;
2082         };
2083         /*\
2084          * Matrix.toTransformString
2085          [ method ]
2086          **
2087          * Return transform string that represents given matrix
2088          = (string) transform string
2089         \*/
2090         matrixproto.toTransformString = function () {
2091             var s = this.split();
2092             if (s.isSimple) {
2093                 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
2094             } else {
2095                 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
2096             }
2097         };
2098     })(Matrix.prototype);
2099
2100     // WebKit rendering bug workaround method
2101     var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
2102     if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
2103         (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
2104         /*\
2105          * Paper.safari
2106          [ method ]
2107          **
2108          * There is an inconvenient rendering bug in Safari (WebKit):
2109          * sometimes the rendering should be forced.
2110          * This method should help with dealing with this bug.
2111         \*/
2112         paperproto.safari = function () {
2113             var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
2114             setTimeout(function () {rect.remove();});
2115         };
2116     } else {
2117         paperproto.safari = fun;
2118     }
2119  
2120     // Events
2121     var preventDefault = function () {
2122         this.returnValue = false;
2123     },
2124     preventTouch = function () {
2125         return this.originalEvent.preventDefault();
2126     },
2127     stopPropagation = function () {
2128         this.cancelBubble = true;
2129     },
2130     stopTouch = function () {
2131         return this.originalEvent.stopPropagation();
2132     },
2133     addEvent = (function () {
2134         if (g.doc.addEventListener) {
2135             return function (obj, type, fn, element) {
2136                 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
2137                     f = function (e) {
2138                         var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2139                             scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2140                             x = e.clientX + scrollX,
2141                             y = e.clientY + scrollY;
2142                     if (supportsTouch && touchMap[has](type)) {
2143                         for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
2144                             if (e.targetTouches[i].target == obj) {
2145                                 var olde = e;
2146                                 e = e.targetTouches[i];
2147                                 e.originalEvent = olde;
2148                                 e.preventDefault = preventTouch;
2149                                 e.stopPropagation = stopTouch;
2150                                 break;
2151                             }
2152                         }
2153                     }
2154                     return fn.call(element, e, x, y);
2155                 };
2156                 obj.addEventListener(realName, f, false);
2157                 return function () {
2158                     obj.removeEventListener(realName, f, false);
2159                     return true;
2160                 };
2161             };
2162         } else if (g.doc.attachEvent) {
2163             return function (obj, type, fn, element) {
2164                 var f = function (e) {
2165                     e = e || g.win.event;
2166                     var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2167                         scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2168                         x = e.clientX + scrollX,
2169                         y = e.clientY + scrollY;
2170                     e.preventDefault = e.preventDefault || preventDefault;
2171                     e.stopPropagation = e.stopPropagation || stopPropagation;
2172                     return fn.call(element, e, x, y);
2173                 };
2174                 obj.attachEvent("on" + type, f);
2175                 var detacher = function () {
2176                     obj.detachEvent("on" + type, f);
2177                     return true;
2178                 };
2179                 return detacher;
2180             };
2181         }
2182     })(),
2183     drag = [],
2184     dragMove = function (e) {
2185         var x = e.clientX,
2186             y = e.clientY,
2187             scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2188             scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
2189             dragi,
2190             j = drag.length;
2191         while (j--) {
2192             dragi = drag[j];
2193             if (supportsTouch) {
2194                 var i = e.touches.length,
2195                     touch;
2196                 while (i--) {
2197                     touch = e.touches[i];
2198                     if (touch.identifier == dragi.el._drag.id) {
2199                         x = touch.clientX;
2200                         y = touch.clientY;
2201                         (e.originalEvent ? e.originalEvent : e).preventDefault();
2202                         break;
2203                     }
2204                 }
2205             } else {
2206                 e.preventDefault();
2207             }
2208             var node = dragi.el.node,
2209                 o,
2210                 next = node.nextSibling,
2211                 parent = node.parentNode,
2212                 display = node.style.display;
2213             g.win.opera && parent.removeChild(node);
2214             node.style.display = "none";
2215             o = dragi.el.paper.getElementByPoint(x, y);
2216             node.style.display = display;
2217             g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
2218             o && eve("drag.over." + dragi.el.id, dragi.el, o);
2219             x += scrollX;
2220             y += scrollY;
2221             eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
2222         }
2223     },
2224     dragUp = function (e) {
2225         R.unmousemove(dragMove).unmouseup(dragUp);
2226         var i = drag.length,
2227             dragi;
2228         while (i--) {
2229             dragi = drag[i];
2230             dragi.el._drag = {};
2231             eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
2232         }
2233         drag = [];
2234     },
2235     /*\
2236      * Raphael.el
2237      [ property (object) ]
2238      **
2239      * You can add your own method to elements. This is usefull when you want to hack default functionality or
2240      * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
2241      * you can redefine element method at any time. Expending element methods wouldn’t affect set.
2242      > Usage
2243      | Raphael.el.red = function () {
2244      |     this.attr({fill: "#f00"});
2245      | };
2246      | // then use it
2247      | paper.circle(100, 100, 20).red();
2248     \*/
2249     elproto = R.el = {};
2250     for (var i = events.length; i--;) {
2251         (function (eventName) {
2252             R[eventName] = elproto[eventName] = function (fn, scope) {
2253                 if (R.is(fn, "function")) {
2254                     this.events = this.events || [];
2255                     this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
2256                 }
2257                 return this;
2258             };
2259             R["un" + eventName] = elproto["un" + eventName] = function (fn) {
2260                 var events = this.events,
2261                     l = events.length;
2262                 while (l--) if (events[l].name == eventName && events[l].f == fn) {
2263                     events[l].unbind();
2264                     events.splice(l, 1);
2265                     !events.length && delete this.events;
2266                     return this;
2267                 }
2268                 return this;
2269             };
2270         })(events[i]);
2271     }
2272     
2273     /*\
2274      * Element.hover
2275      [ method ]
2276      **
2277      * Adds event handlers for hover for the element.
2278      > Parameters
2279      - f_in (function) handler for hover in
2280      - f_out (function) handler for hover out
2281      - icontext (object) #optional context for hover in handler
2282      - ocontext (object) #optional context for hover out handler
2283      = (object) @Element
2284     \*/
2285     elproto.hover = function (f_in, f_out, scope_in, scope_out) {
2286         return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
2287     };
2288     /*\
2289      * Element.unhover
2290      [ method ]
2291      **
2292      * Removes event handlers for hover for the element.
2293      > Parameters
2294      - f_in (function) handler for hover in
2295      - f_out (function) handler for hover out
2296      = (object) @Element
2297     \*/
2298     elproto.unhover = function (f_in, f_out) {
2299         return this.unmouseover(f_in).unmouseout(f_out);
2300     };
2301     /*\
2302      * Element.drag
2303      [ method ]
2304      **
2305      * Adds event handlers for drag of the element.
2306      > Parameters
2307      - onmove (function) handler for moving
2308      - onstart (function) handler for drag start
2309      - onend (function) handler for drag end
2310      - mcontext (object) #optional context for moving handler
2311      - scontext (object) #optional context for drag start handler
2312      - econtext (object) #optional context for drag end handler
2313      * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start, 
2314      * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element 
2315      * `drag.over.<id>` will be fired as well.
2316      *
2317      * Start event and start handler will be called in specified context or in context of the element with following parameters:
2318      o x (number) x position of the mouse
2319      o y (number) y position of the mouse
2320      o event (object) DOM event object
2321      * Move event and move handler will be called in specified context or in context of the element with following parameters:
2322      o dx (number) shift by x from the start point
2323      o dy (number) shift by y from the start point
2324      o x (number) x position of the mouse
2325      o y (number) y position of the mouse
2326      o event (object) DOM event object
2327      * End event and end handler will be called in specified context or in context of the element with following parameters:
2328      o event (object) DOM event object
2329      = (object) @Element
2330     \*/
2331     elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
2332         function start(e) {
2333             (e.originalEvent || e).preventDefault();
2334             var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
2335                 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
2336             this._drag.x = e.clientX + scrollX;
2337             this._drag.y = e.clientY + scrollY;
2338             this._drag.id = e.identifier;
2339             !drag.length && R.mousemove(dragMove).mouseup(dragUp);
2340             drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
2341             onstart && eve.on("drag.start." + this.id, onstart);
2342             onmove && eve.on("drag.move." + this.id, onmove);
2343             onend && eve.on("drag.end." + this.id, onend);
2344             eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
2345         }
2346         this._drag = {};
2347         this.mousedown(start);
2348         return this;
2349     };
2350     /*\
2351      * Element.onDragOver
2352      [ method ]
2353      **
2354      * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
2355      > Parameters
2356      - f (function) handler for event
2357     \*/
2358     elproto.onDragOver = function (f) {
2359         f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
2360     };
2361     /*\
2362      * Element.undrag
2363      [ method ]
2364      **
2365      * Removes all drag event handlers from given element.
2366     \*/
2367     elproto.undrag = function () {
2368         var i = drag.length;
2369         while (i--) if (drag[i].el == this) {
2370             R.unmousedown(drag[i].start);
2371             drag.splice(i++, 1);
2372             eve.unbind("drag.*." + this.id);
2373         }
2374         !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
2375     };
2376     /*\
2377      * Paper.circle
2378      [ method ]
2379      **
2380      * Draws a circle.
2381      **
2382      > Parameters
2383      **
2384      - x (number) x coordinate of the centre
2385      - y (number) y coordinate of the centre
2386      - r (number) radius
2387      = (object) Raphaël element object with type “circle”
2388      **
2389      > Usage
2390      | var c = paper.circle(50, 50, 40);
2391     \*/
2392     paperproto.circle = function (x, y, r) {
2393         var out = R._engine.circle(this, x || 0, y || 0, r || 0);
2394         this.__set__ && this.__set__.push(out);
2395         return out;
2396     };
2397     /*\
2398      * Paper.rect
2399      [ method ]
2400      *
2401      * Draws a rectangle.
2402      **
2403      > Parameters
2404      **
2405      - x (number) x coordinate of the top left corner
2406      - y (number) y coordinate of the top left corner
2407      - width (number) width
2408      - height (number) height
2409      - r (number) #optional radius for rounded corners, default is 0
2410      = (object) Raphaël element object with type “rect”
2411      **
2412      > Usage
2413      | // regular rectangle
2414      | var c = paper.rect(10, 10, 50, 50);
2415      | // rectangle with rounded corners
2416      | var c = paper.rect(40, 40, 50, 50, 10);
2417     \*/
2418     paperproto.rect = function (x, y, w, h, r) {
2419         var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
2420         this.__set__ && this.__set__.push(out);
2421         return out;
2422     };
2423     /*\
2424      * Paper.ellipse
2425      [ method ]
2426      **
2427      * Draws an ellipse.
2428      **
2429      > Parameters
2430      **
2431      - x (number) x coordinate of the centre
2432      - y (number) y coordinate of the centre
2433      - rx (number) horizontal radius
2434      - ry (number) vertical radius
2435      = (object) Raphaël element object with type “ellipse”
2436      **
2437      > Usage
2438      | var c = paper.ellipse(50, 50, 40, 20);
2439     \*/
2440     paperproto.ellipse = function (x, y, rx, ry) {
2441         var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
2442         this.__set__ && this.__set__.push(out);
2443         return out;
2444     };
2445     /*\
2446      * Paper.path
2447      [ method ]
2448      **
2449      * Creates a path element by given path data string.
2450      **
2451      > Parameters
2452      **
2453      - pathString (string) path data in SVG path string format.
2454      = (object) Raphaël element object with type “path”
2455      # 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>.
2456      **
2457      > Usage
2458      | var c = paper.path("M10 10L90 90");
2459      | // draw a diagonal line:
2460      | // move to 10,10, line to 90,90
2461     \*/
2462     paperproto.path = function (pathString) {
2463         pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
2464         var out = R._engine.path(R.format[apply](R, arguments), this);
2465         this.__set__ && this.__set__.push(out);
2466         return out;
2467     };
2468     /*\
2469      * Paper.image
2470      [ method ]
2471      **
2472      * Embeds an image into the surface.
2473      **
2474      > Parameters
2475      **
2476      - src (string) URI of the source image
2477      - x (number) x coordinate position
2478      - y (number) y coordinate position
2479      - width (number) width of the image
2480      - height (number) height of the image
2481      = (object) Raphaël element object with type “image”
2482      **
2483      > Usage
2484      | var c = paper.image("apple.png", 10, 10, 80, 80);
2485     \*/
2486     paperproto.image = function (src, x, y, w, h) {
2487         var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
2488         this.__set__ && this.__set__.push(out);
2489         return out;
2490     };
2491     /*\
2492      * Paper.text
2493      [ method ]
2494      **
2495      * Draws a text string. If you need line breaks, put “\n” in the string.
2496      **
2497      > Parameters
2498      **
2499      - x (number) x coordinate position
2500      - y (number) y coordinate position
2501      - text (string) The text string to draw
2502      = (object) Raphaël element object with type “text”
2503      **
2504      > Usage
2505      | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
2506     \*/
2507     paperproto.text = function (x, y, text) {
2508         var out = R._engine.text(this, x || 0, y || 0, Str(text));
2509         this.__set__ && this.__set__.push(out);
2510         return out;
2511     };
2512     /*\
2513      * Paper.set
2514      [ method ]
2515      **
2516      * Creates array-like object to keep and operate several elements at once.
2517      * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
2518      * Sets act as pseudo elements — all methods available to an element can be used on a set.
2519      = (object) array-like object that represents set of elements
2520      **
2521      > Usage
2522      | var st = paper.set();
2523      | st.push(
2524      |     paper.circle(10, 10, 5),
2525      |     paper.circle(30, 10, 5)
2526      | );
2527      | st.attr({fill: "red"}); // changes the fill of both circles
2528     \*/
2529     paperproto.set = function (itemsArray) {
2530         !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
2531         var out = new Set(itemsArray);
2532         this.__set__ && this.__set__.push(out);
2533         return out;
2534     };
2535     /*\
2536      * Paper.setStart
2537      [ method ]
2538      **
2539      * Creates @Paper.set. All elements that will be created after calling this method and before calling
2540      * @Paper.setFinish will be added to the set.
2541      **
2542      > Usage
2543      | paper.setStart();
2544      | paper.circle(10, 10, 5),
2545      | paper.circle(30, 10, 5)
2546      | var st = paper.setFinish();
2547      | st.attr({fill: "red"}); // changes the fill of both circles
2548     \*/
2549     paperproto.setStart = function (set) {
2550         this.__set__ = set || this.set();
2551     };
2552     /*\
2553      * Paper.setFinish
2554      [ method ]
2555      **
2556      * See @Paper.setStart. This method finishes catching and returns resulting set.
2557      **
2558      = (object) set
2559     \*/
2560     paperproto.setFinish = function (set) {
2561         var out = this.__set__;
2562         delete this.__set__;
2563         return out;
2564     };
2565     /*\
2566      * Paper.setSize
2567      [ method ]
2568      **
2569      * If you need to change dimensions of the canvas call this method
2570      **
2571      > Parameters
2572      **
2573      - width (number) new width of the canvas
2574      - height (number) new height of the canvas
2575      > Usage
2576      | var st = paper.set();
2577      | st.push(
2578      |     paper.circle(10, 10, 5),
2579      |     paper.circle(30, 10, 5)
2580      | );
2581      | st.attr({fill: "red"});
2582     \*/
2583     paperproto.setSize = R._engine.setSize;
2584     /*\
2585      * Paper.setViewBox
2586      [ method ]
2587      **
2588      * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by 
2589      * specifying new boundaries.
2590      **
2591      > Parameters
2592      **
2593      x, y, w, h, fit
2594      - x (number) new x position, default is `0`
2595      - y (number) new y position, default is `0`
2596      - w (number) new width of the canvas
2597      - h (number) new height of the canvas
2598      - fit (boolean) `true` if you want graphics to fit into new boundary box
2599     \*/
2600     paperproto.setViewBox = R._engine.setViewBox;
2601     /*\
2602      * Paper.top
2603      [ property ]
2604      **
2605      * Points to the topmost element on the paper
2606     \*/
2607     /*\
2608      * Paper.bottom
2609      [ property ]
2610      **
2611      * Points to the bottom element on the paper
2612     \*/
2613     paperproto.top = paperproto.bottom = null;
2614     /*\
2615      * Paper.raphael
2616      [ property ]
2617      **
2618      * Points to the @Raphael object/function
2619     \*/
2620     paperproto.raphael = R;
2621     var getOffset = function (elem) {
2622         var box = elem.getBoundingClientRect(),
2623             doc = elem.ownerDocument,
2624             body = doc.body,
2625             docElem = doc.documentElement,
2626             clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
2627             top  = box.top  + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
2628             left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
2629         return {
2630             y: top,
2631             x: left
2632         };
2633     };
2634     /*\
2635      * Paper.getElementByPoint
2636      [ method ]
2637      **
2638      * Returns you topmost element under given point.
2639      **
2640      = (object) Raphaël element object
2641      > Parameters
2642      **
2643      - x (number) x coordinate from the top left corner of the window
2644      - y (number) y coordinate from the top left corner of the window
2645      > Usage
2646      | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
2647     \*/
2648     paperproto.getElementByPoint = function (x, y) {
2649         var paper = this,
2650             svg = paper.canvas,
2651             target = g.doc.elementFromPoint(x, y);
2652         if (g.win.opera && target.tagName == "svg") {
2653             var so = getOffset(svg),
2654                 sr = svg.createSVGRect();
2655             sr.x = x - so.x;
2656             sr.y = y - so.y;
2657             sr.width = sr.height = 1;
2658             var hits = svg.getIntersectionList(sr, null);
2659             if (hits.length) {
2660                 target = hits[hits.length - 1];
2661             }
2662         }
2663         if (!target) {
2664             return null;
2665         }
2666         while (target.parentNode && target != svg.parentNode && !target.raphael) {
2667             target = target.parentNode;
2668         }
2669         target == paper.canvas.parentNode && (target = svg);
2670         target = target && target.raphael ? paper.getById(target.raphaelid) : null;
2671         return target;
2672     };
2673     /*\
2674      * Paper.getById
2675      [ method ]
2676      **
2677      * Returns you element by its internal ID.
2678      **
2679      > Parameters
2680      **
2681      - id (number) id
2682      = (object) Raphaël element object
2683     \*/
2684     paperproto.getById = function (id) {
2685         var bot = this.bottom;
2686         while (bot) {
2687             if (bot.id == id) {
2688                 return bot;
2689             }
2690             bot = bot.next;
2691         }
2692         return null;
2693     };
2694     /*\
2695      * Paper.forEach
2696      [ method ]
2697      **
2698      * Executes given function for each element on the paper
2699      *
2700      * If callback function returns `false` it will stop loop running.
2701      **
2702      > Parameters
2703      **
2704      - callback (function) function to run
2705      - thisArg (object) context object for the callback
2706      = (object) Paper object
2707     \*/
2708     paperproto.forEach = function (callback, thisArg) {
2709         var bot = this.bottom;
2710         while (bot) {
2711             if (callback.call(thisArg, bot) === false) {
2712                 return this;
2713             }
2714             bot = bot.next;
2715         }
2716         return this;
2717     };
2718     function x_y() {
2719         return this.x + S + this.y;
2720     }
2721     function x_y_w_h() {
2722         return this.x + S + this.y + S + this.width + " \xd7 " + this.height;
2723     }
2724     /*\
2725      * Element.getBBox
2726      [ method ]
2727      **
2728      * Return bounding box for a given element
2729      **
2730      > Parameters
2731      **
2732      - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
2733      = (object) Bounding box object:
2734      o {
2735      o     x: (number) top left corner x
2736      o     y: (number) top left corner y
2737      o     width: (number) width
2738      o     height: (number) height
2739      o }
2740     \*/
2741     elproto.getBBox = function (isWithoutTransform) {
2742         if (this.removed) {
2743             return {};
2744         }
2745         var _ = this._;
2746         if (isWithoutTransform) {
2747             if (_.dirty || !_.bboxwt) {
2748                 this.realPath = getPath[this.type](this);
2749                 _.bboxwt = pathDimensions(this.realPath);
2750                 _.bboxwt.toString = x_y_w_h;
2751                 _.dirty = 0;
2752             }
2753             return _.bboxwt;
2754         }
2755         if (_.dirty || _.dirtyT || !_.bbox) {
2756             if (_.dirty || !this.realPath) {
2757                 _.bboxwt = 0;
2758                 this.realPath = getPath[this.type](this);
2759             }
2760             _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
2761             _.bbox.toString = x_y_w_h;
2762             _.dirty = _.dirtyT = 0;
2763         }
2764         return _.bbox;
2765     };
2766     /*\
2767      * Element.clone
2768      [ method ]
2769      **
2770      = (object) clone of a given element
2771      **
2772     \*/
2773     elproto.clone = function () {
2774         if (this.removed) {
2775             return null;
2776         }
2777         return this.paper[this.type]().attr(this.attr());
2778     };
2779     /*\
2780      * Element.glow
2781      [ method ]
2782      **
2783      * Return set of elements that create glow-like effect around given element. See @Paper.set.
2784      *
2785      * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
2786      **
2787      > Parameters
2788      **
2789      - glow (object) #optional parameters object with all properties optional:
2790      o {
2791      o     width (number) size of the glow, default is `10`
2792      o     fill (boolean) will it be filled, default is `false`
2793      o     opacity (number) opacity, default is `0.5`
2794      o     offsetx (number) horizontal offset, default is `0`
2795      o     offsety (number) vertical offset, default is `0`
2796      o     color (string) glow colour, default is `black`
2797      o }
2798      = (object) @Paper.set of elements that represents glow
2799     \*/
2800     elproto.glow = function (glow) {
2801         if (this.type == "text") {
2802             return null;
2803         }
2804         glow = glow || {};
2805         var s = {
2806             width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
2807             fill: glow.fill || false,
2808             opacity: glow.opacity || .5,
2809             offsetx: glow.offsetx || 0,
2810             offsety: glow.offsety || 0,
2811             color: glow.color || "#000"
2812         },
2813             c = s.width / 2,
2814             r = this.paper,
2815             out = r.set(),
2816             path = this.realPath || getPath[this.type](this);
2817         path = this.matrix ? mapPath(path, this.matrix) : path;
2818         for (var i = 1; i < c + 1; i++) {
2819             out.push(r.path(path).attr({
2820                 stroke: s.color,
2821                 fill: s.fill ? s.color : "none",
2822                 "stroke-linejoin": "round",
2823                 "stroke-linecap": "round",
2824                 "stroke-width": +(s.width / c * i).toFixed(3),
2825                 opacity: +(s.opacity / c).toFixed(3)
2826             }));
2827         }
2828         return out.insertBefore(this).translate(s.offsetx, s.offsety);
2829     };
2830     var curveslengths = {},
2831     getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
2832         var len = 0,
2833             precision = 100,
2834             name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
2835             cache = curveslengths[name],
2836             old, dot;
2837         !cache && (curveslengths[name] = cache = {data: []});
2838         cache.timer && clearTimeout(cache.timer);
2839         cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
2840         if (length != null && !cache.precision) {
2841             var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
2842             cache.precision = ~~total * 10;
2843             cache.data = [];
2844         }
2845         precision = cache.precision || precision;
2846         for (var i = 0; i < precision + 1; i++) {
2847             if (cache.data[i * precision]) {
2848                 dot = cache.data[i * precision];
2849             } else {
2850                 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
2851                 cache.data[i * precision] = dot;
2852             }
2853             i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
2854             if (length != null && len >= length) {
2855                 return dot;
2856             }
2857             old = dot;
2858         }
2859         if (length == null) {
2860             return len;
2861         }
2862     },
2863     getLengthFactory = function (istotal, subpath) {
2864         return function (path, length, onlystart) {
2865             path = path2curve(path);
2866             var x, y, p, l, sp = "", subpaths = {}, point,
2867                 len = 0;
2868             for (var i = 0, ii = path.length; i < ii; i++) {
2869                 p = path[i];
2870                 if (p[0] == "M") {
2871                     x = +p[1];
2872                     y = +p[2];
2873                 } else {
2874                     l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
2875                     if (len + l > length) {
2876                         if (subpath && !subpaths.start) {
2877                             point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
2878                             sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
2879                             if (onlystart) {return sp;}
2880                             subpaths.start = sp;
2881                             sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
2882                             len += l;
2883                             x = +p[5];
2884                             y = +p[6];
2885                             continue;
2886                         }
2887                         if (!istotal && !subpath) {
2888                             point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
2889                             return {x: point.x, y: point.y, alpha: point.alpha};
2890                         }
2891                     }
2892                     len += l;
2893                     x = +p[5];
2894                     y = +p[6];
2895                 }
2896                 sp += p.shift() + p;
2897             }
2898             subpaths.end = sp;
2899             point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[1], p[2], p[3], p[4], p[5], p[6], 1);
2900             point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
2901             return point;
2902         };
2903     };
2904     var getTotalLength = getLengthFactory(1),
2905         getPointAtLength = getLengthFactory(),
2906         getSubpathsAtLength = getLengthFactory(0, 1);
2907     /*\
2908      * Raphael.getTotalLength
2909      [ method ]
2910      **
2911      * Returns length of the given path in pixels.
2912      **
2913      > Parameters
2914      **
2915      - path (string) SVG path string.
2916      **
2917      = (number) length.
2918     \*/
2919     R.getTotalLength = getTotalLength;
2920     /*\
2921      * Raphael.getPointAtLength
2922      [ method ]
2923      **
2924      * Return coordinates of the point located at the given length on the given path.
2925      **
2926      > Parameters
2927      **
2928      - path (string) SVG path string
2929      - length (number)
2930      **
2931      = (object) representation of the point:
2932      o {
2933      o     x: (number) x coordinate
2934      o     y: (number) y coordinate
2935      o     alpha: (number) angle of derivative
2936      o }
2937     \*/
2938     R.getPointAtLength = getPointAtLength;
2939     /*\
2940      * Raphael.getSubpath
2941      [ method ]
2942      **
2943      * Return subpath of a given path from given length to given length.
2944      **
2945      > Parameters
2946      **
2947      - path (string) SVG path string
2948      - from (number) position of the start of the segment
2949      - to (number) position of the end of the segment
2950      **
2951      = (string) pathstring for the segment
2952     \*/
2953     R.getSubpath = function (path, from, to) {
2954         if (abs(this.getTotalLength(path) - to) < 1e-6) {
2955             return getSubpathsAtLength(path, from).end;
2956         }
2957         var a = getSubpathsAtLength(path, to, 1);
2958         return from ? getSubpathsAtLength(a, from).end : a;
2959     };
2960     /*\
2961      * Element.getTotalLength
2962      [ method ]
2963      **
2964      * Returns length of the path in pixels. Only works for element of “path” type.
2965      = (number) length.
2966     \*/
2967     elproto.getTotalLength = function () {
2968         if (this.type != "path") {return;}
2969         if (this.node.getTotalLength) {
2970             return this.node.getTotalLength();
2971         }
2972         return getTotalLength(this.attrs.path);
2973     };
2974     /*\
2975      * Element.getPointAtLength
2976      [ method ]
2977      **
2978      * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
2979      **
2980      > Parameters
2981      **
2982      - length (number)
2983      **
2984      = (object) representation of the point:
2985      o {
2986      o     x: (number) x coordinate
2987      o     y: (number) y coordinate
2988      o     alpha: (number) angle of derivative
2989      o }
2990     \*/
2991     elproto.getPointAtLength = function (length) {
2992         if (this.type != "path") {return;}
2993         return getPointAtLength(this.attrs.path, length);
2994     };
2995     /*\
2996      * Element.getSubpath
2997      [ method ]
2998      **
2999      * Return subpath of a given element from given length to given length. Only works for element of “path” type.
3000      **
3001      > Parameters
3002      **
3003      - from (number) position of the start of the segment
3004      - to (number) position of the end of the segment
3005      **
3006      = (string) pathstring for the segment
3007     \*/
3008     elproto.getSubpath = function (from, to) {
3009         if (this.type != "path") {return;}
3010         return R.getSubpath(this.attrs.path, from, to);
3011     };
3012     /*\
3013      * Raphael.easing_formulas
3014      [ property ]
3015      **
3016      * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
3017      # <ul>
3018      #     <li>“linear”</li>
3019      #     <li>“&lt;” or “easeIn” or “ease-in”</li>
3020      #     <li>“>” or “easeOut” or “ease-out”</li>
3021      #     <li>“&lt;>” or “easeInOut” or “ease-in-out”</li>
3022      #     <li>“backIn” or “back-in”</li>
3023      #     <li>“backOut” or “back-out”</li>
3024      #     <li>“elastic”</li>
3025      #     <li>“bounce”</li>
3026      # </ul>
3027      # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
3028     \*/
3029     var ef = R.easing_formulas = {
3030         linear: function (n) {
3031             return n;
3032         },
3033         "<": function (n) {
3034             return pow(n, 1.7);
3035         },
3036         ">": function (n) {
3037             return pow(n, .48);
3038         },
3039         "<>": function (n) {
3040             var q = .48 - n / 1.04,
3041                 Q = math.sqrt(.1734 + q * q),
3042                 x = Q - q,
3043                 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
3044                 y = -Q - q,
3045                 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
3046                 t = X + Y + .5;
3047             return (1 - t) * 3 * t * t + t * t * t;
3048         },
3049         backIn: function (n) {
3050             var s = 1.70158;
3051             return n * n * ((s + 1) * n - s);
3052         },
3053         backOut: function (n) {
3054             n = n - 1;
3055             var s = 1.70158;
3056             return n * n * ((s + 1) * n + s) + 1;
3057         },
3058         elastic: function (n) {
3059             if (n == !!n) {
3060                 return n;
3061             }
3062             return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
3063         },
3064         bounce: function (n) {
3065             var s = 7.5625,
3066                 p = 2.75,
3067                 l;
3068             if (n < (1 / p)) {
3069                 l = s * n * n;
3070             } else {
3071                 if (n < (2 / p)) {
3072                     n -= (1.5 / p);
3073                     l = s * n * n + .75;
3074                 } else {
3075                     if (n < (2.5 / p)) {
3076                         n -= (2.25 / p);
3077                         l = s * n * n + .9375;
3078                     } else {
3079                         n -= (2.625 / p);
3080                         l = s * n * n + .984375;
3081                     }
3082                 }
3083             }
3084             return l;
3085         }
3086     };
3087     ef.easeIn = ef["ease-in"] = ef["<"];
3088     ef.easeOut = ef["ease-out"] = ef[">"];
3089     ef.easeInOut = ef["ease-in-out"] = ef["<>"];
3090     ef["back-in"] = ef.backIn;
3091     ef["back-out"] = ef.backOut;
3092
3093     var animationElements = [],
3094         requestAnimFrame = window.requestAnimationFrame       ||
3095                            window.webkitRequestAnimationFrame ||
3096                            window.mozRequestAnimationFrame    ||
3097                            window.oRequestAnimationFrame      ||
3098                            window.msRequestAnimationFrame     ||
3099                            function (callback) {
3100                                setTimeout(callback, 16);
3101                            },
3102         animation = function () {
3103             var Now = +new Date,
3104                 l = 0;
3105             for (; l < animationElements.length; l++) {
3106                 var e = animationElements[l];
3107                 if (e.el.removed || e.paused) {
3108                     continue;
3109                 }
3110                 var time = Now - e.start,
3111                     ms = e.ms,
3112                     easing = e.easing,
3113                     from = e.from,
3114                     diff = e.diff,
3115                     to = e.to,
3116                     t = e.t,
3117                     that = e.el,
3118                     set = {},
3119                     now;
3120                 if (e.initstatus) {
3121                     time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
3122                     e.status = e.initstatus;
3123                     delete e.initstatus;
3124                     e.stop && animationElements.splice(l--, 1);
3125                 } else {
3126                     e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
3127                 }
3128                 if (time < 0) {
3129                     continue;
3130                 }
3131                 if (time < ms) {
3132                     var pos = easing(time / ms);
3133                     for (var attr in from) if (from[has](attr)) {
3134                         switch (availableAnimAttrs[attr]) {
3135                             case nu:
3136                                 now = +from[attr] + pos * ms * diff[attr];
3137                                 break;
3138                             case "colour":
3139                                 now = "rgb(" + [
3140                                     upto255(round(from[attr].r + pos * ms * diff[attr].r)),
3141                                     upto255(round(from[attr].g + pos * ms * diff[attr].g)),
3142                                     upto255(round(from[attr].b + pos * ms * diff[attr].b))
3143                                 ].join(",") + ")";
3144                                 break;
3145                             case "path":
3146                                 now = [];
3147                                 for (var i = 0, ii = from[attr].length; i < ii; i++) {
3148                                     now[i] = [from[attr][i][0]];
3149                                     for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3150                                         now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
3151                                     }
3152                                     now[i] = now[i].join(S);
3153                                 }
3154                                 now = now.join(S);
3155                                 break;
3156                             case "transform":
3157                                 if (diff[attr].real) {
3158                                     now = [];
3159                                     for (i = 0, ii = from[attr].length; i < ii; i++) {
3160                                         now[i] = [from[attr][i][0]];
3161                                         for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3162                                             now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
3163                                         }
3164                                     }
3165                                 } else {
3166                                     var get = function (i) {
3167                                         return +from[attr][i] + pos * ms * diff[attr][i];
3168                                     };
3169                                     // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
3170                                     now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
3171                                 }
3172                                 break;
3173                             case "csv":
3174                                 if (attr == "clip-rect") {
3175                                     now = [];
3176                                     i = 4;
3177                                     while (i--) {
3178                                         now[i] = +from[attr][i] + pos * ms * diff[attr][i];
3179                                     }
3180                                 }
3181                                 break;
3182                             default:
3183                                 var from2 = [].concat(from[attr]);
3184                                 now = [];
3185                                 i = that.paper.customAttributes[attr].length;
3186                                 while (i--) {
3187                                     now[i] = +from2[i] + pos * ms * diff[attr][i];
3188                                 }
3189                                 break;
3190                         }
3191                         set[attr] = now;
3192                     }
3193                     that.attr(set);
3194                     (function (id, that, anim) {
3195                         setTimeout(function () {
3196                             eve("anim.frame." + id, that, anim);
3197                         });
3198                     })(that.id, that, e.anim);
3199                 } else {
3200                     (function(f, el, a) {
3201                         setTimeout(function() {
3202                             eve("anim.frame." + el.id, el, a);
3203                             eve("anim.finish." + el.id, el, a);
3204                             R.is(f, "function") && f.call(el);
3205                         });
3206                     })(e.callback, that, e.anim);
3207                     that.attr(to);
3208                     animationElements.splice(l--, 1);
3209                     if (e.repeat > 1 && !e.next) {
3210                         runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
3211                     }
3212                     if (e.next && !e.stop) {
3213                         runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
3214                     }
3215                 }
3216             }
3217             R.svg && that && that.paper && that.paper.safari();
3218             animationElements.length && requestAnimFrame(animation);
3219         },
3220         upto255 = function (color) {
3221             return color > 255 ? 255 : color < 0 ? 0 : color;
3222         };
3223     /*\
3224      * Element.animateWith
3225      [ method ]
3226      **
3227      * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
3228      **
3229      > Parameters
3230      **
3231      - params (object) final attributes for the element, see also @Element.attr
3232      - ms (number) number of milliseconds for animation to run
3233      - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
3234      - callback (function) #optional callback function. Will be called at the end of animation.
3235      * or
3236      - animation (object) animation object, see @Raphael.animation
3237      **
3238      = (object) original element
3239     \*/
3240     elproto.animateWith = function (element, params, ms, easing, callback) {
3241         this.animate(params, ms, easing, callback);
3242         var start, el;
3243         for (var i = 0, ii = animationElements.length; i < ii; i++) {
3244             el = animationElements[i];
3245             if (el.el.id == element.id) {
3246                 start = el.timestamp;
3247             } else if (el.el.id == this.id) {
3248                 el.start = start;
3249             }
3250         }
3251         return this.animate(params, ms, easing, callback);
3252     };
3253     function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
3254         var cx = 3 * p1x,
3255             bx = 3 * (p2x - p1x) - cx,
3256             ax = 1 - cx - bx,
3257             cy = 3 * p1y,
3258             by = 3 * (p2y - p1y) - cy,
3259             ay = 1 - cy - by;
3260         function sampleCurveX(t) {
3261             return ((ax * t + bx) * t + cx) * t;
3262         }
3263         function solve(x, epsilon) {
3264             var t = solveCurveX(x, epsilon);
3265             return ((ay * t + by) * t + cy) * t;
3266         }
3267         function solveCurveX(x, epsilon) {
3268             var t0, t1, t2, x2, d2, i;
3269             for(t2 = x, i = 0; i < 8; i++) {
3270                 x2 = sampleCurveX(t2) - x;
3271                 if (abs(x2) < epsilon) {
3272                     return t2;
3273                 }
3274                 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
3275                 if (abs(d2) < 1e-6) {
3276                     break;
3277                 }
3278                 t2 = t2 - x2 / d2;
3279             }
3280             t0 = 0;
3281             t1 = 1;
3282             t2 = x;
3283             if (t2 < t0) {
3284                 return t0;
3285             }
3286             if (t2 > t1) {
3287                 return t1;
3288             }
3289             while (t0 < t1) {
3290                 x2 = sampleCurveX(t2);
3291                 if (abs(x2 - x) < epsilon) {
3292                     return t2;
3293                 }
3294                 if (x > x2) {
3295                     t0 = t2;
3296                 } else {
3297                     t1 = t2;
3298                 }
3299                 t2 = (t1 - t0) / 2 + t0;
3300             }
3301             return t2;
3302         }
3303         return solve(t, 1 / (200 * duration));
3304     }
3305     elproto.onAnimation = function (f) {
3306         f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
3307         return this;
3308     };
3309     function Animation(anim, ms) {
3310         var percents = [];
3311         this.anim = anim;
3312         this.ms = ms;
3313         this.times = 1;
3314         if (this.anim) {
3315             for (var attr in this.anim) if (this.anim[has](attr)) {
3316                 percents.push(+attr);
3317             }
3318             percents.sort(sortByNumber);
3319         }
3320         this.top = percents[percents.length - 1];
3321         this.percents = percents;
3322     }
3323     /*\
3324      * Animation.delay
3325      [ method ]
3326      **
3327      * Creates a copy of existing animation object with given delay.
3328      **
3329      > Parameters
3330      **
3331      - delay (number) number of ms to pass between animation start and actual animation
3332      **
3333      = (object) new altered Animation object
3334     \*/
3335     Animation.prototype.delay = function (delay) {
3336         var a = new Animation(this.anim, this.ms);
3337         a.times = this.times;
3338         a.del = +delay || 0;
3339         return a;
3340     };
3341     /*\
3342      * Animation.repeat
3343      [ method ]
3344      **
3345      * Creates a copy of existing animation object with given repetition.
3346      **
3347      > Parameters
3348      **
3349      - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
3350      **
3351      = (object) new altered Animation object
3352     \*/
3353     Animation.prototype.repeat = function (times) { 
3354         var a = new Animation(this.anim, this.ms);
3355         a.del = this.del;
3356         a.times = math.floor(mmax(times, 0)) || 1;
3357         return a;
3358     };
3359     function runAnimation(anim, element, percent, status, totalOrigin, times) {
3360         percent = toFloat(percent);
3361         var params,
3362             isInAnim,
3363             isInAnimSet,
3364             percents = [],
3365             next,
3366             prev,
3367             timestamp,
3368             ms = anim.ms,
3369             from = {},
3370             to = {},
3371             diff = {};
3372         if (status) {
3373             for (i = 0, ii = animationElements.length; i < ii; i++) {
3374                 var e = animationElements[i];
3375                 if (e.el.id == element.id && e.anim == anim) {
3376                     if (e.percent != percent) {
3377                         animationElements.splice(i, 1);
3378                         isInAnimSet = 1;
3379                     } else {
3380                         isInAnim = e;
3381                     }
3382                     element.attr(e.totalOrigin);
3383                     break;
3384                 }
3385             }
3386         } else {
3387             status = +to; // NaN
3388         }
3389         for (var i = 0, ii = anim.percents.length; i < ii; i++) {
3390             if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
3391                 percent = anim.percents[i];
3392                 prev = anim.percents[i - 1] || 0;
3393                 ms = ms / anim.top * (percent - prev);
3394                 next = anim.percents[i + 1];
3395                 params = anim.anim[percent];
3396                 break;
3397             } else if (status) {
3398                 element.attr(anim.anim[anim.percents[i]]);
3399             }
3400         }
3401         if (!params) {
3402             return;
3403         }
3404         if (!isInAnim) {
3405             for (attr in params) if (params[has](attr)) {
3406                 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
3407                     from[attr] = element.attr(attr);
3408                     (from[attr] == null) && (from[attr] = availableAttrs[attr]);
3409                     to[attr] = params[attr];
3410                     switch (availableAnimAttrs[attr]) {
3411                         case nu:
3412                             diff[attr] = (to[attr] - from[attr]) / ms;
3413                             break;
3414                         case "colour":
3415                             from[attr] = R.getRGB(from[attr]);
3416                             var toColour = R.getRGB(to[attr]);
3417                             diff[attr] = {
3418                                 r: (toColour.r - from[attr].r) / ms,
3419                                 g: (toColour.g - from[attr].g) / ms,
3420                                 b: (toColour.b - from[attr].b) / ms
3421                             };
3422                             break;
3423                         case "path":
3424                             var pathes = path2curve(from[attr], to[attr]),
3425                                 toPath = pathes[1];
3426                             from[attr] = pathes[0];
3427                             diff[attr] = [];
3428                             for (i = 0, ii = from[attr].length; i < ii; i++) {
3429                                 diff[attr][i] = [0];
3430                                 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
3431                                     diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
3432                                 }
3433                             }
3434                             break;
3435                         case "transform":
3436                             var _ = element._,
3437                                 eq = equaliseTransform(_[attr], to[attr]);
3438                             if (eq) {
3439                                 from[attr] = eq.from;
3440                                 to[attr] = eq.to;
3441                                 diff[attr] = [];
3442                                 diff[attr].real = true;
3443                                 for (i = 0, ii = from[attr].length; i < ii; i++) {
3444                                     diff[attr][i] = [from[attr][i][0]];
3445                                     for (j = 1, jj = from[attr][i].length; j < jj; j++) {
3446                                         diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
3447                                     }
3448                                 }
3449                             } else {
3450                                 var m = (element.matrix || new Matrix),
3451                                     to2 = {
3452                                         _: {transform: _.transform},
3453                                         getBBox: function () {
3454                                             return element.getBBox(1);
3455                                         }
3456                                     };
3457                                 from[attr] = [
3458                                     m.a,
3459                                     m.b,
3460                                     m.c,
3461                                     m.d,
3462                                     m.e,
3463                                     m.f
3464                                 ];
3465                                 extractTransform(to2, to[attr]);
3466                                 to[attr] = to2._.transform;
3467                                 diff[attr] = [
3468                                     (to2.matrix.a - m.a) / ms,
3469                                     (to2.matrix.b - m.b) / ms,
3470                                     (to2.matrix.c - m.c) / ms,
3471                                     (to2.matrix.d - m.d) / ms,
3472                                     (to2.matrix.e - m.e) / ms,
3473                                     (to2.matrix.e - m.f) / ms
3474                                 ];
3475                                 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
3476                                 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
3477                                 // extractTransform(to2, to[attr]);
3478                                 // diff[attr] = [
3479                                 //     (to2._.sx - _.sx) / ms,
3480                                 //     (to2._.sy - _.sy) / ms,
3481                                 //     (to2._.deg - _.deg) / ms,
3482                                 //     (to2._.dx - _.dx) / ms,
3483                                 //     (to2._.dy - _.dy) / ms
3484                                 // ];
3485                             }
3486                             break;
3487                         case "csv":
3488                             var values = Str(params[attr]).split(separator),
3489                                 from2 = Str(from[attr]).split(separator);
3490                             if (attr == "clip-rect") {
3491                                 from[attr] = from2;
3492                                 diff[attr] = [];
3493                                 i = from2.length;
3494                                 while (i--) {
3495                                     diff[attr][i] = (values[i] - from[attr][i]) / ms;
3496                                 }
3497                             }
3498                             to[attr] = values;
3499                             break;
3500                         default:
3501                             values = [].concat(params[attr]);
3502                             from2 = [].concat(from[attr]);
3503                             diff[attr] = [];
3504                             i = element.paper.customAttributes[attr].length;
3505                             while (i--) {
3506                                 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
3507                             }
3508                             break;
3509                     }
3510                 }
3511             }
3512             var easing = params.easing,
3513                 easyeasy = R.easing_formulas[easing];
3514             if (!easyeasy) {
3515                 easyeasy = Str(easing).match(bezierrg);
3516                 if (easyeasy && easyeasy.length == 5) {
3517                     var curve = easyeasy;
3518                     easyeasy = function (t) {
3519                         return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
3520                     };
3521                 } else {
3522                     easyeasy = pipe;
3523                 }
3524             }
3525             timestamp = params.start || anim.start || +new Date;
3526             e = {
3527                 anim: anim,
3528                 percent: percent,
3529                 timestamp: timestamp,
3530                 start: timestamp + (anim.del || 0),
3531                 status: 0,
3532                 initstatus: status || 0,
3533                 stop: false,
3534                 ms: ms,
3535                 easing: easyeasy,
3536                 from: from,
3537                 diff: diff,
3538                 to: to,
3539                 el: element,
3540                 callback: params.callback,
3541                 prev: prev,
3542                 next: next,
3543                 repeat: times || anim.times,
3544                 origin: element.attr(),
3545                 totalOrigin: totalOrigin
3546             };
3547             animationElements.push(e);
3548             if (status && !isInAnim) {
3549                 e.stop = true;
3550                 e.start = new Date - ms * status;
3551                 if (animationElements.length == 1) {
3552                     return animation();
3553                 }
3554             }
3555             animationElements.length == 1 && requestAnimFrame(animation);
3556         } else {
3557             isInAnim.initstatus = status;
3558             isInAnim.start = new Date - isInAnim.ms * status;
3559         }
3560         eve("anim.start." + element.id, element, anim);
3561     }
3562     /*\
3563      * Raphael.animation
3564      [ method ]
3565      **
3566      * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
3567      * See also @Animation.delay and @Animation.repeat methods.
3568      **
3569      > Parameters
3570      **
3571      - params (object) final attributes for the element, see also @Element.attr
3572      - ms (number) number of milliseconds for animation to run
3573      - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
3574      - callback (function) #optional callback function. Will be called at the end of animation.
3575      **
3576      = (object) @Animation
3577     \*/
3578     R.animation = function (params, ms, easing, callback) {
3579         if (R.is(easing, "function") || !easing) {
3580             callback = callback || easing || null;
3581             easing = null;
3582         }
3583         params = Object(params);
3584         ms = +ms || 0;
3585         var p = {},
3586             json,
3587             attr;
3588         for (attr in params) if (params[has](attr) && toFloat(attr) != attr) {
3589             json = true;
3590             p[attr] = params[attr];
3591         }
3592         if (!json) {
3593             return new Animation(params, ms);
3594         } else {
3595             easing && (p.easing = easing);
3596             callback && (p.callback = callback);
3597             return new Animation({100: p}, ms);
3598         }
3599     };
3600     /*\
3601      * Element.animate
3602      [ method ]
3603      **
3604      * Creates and starts animation for given element.
3605      **
3606      > Parameters
3607      **
3608      - params (object) final attributes for the element, see also @Element.attr
3609      - ms (number) number of milliseconds for animation to run
3610      - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
3611      - callback (function) #optional callback function. Will be called at the end of animation.
3612      * or
3613      - animation (object) animation object, see @Raphael.animation
3614      **
3615      = (object) original element
3616     \*/
3617     elproto.animate = function (params, ms, easing, callback) {
3618         var element = this;
3619         if (element.removed) {
3620             callback && callback.call(element);
3621             return element;
3622         }
3623         var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
3624         runAnimation(anim, element, anim.percents[0], null, element.attr());
3625         return element;
3626     };
3627     /*\
3628      * Element.setTime
3629      [ method ]
3630      **
3631      * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
3632      **
3633      > Parameters
3634      **
3635      - anim (object) animation object
3636      - value (number) number of milliseconds from the beginning of the animation
3637      **
3638      = (object) original element if `value` is specified
3639      * Note, that during animation following events are triggered:
3640      *
3641      * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
3642     \*/
3643     elproto.setTime = function (anim, value) {
3644         if (anim && value != null) {
3645             this.status(anim, mmin(value, anim.ms) / anim.ms);
3646         }
3647         return this;
3648     };
3649     /*\
3650      * Element.status
3651      [ method ]
3652      **
3653      * Gets or sets the status of animation of the element.
3654      **
3655      > Parameters
3656      **
3657      - anim (object) #optional animation object
3658      - 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.
3659      **
3660      = (number) status
3661      * or
3662      = (array) status if `anim` is not specified. Array of objects in format:
3663      o {
3664      o     anim: (object) animation object
3665      o     status: (number) status
3666      o }
3667      * or
3668      = (object) original element if `value` is specified
3669     \*/
3670     elproto.status = function (anim, value) {
3671         var out = [],
3672             i = 0,
3673             len,
3674             e;
3675         if (value != null) {
3676             runAnimation(anim, this, -1, mmin(value, 1));
3677             return this;
3678         } else {
3679             len = animationElements.length;
3680             for (; i < len; i++) {
3681                 e = animationElements[i];
3682                 if (e.el.id == this.id && (!anim || e.anim == anim)) {
3683                     if (anim) {
3684                         return e.status;
3685                     }
3686                     out.push({anim: e.anim, status: e.status});
3687                 }
3688             }
3689             if (anim) {
3690                 return 0;
3691             }
3692             return out;
3693         }
3694     };
3695     /*\
3696      * Element.pause
3697      [ method ]
3698      **
3699      * Stops animation of the element with ability to resume it later on.
3700      **
3701      > Parameters
3702      **
3703      - anim (object) #optional animation object
3704      **
3705      = (object) original element
3706     \*/
3707     elproto.pause = function (anim) {
3708         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3709             if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
3710                 animationElements[i].paused = true;
3711             }
3712         }
3713         return this;
3714     };
3715     /*\
3716      * Element.resume
3717      [ method ]
3718      **
3719      * Resumes animation if it was paused with @Element.pause method.
3720      **
3721      > Parameters
3722      **
3723      - anim (object) #optional animation object
3724      **
3725      = (object) original element
3726     \*/
3727     elproto.resume = function (anim) {
3728         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3729             var e = animationElements[i];
3730             if (eve("anim.resume." + this.id, this, e.anim) !== false) {
3731                 delete e.paused;
3732                 this.status(e.anim, e.status);
3733             }
3734         }
3735         return this;
3736     };
3737     /*\
3738      * Element.stop
3739      [ method ]
3740      **
3741      * Stops animation of the element.
3742      **
3743      > Parameters
3744      **
3745      - anim (object) #optional animation object
3746      **
3747      = (object) original element
3748     \*/
3749     elproto.stop = function (anim) {
3750         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
3751             if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
3752                 animationElements.splice(i--, 1);
3753             }
3754         }
3755         return this;
3756     };
3757     elproto.toString = function () {
3758         return "Rapha\xebl\u2019s object";
3759     };
3760
3761     // Set
3762     var Set = function (items) {
3763         this.items = [];
3764         this.length = 0;
3765         this.type = "set";
3766         if (items) {
3767             for (var i = 0, ii = items.length; i < ii; i++) {
3768                 if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
3769                     this[this.items.length] = this.items[this.items.length] = items[i];
3770                     this.length++;
3771                 }
3772             }
3773         }
3774     },
3775     setproto = Set.prototype;
3776     /*\
3777      * Set.push
3778      [ method ]
3779      **
3780      * Adds each argument to the current set.
3781      = (object) original element
3782     \*/
3783     setproto.push = function () {
3784         var item,
3785             len;
3786         for (var i = 0, ii = arguments.length; i < ii; i++) {
3787             item = arguments[i];
3788             if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
3789                 len = this.items.length;
3790                 this[len] = this.items[len] = item;
3791                 this.length++;
3792             }
3793         }
3794         return this;
3795     };
3796     /*\
3797      * Set.pop
3798      [ method ]
3799      **
3800      * Removes last element and returns it.
3801      = (object) element
3802     \*/
3803     setproto.pop = function () {
3804         this.length && delete this[this.length--];
3805         return this.items.pop();
3806     };
3807     /*\
3808      * Set.forEach
3809      [ method ]
3810      **
3811      * Executes given function for each element in the set.
3812      *
3813      * If function returns `false` it will stop loop running.
3814      **
3815      > Parameters
3816      **
3817      - callback (function) function to run
3818      - thisArg (object) context object for the callback
3819      = (object) Set object
3820     \*/
3821     setproto.forEach = function (callback, thisArg) {
3822         for (var i = 0, ii = this.items.length; i < ii; i++) {
3823             if (callback.call(thisArg, this.items[i]) === false) {
3824                 return this;
3825             }
3826         }
3827         return this;
3828     };
3829     for (var method in elproto) if (elproto[has](method)) {
3830         setproto[method] = (function (methodname) {
3831             return function () {
3832                 var arg = arguments;
3833                 return this.forEach(function (el) {
3834                     el[methodname][apply](el, arg);
3835                 });
3836             };
3837         })(method);
3838     }
3839     setproto.attr = function (name, value) {
3840         if (name && R.is(name, array) && R.is(name[0], "object")) {
3841             for (var j = 0, jj = name.length; j < jj; j++) {
3842                 this.items[j].attr(name[j]);
3843             }
3844         } else {
3845             for (var i = 0, ii = this.items.length; i < ii; i++) {
3846                 this.items[i].attr(name, value);
3847             }
3848         }
3849         return this;
3850     };
3851     setproto.clear = function () {
3852         while (this.length) {
3853             this.pop();
3854         }
3855     };
3856     setproto.animate = function (params, ms, easing, callback) {
3857         (R.is(easing, "function") || !easing) && (callback = easing || null);
3858         var len = this.items.length,
3859             i = len,
3860             item,
3861             set = this,
3862             collector;
3863         if (!len) {
3864             return this;
3865         }
3866         callback && (collector = function () {
3867             !--len && callback.call(set);
3868         });
3869         easing = R.is(easing, string) ? easing : collector;
3870         var anim = params instanceof Animation ? params : R.animation(params, ms, easing, collector);
3871         item = this.items[--i].animate(anim);
3872         while (i--) {
3873             this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
3874         }
3875         return this;
3876     };
3877     setproto.insertAfter = function (el) {
3878         var i = this.items.length;
3879         while (i--) {
3880             this.items[i].insertAfter(el);
3881         }
3882         return this;
3883     };
3884     setproto.getBBox = function () {
3885         var x = [],
3886             y = [],
3887             w = [],
3888             h = [];
3889         for (var i = this.items.length; i--;) if (!this.items[i].removed) {
3890             var box = this.items[i].getBBox();
3891             x.push(box.x);
3892             y.push(box.y);
3893             w.push(box.x + box.width);
3894             h.push(box.y + box.height);
3895         }
3896         x = mmin[apply](0, x);
3897         y = mmin[apply](0, y);
3898         return {
3899             x: x,
3900             y: y,
3901             width: mmax[apply](0, w) - x,
3902             height: mmax[apply](0, h) - y
3903         };
3904     };
3905     setproto.clone = function (s) {
3906         s = new Set;
3907         for (var i = 0, ii = this.items.length; i < ii; i++) {
3908             s.push(this.items[i].clone());
3909         }
3910         return s;
3911     };
3912     setproto.toString = function () {
3913         return "Rapha\xebl\u2018s set";
3914     };
3915
3916     R.registerFont = function (font) {
3917         if (!font.face) {
3918             return font;
3919         }
3920         this.fonts = this.fonts || {};
3921         var fontcopy = {
3922                 w: font.w,
3923                 face: {},
3924                 glyphs: {}
3925             },
3926             family = font.face["font-family"];
3927         for (var prop in font.face) if (font.face[has](prop)) {
3928             fontcopy.face[prop] = font.face[prop];
3929         }
3930         if (this.fonts[family]) {
3931             this.fonts[family].push(fontcopy);
3932         } else {
3933             this.fonts[family] = [fontcopy];
3934         }
3935         if (!font.svg) {
3936             fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
3937             for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
3938                 var path = font.glyphs[glyph];
3939                 fontcopy.glyphs[glyph] = {
3940                     w: path.w,
3941                     k: {},
3942                     d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
3943                             return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
3944                         }) + "z"
3945                 };
3946                 if (path.k) {
3947                     for (var k in path.k) if (path[has](k)) {
3948                         fontcopy.glyphs[glyph].k[k] = path.k[k];
3949                     }
3950                 }
3951             }
3952         }
3953         return font;
3954     };
3955     paperproto.getFont = function (family, weight, style, stretch) {
3956         stretch = stretch || "normal";
3957         style = style || "normal";
3958         weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
3959         if (!R.fonts) {
3960             return;
3961         }
3962         var font = R.fonts[family];
3963         if (!font) {
3964             var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
3965             for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
3966                 if (name.test(fontName)) {
3967                     font = R.fonts[fontName];
3968                     break;
3969                 }
3970             }
3971         }
3972         var thefont;
3973         if (font) {
3974             for (var i = 0, ii = font.length; i < ii; i++) {
3975                 thefont = font[i];
3976                 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
3977                     break;
3978                 }
3979             }
3980         }
3981         return thefont;
3982     };
3983     paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
3984         origin = origin || "middle"; // baseline|middle
3985         letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
3986         var out = this.set(),
3987             letters = Str(string).split(E),
3988             shift = 0,
3989             path = E,
3990             scale;
3991         R.is(font, string) && (font = this.getFont(font));
3992         if (font) {
3993             scale = (size || 16) / font.face["units-per-em"];
3994             var bb = font.face.bbox.split(separator),
3995                 top = +bb[0],
3996                 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
3997             for (var i = 0, ii = letters.length; i < ii; i++) {
3998                 var prev = i && font.glyphs[letters[i - 1]] || {},
3999                     curr = font.glyphs[letters[i]];
4000                 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
4001                 curr && curr.d && out.push(this.path(curr.d).attr({
4002                     fill: "#000",
4003                     stroke: "none",
4004                     transform: [["t", shift * scale, 0]]
4005                 }));
4006             }
4007             out.transform(["...s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]);
4008         }
4009         return out;
4010     };
4011
4012     /*\
4013      * Raphael.format
4014      [ method ]
4015      **
4016      * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument.
4017      **
4018      > Parameters
4019      **
4020      - token (string) string to format
4021      - … (string) rest of arguments will be treated as parameters for replacement
4022      = (string) formated string
4023      > Usage
4024      | var x = 10,
4025      |     y = 20,
4026      |     width = 40,
4027      |     height = 50;
4028      | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4029      | paper.path(Raphael.format("M{1},{2}h{3}v{4}h{5}z", x, y, width, height, -width));
4030     \*/
4031     R.format = function (token, params) {
4032         var args = R.is(params, array) ? [0][concat](params) : arguments;
4033         token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
4034             return args[++i] == null ? E : args[i];
4035         }));
4036         return token || E;
4037     };
4038     /*\
4039      * Raphael.fullfill
4040      [ method ]
4041      **
4042      * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument.
4043      **
4044      > Parameters
4045      **
4046      - token (string) string to format
4047      - json (object) object which properties will be used as a replacement
4048      = (string) formated string
4049      > Usage
4050      | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z"
4051      | paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", {
4052      |     x: 10,
4053      |     y: 20,
4054      |     dim: {
4055      |         width: 40,
4056      |         height: 50,
4057      |         "negative width": -40
4058      |     }
4059      | }));
4060     \*/
4061     R.fullfill = (function () {
4062         var tokenRegex = /\{([^\}]+)\}/g,
4063             objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties
4064             replacer = function (all, key, obj) {
4065                 var res = obj;
4066                 key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) {
4067                     name = name || quotedName;
4068                     if (res) {
4069                         if (name in res) {
4070                             res = res[name];
4071                         }
4072                         typeof res == "function" && isFunc && (res = res());
4073                     }
4074                 });
4075                 res = (res == null || res == obj ? all : res) + "";
4076                 return res;
4077             };
4078         return function (str, obj) {
4079             return String(str).replace(tokenRegex, function (all, key) {
4080                 return replacer(all, key, obj);
4081             });
4082         };
4083     })();
4084     /*\
4085      * Raphael.ninja
4086      [ method ]
4087      **
4088      * 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.
4089      * Beware, that in this case plugins could stop working, because they are depending on global variable existance.
4090      **
4091      = (object) Raphael object
4092      > Usage
4093      | (function (local_raphael) {
4094      |     var paper = local_raphael(10, 10, 320, 200);
4095      |     …
4096      | })(Raphael.ninja());
4097     \*/
4098     R.ninja = function () {
4099         oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
4100         return R;
4101     };
4102     /*\
4103      * Raphael.st
4104      [ property (object) ]
4105      **
4106      * You can add your own method to elements and sets. It is wise to add a set method for each element method
4107      * you added, so you will be able to call the same method on sets too.
4108      **
4109      * See also @Raphael.el.
4110      > Usage
4111      | Raphael.el.red = function () {
4112      |     this.attr({fill: "#f00"});
4113      | };
4114      | Raphael.st.red = function () {
4115      |     this.forEach(function () {
4116      |         this.red();
4117      |     });
4118      | };
4119      | // then use it
4120      | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
4121     \*/
4122     R.st = setproto;
4123     // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
4124     (function (doc, loaded, f) {
4125         if (doc.readyState == null && doc.addEventListener){
4126             doc.addEventListener(loaded, f = function () {
4127                 doc.removeEventListener(loaded, f, false);
4128                 doc.readyState = "complete";
4129             }, false);
4130             doc.readyState = "loading";
4131         }
4132         function isLoaded() {
4133             (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("DOMload");
4134         }
4135         isLoaded();
4136     })(document, "DOMContentLoaded");
4137
4138     oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
4139     
4140     eve.on("DOMload", function () {
4141         loaded = true;
4142     });
4143 })();