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