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