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