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