Fixed bug for HSL/HSB
[raphael] / raphael.js
1 // ┌─────────────────────────────────────────────────────────────────────┐ \\
2 // │ Raphaël 2 - JavaScript Vector Library                               │ \\
3 // ├─────────────────────────────────────────────────────────────────────┤ \\
4 // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com)   │ \\
5 // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com)             │ \\
6 // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\
7 // └─────────────────────────────────────────────────────────────────────┘ \\
8 (function () {
9     /*\
10      * Raphael
11      [ method ]
12      **
13      * Creates a canvas object on which to draw.
14      * You must do this first, as all future calls to drawing methods
15      * from this instance will be bound to this canvas.
16      > Parameters
17      **
18      - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface
19      - width (number)
20      - height (number)
21      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
22      * or
23      - x (number)
24      - y (number)
25      - width (number)
26      - height (number)
27      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
28      * or
29      - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>})
30      - callback (function) #optional callback function which is going to be executed in the context of newly created paper
31      * or
32      - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`.
33      = (object) @Paper
34      > Usage
35      | // Each of the following examples create a canvas
36      | // that is 320px wide by 200px high.
37      | // Canvas is created at the viewport’s 10,50 coordinate.
38      | var paper = Raphael(10, 50, 320, 200);
39      | // Canvas is created at the top left corner of the #notepad element
40      | // (or its top right corner in dir="rtl" elements)
41      | var paper = Raphael(document.getElementById("notepad"), 320, 200);
42      | // Same as above
43      | var paper = Raphael("notepad", 320, 200);
44      | // Image dump
45      | var set = Raphael(["notepad", 320, 200, {
46      |     type: "rect",
47      |     x: 10,
48      |     y: 10,
49      |     width: 25,
50      |     height: 25,
51      |     stroke: "#f00"
52      | }, {
53      |     type: "text",
54      |     x: 30,
55      |     y: 40,
56      |     text: "Dump"
57      | }]);
58     \*/
59     function R(first) {
60         if (R.is(first, "function")) {
61             return loaded ? first() : eve.on("DOMload", first);
62         } else if (R.is(first, array)) {
63             var a = first,
64                 cnv = create[apply](R, a.splice(0, 3 + R.is(a[0], nu))),
65                 res = cnv.set(),
66                 i = 0,
67                 ii = a.length,
68                 j;
69             for (; i < ii; i++) {
70                 j = a[i] || {};
71                 elements[has](j.type) && res.push(cnv[j.type]().attr(j));
72             }
73             return res;
74         } else {
75             var args = Array.prototype.slice.call(arguments, 0);
76             if (R.is(args[args.length - 1], "function")) {
77                 var f = args.pop();
78                 return loaded ? f.call(create[apply](R, args)) : eve.on("DOMload", function () {
79                     f.call(create[apply](R, args));
80                 });
81             } else {
82                 return create[apply](R, arguments);
83             }
84         }
85     }
86     R.version = "2.0.0";
87     var loaded,
88         separator = /[, ]+/,
89         elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1},
90         formatrg = /\{(\d+)\}/g,
91         proto = "prototype",
92         has = "hasOwnProperty",
93         g = {
94             doc: document,
95             win: window
96         },
97         oldRaphael = {
98             was: Object.prototype[has].call(g.win, "Raphael"),
99             is: g.win.Raphael
100         },
101         Paper = function () {},
102         paperproto,
103         appendChild = "appendChild",
104         apply = "apply",
105         concat = "concat",
106         supportsTouch = "createTouch" in g.doc,
107         E = "",
108         S = " ",
109         Str = String,
110         split = "split",
111         events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend orientationchange touchcancel gesturestart gesturechange gestureend".split(S),
112         touchMap = {
113             mousedown: "touchstart",
114             mousemove: "touchmove",
115             mouseup: "touchend"
116         },
117         lowerCase = Str.prototype.toLowerCase,
118         math = Math,
119         mmax = math.max,
120         mmin = math.min,
121         abs = math.abs,
122         pow = math.pow,
123         PI = math.PI,
124         nu = "number",
125         string = "string",
126         array = "array",
127         toString = "toString",
128         fillString = "fill",
129         objectToString = Object.prototype.toString,
130         paper = {},
131         push = "push",
132         ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
133         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,
134         isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1},
135         bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
136         round = math.round,
137         setAttribute = "setAttribute",
138         toFloat = parseFloat,
139         toInt = parseInt,
140         ms = " progid:DXImageTransform.Microsoft",
141         upperCase = Str.prototype.toUpperCase,
142         availableAttrs = {"arrow-end": "none", "arrow-start": "none", blur: 0, "clip-rect": "0 0 1e9 1e9", cursor: "default", cx: 0, cy: 0, fill: "#fff", "fill-opacity": 1, font: '10px "Arial"', "font-family": '"Arial"', "font-size": "10", "font-style": "normal", "font-weight": 400, gradient: 0, height: 0, href: "http://raphaeljs.com/", opacity: 1, path: "M0,0", r: 0, rx: 0, ry: 0, src: "", stroke: "#000", "stroke-dasharray": "", "stroke-linecap": "butt", "stroke-linejoin": "butt", "stroke-miterlimit": 0, "stroke-opacity": 1, "stroke-width": 1, target: "_blank", "text-anchor": "middle", title: "Raphael", transform: "", width: 0, x: 0, y: 0},
143         availableAnimAttrs = {blur: nu, "clip-rect": "csv", cx: nu, cy: nu, fill: "colour", "fill-opacity": nu, "font-size": nu, height: nu, opacity: nu, path: "path", r: nu, rx: nu, ry: nu, stroke: "colour", "stroke-opacity": nu, "stroke-width": nu, transform: "transform", width: nu, x: nu, y: nu},
144         commaSpaces = /\s*,\s*/,
145         hsrg = {hs: 1, rg: 1},
146         p2s = /,?([achlmqrstvxz]),?/gi,
147         pathCommand = /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
148         tCommand = /([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?\s*,?\s*)+)/ig,
149         pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)\s*,?\s*/ig,
150         radial_gradient = /^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,
151         sortByKey = function (a, b) {
152             return a.key - b.key;
153         },
154         sortByNumber = function (a, b) {
155             return a - b;
156         },
157         fun = function () {},
158         pipe = function (x) {
159             return x;
160         },
161         rectPath = function (x, y, w, h, r) {
162             if (r) {
163                 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"]];
164             }
165             return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
166         },
167         ellipsePath = function (x, y, rx, ry) {
168             if (ry == null) {
169                 ry = rx;
170             }
171             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"]];
172         },
173         getPath = {
174             path: function (el) {
175                 return el.attr("path");
176             },
177             circle: function (el) {
178                 var a = el.attrs;
179                 return ellipsePath(a.cx, a.cy, a.r);
180             },
181             ellipse: function (el) {
182                 var a = el.attrs;
183                 return ellipsePath(a.cx, a.cy, a.rx, a.ry);
184             },
185             rect: function (el) {
186                 var a = el.attrs;
187                 return rectPath(a.x, a.y, a.width, a.height, a.r);
188             },
189             image: function (el) {
190                 var a = el.attrs;
191                 return rectPath(a.x, a.y, a.width, a.height);
192             },
193             text: function (el) {
194                 var bbox = el._getBBox();
195                 return rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
196             }
197         },
198         mapPath = function (path, matrix) {
199             if (!matrix) {
200                 return path;
201             }
202             var x, y, i, j, pathi;
203             path = path2curve(path);
204             for (i = 0, ii = path.length; i < ii; i++) {
205                 pathi = path[i];
206                 for (j = 1, jj = pathi.length; j < jj; j += 2) {
207                     x = matrix.x(pathi[j], pathi[j + 1]);
208                     y = matrix.y(pathi[j], pathi[j + 1]);
209                     pathi[j] = x;
210                     pathi[j + 1] = y;
211                 }
212             }
213             return path;
214         };
215
216     /*\
217      * Raphael.type
218      [ property (string) ]
219      **
220      * Can be “SVG”, “VML” or empty, depending on browser support.
221     \*/
222     R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML");
223     if (R.type == "VML") {
224         var d = g.doc.createElement("div"),
225             b;
226         d.innerHTML = '<v:shape adj="1"/>';
227         b = d.firstChild;
228         b.style.behavior = "url(#default#VML)";
229         if (!(b && typeof b.adj == "object")) {
230             return (R.type = E);
231         }
232         d = null;
233     }
234     /*\
235      * Raphael.svg
236      [ property (boolean) ]
237      **
238      * `true` if browser supports SVG.
239     \*/
240     /*\
241      * Raphael.vml
242      [ property (boolean) ]
243      **
244      * `true` if browser supports VML.
245     \*/
246     R.svg = !(R.vml = R.type == "VML");
247     paperproto = Paper.prototype = R.prototype;
248     /*\
249      * Paper.customAttributes
250      [ property (object) ]
251      **
252      * If you have a set of attributes that you would like to represent
253      * as a function of some number you can do it easily with custom attributes:
254      > Usage
255      | paper.customAttributes.hue = function (num) {
256      |     num = num % 1;
257      |     return {fill: "hsb(" + num + ", .75, 1)"};
258      | };
259      | // Custom attribute “hue” will change fill
260      | // to be given hue with fixed saturation and brightness.
261      | // Now you can use it like this:
262      | var c = paper.circle(10, 10, 10).attr({hue: .45});
263      | // or even like this:
264      | c.animate({hue: 1}, 1e3);
265      | 
266      | // You could also create custom attribute
267      | // with multiple parameters:
268      | paper.customAttributes.hsb = function (h, s, b) {
269      |     return {fill: "hsb(" + [h, s, b].join(",") + ")"};
270      | };
271      | c.attr({hsb: ".5 .8 1"});
272      | c.animate({hsb: "1 0 .5"}, 1e3);
273     \*/
274     paperproto.customAttributes = {};
275     R._id = 0;
276     R._oid = 0;
277     /*\
278      * Raphael.fn
279      [ property (object) ]
280      **
281      * You can add your own method to the canvas. For example if you want to draw a pie chart,
282      * you can create your own pie chart function and ship it as a Raphaël plugin. To do this
283      * you need to extend the `Raphael.fn` object. Please note that you can create your own namespaces
284      * inside the `fn` object — methods will be run in the context of canvas anyway. You should alter
285      * the `fn` object before a Raphaël instance is created, otherwise it will take no effect.
286      > Usage
287      | Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
288      |     return this.path( ... );
289      | };
290      | // or create namespace
291      | Raphael.fn.mystuff = {
292      |     arrow: function () {…},
293      |     star: function () {…},
294      |     // etc…
295      | };
296      | var paper = Raphael(10, 10, 630, 480);
297      | // then use it
298      | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
299      | paper.mystuff.arrow();
300      | paper.mystuff.star();
301     \*/
302     R.fn = {};
303     /*\
304      * Raphael.is
305      [ method ]
306      **
307      * Handfull replacement for `typeof` operator.
308      > Parameters
309      - o (…) any object or primitive
310      - type (string) name of the type, i.e. “string”, “function”, “number”, etc.
311      = (boolean) is given value is of given type
312     \*/
313     R.is = function (o, type) {
314         type = lowerCase.call(type);
315         if (type == "finite") {
316             return !isnan[has](+o);
317         }
318         return  (type == "null" && o === null) ||
319                 (type == typeof o) ||
320                 (type == "object" && o === Object(o)) ||
321                 (type == "array" && Array.isArray && Array.isArray(o)) ||
322                 objectToString.call(o).slice(8, -1).toLowerCase() == type;
323     };
324     /*\
325      * Raphael.angle
326      [ method ]
327      **
328      * Returns angle between two or three points
329      > Parameters
330      - x1 (number) x coord of first point
331      - y1 (number) y coord of first point
332      - x2 (number) x coord of second point
333      - y2 (number) y coord of second point
334      - x3 (number) #optional x coord of third point
335      - y3 (number) #optional y coord of third point
336      = (number) angle in degrees.
337     \*/
338     R.angle = function (x1, y1, x2, y2, x3, y3) {
339         if (x3 == null) {
340             var x = x1 - x2,
341                 y = y1 - y2;
342             if (!x && !y) {
343                 return 0;
344             }
345             return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360;
346         } else {
347             return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3);
348         }
349     };
350     /*\
351      * Raphael.rad
352      [ method ]
353      **
354      * Transform angle to radians
355      > Parameters
356      - deg (number) angle in degrees
357      = (number) angle in radians.
358     \*/
359     R.rad = function (deg) {
360         return deg % 360 * PI / 180;
361     };
362     /*\
363      * Raphael.deg
364      [ method ]
365      **
366      * Transform angle to degrees
367      > Parameters
368      - deg (number) angle in radians
369      = (number) angle in degrees.
370     \*/
371     R.deg = function (rad) {
372         return rad * 180 / PI % 360;
373     };
374     /*\
375      * Raphael.snapTo
376      [ method ]
377      **
378      * Snaps given value to given grid.
379      > Parameters
380      - values (array|number) given array of values or step of the grid
381      - value (number) value to adjust
382      - tolerance (number) #optional tolerance for snapping. Default is `10`.
383      = (number) adjusted value.
384     \*/
385     R.snapTo = function (values, value, tolerance) {
386         tolerance = R.is(tolerance, "finite") ? tolerance : 10;
387         if (R.is(values, array)) {
388             var i = values.length;
389             while (i--) if (abs(values[i] - value) <= tolerance) {
390                 return values[i];
391             }
392         } else {
393             values = +values;
394             var rem = value % values;
395             if (rem < tolerance) {
396                 return value - rem;
397             }
398             if (rem > values - tolerance) {
399                 return value - rem + values;
400             }
401         }
402         return value;
403     };
404     
405     var createUUID = (function (uuidRegEx, uuidReplacer) {
406         return function () {
407             return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
408         };
409     })(/[xy]/g, function (c) {
410         var r = math.random() * 16 | 0,
411             v = c == "x" ? r : (r & 3 | 8);
412         return v.toString(16);
413     });
414
415     /*\
416      * Raphael.setWindow
417      [ method ]
418      **
419      * Used when you need to draw in `&lt;iframe>`. Switched window to the iframe one.
420      > Parameters
421      - newwin (window) new window object
422     \*/
423     R.setWindow = function (newwin) {
424         eve("setWindow", R, g.win, newwin);
425         g.win = newwin;
426         g.doc = g.win.document;
427         if (initWin) {
428             initWin(g.win);
429         }
430     };
431     // colour utilities
432     var toHex = function (color) {
433         if (R.vml) {
434             // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/
435             var trim = /^\s+|\s+$/g;
436             var bod;
437             try {
438                 var docum = new ActiveXObject("htmlfile");
439                 docum.write("<body>");
440                 docum.close();
441                 bod = docum.body;
442             } catch(e) {
443                 bod = createPopup().document.body;
444             }
445             var range = bod.createTextRange();
446             toHex = cacher(function (color) {
447                 try {
448                     bod.style.color = Str(color).replace(trim, E);
449                     var value = range.queryCommandValue("ForeColor");
450                     value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16);
451                     return "#" + ("000000" + value.toString(16)).slice(-6);
452                 } catch(e) {
453                     return "none";
454                 }
455             });
456         } else {
457             var i = g.doc.createElement("i");
458             i.title = "Rapha\xebl Colour Picker";
459             i.style.display = "none";
460             g.doc.body.appendChild(i);
461             toHex = cacher(function (color) {
462                 i.style.color = color;
463                 return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color");
464             });
465         }
466         return toHex(color);
467     },
468     hsbtoString = function () {
469         return "hsb(" + [this.h, this.s, this.b] + ")";
470     },
471     hsltoString = function () {
472         return "hsl(" + [this.h, this.s, this.l] + ")";
473     },
474     rgbtoString = function () {
475         return this.hex;
476     },
477     prepareRGB = function (r, g, b) {
478         if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
479             b = r.b;
480             g = r.g;
481             r = r.r;
482         }
483         if (g == null && R.is(r, string)) {
484             var clr = R.getRGB(r);
485             r = clr.r;
486             g = clr.g;
487             b = clr.b;
488         }
489         if (r > 1 || g > 1 || b > 1) {
490             r /= 255;
491             g /= 255;
492             b /= 255;
493         }
494         
495         return [r, g, b];
496     },
497     packageRGB = function (r, g, b, o) {
498         r *= 255;
499         g *= 255;
500         b *= 255;
501         var rgb = {
502             r: r,
503             g: g,
504             b: b,
505             hex: R.rgb(r, g, b),
506             toString: rgbtoString
507         };
508         R.is(o, "finite") && (rgb.opacity = o);
509         return rgb;
510     };
511     
512     /*\
513      * Raphael.color
514      [ method ]
515      **
516      * Parses the color string and returns object with all values for the given color.
517      > Parameters
518      - clr (string) color string in one of the supported formasts (see @Raphael.getRGB)
519      = (object) Combined RGB & HSB object in format:
520      o {
521      o     r (number) red,
522      o     g (number) green,
523      o     b (number) blue,
524      o     hex (string) color in HTML/CSS format: #••••••,
525      o     error (boolean) `true` if string can’t be parsed,
526      o     h (number) hue,
527      o     s (number) saturation,
528      o     v (number) value (brightness),
529      o     l (number) lightness
530      o }
531     \*/
532     R.color = function (clr) {
533         var rgb;
534         if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
535             rgb = R.hsb2rgb(clr);
536             clr.r = rgb.r;
537             clr.g = rgb.g;
538             clr.b = rgb.b;
539             clr.hex = rgb.hex;
540         } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
541             rgb = R.hsl2rgb(clr);
542             clr.r = rgb.r;
543             clr.g = rgb.g;
544             clr.b = rgb.b;
545             clr.hex = rgb.hex;
546         } else {
547             if (R.is(clr, "string")) {
548                 clr = R.getRGB(clr);
549             }
550             if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
551                 rgb = R.rgb2hsl(clr);
552                 clr.h = rgb.h;
553                 clr.s = rgb.s;
554                 clr.l = rgb.l;
555                 rgb = R.rgb2hsb(clr);
556                 clr.v = rgb.b;
557             } else {
558                 clr = {hex: "none"};
559                 crl.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1;
560             }
561         }
562         clr.toString = rgbtoString;
563         return clr;
564     };
565     /*\
566      * Raphael.hsb2rgb
567      [ method ]
568      **
569      * Converts HSB values to RGB object.
570      > Parameters
571      - h (number) hue
572      - s (number) saturation
573      - v (number) value or brightness
574      = (object) RGB object in format:
575      o {
576      o     r (number) red,
577      o     g (number) green,
578      o     b (number) blue,
579      o     hex (string) color in HTML/CSS format: #••••••
580      o }
581     \*/
582     R.hsb2rgb = function (h, s, v, o) {
583         if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
584             v = h.b;
585             s = h.s;
586             h = h.h;
587             o = h.o;
588         }
589         h *= 360;
590         var R, G, B, X, C;
591         h = (h % 360) / 60;
592         C = v * s;
593         X = C * (1 - abs(h % 2 - 1));
594         R = G = B = v - C;
595
596         h = ~~h;
597         R += [C, X, 0, 0, X, C][h];
598         G += [X, C, C, X, 0, 0][h];
599         B += [0, 0, X, C, C, X][h];
600         return packageRGB(R, G, B, o);
601     };
602     /*\
603      * Raphael.hsl2rgb
604      [ method ]
605      **
606      * Converts HSL values to RGB object.
607      > Parameters
608      - h (number) hue
609      - s (number) saturation
610      - l (number) luminosity
611      = (object) RGB object in format:
612      o {
613      o     r (number) red,
614      o     g (number) green,
615      o     b (number) blue,
616      o     hex (string) color in HTML/CSS format: #••••••
617      o }
618     \*/
619     R.hsl2rgb = function (h, s, l, o) {
620         if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
621             l = h.l;
622             s = h.s;
623             h = h.h;
624         }
625         if (h > 1 || s > 1 || l > 1) {
626             h /= 360;
627             s /= 100;
628             l /= 100;
629         }
630         h *= 360;
631         var R, G, B, X, C;
632         h = (h % 360) / 60;
633         C = 2 * s * (l < .5 ? l : 1 - l);
634         X = C * (1 - abs(h % 2 - 1));
635         R = G = B = l - C / 2;
636
637         h = ~~h;
638         R += [C, X, 0, 0, X, C][h];
639         G += [X, C, C, X, 0, 0][h];
640         B += [0, 0, X, C, C, X][h];
641         return packageRGB(R, G, B, o);
642     };
643     /*\
644      * Raphael.rgb2hsb
645      [ method ]
646      **
647      * Converts RGB values to HSB object.
648      > Parameters
649      - r (number) red
650      - g (number) green
651      - b (number) blue
652      = (object) HSB object in format:
653      o {
654      o     h (number) hue
655      o     s (number) saturation
656      o     b (number) brightness
657      o }
658     \*/
659     R.rgb2hsb = function (r, g, b) {
660         b = prepareRGB(r, g, b);
661         r = b[0];
662         g = b[1];
663         b = b[2];
664
665         var H, S, V, C;
666         V = mmax(r, g, b);
667         C = V - mmin(r, g, b);
668         H = (C == 0 ? null :
669              V == r ? (g - b) / C :
670              V == g ? (b - r) / C + 2 :
671                       (r - g) / C + 4
672             );
673         H = ((H + 360) % 6) * 60 / 360;
674         S = C == 0 ? 0 : C / V;
675         return {h: H, s: S, b: V, toString: hsbtoString};
676     };
677     /*\
678      * Raphael.rgb2hsl
679      [ method ]
680      **
681      * Converts RGB values to HSL object.
682      > Parameters
683      - r (number) red
684      - g (number) green
685      - b (number) blue
686      = (object) HSL object in format:
687      o {
688      o     h (number) hue
689      o     s (number) saturation
690      o     l (number) luminosity
691      o }
692     \*/
693     R.rgb2hsl = function (r, g, b) {
694         b = prepareRGB(r, g, b);
695         r = b[0];
696         g = b[1];
697         b = b[2];
698
699         var H, S, L, M, m, C;
700         M = mmax(r, g, b);
701         m = mmin(r, g, b);
702         C = M - m;
703         H = (C == 0 ? null :
704              M == r ? (g - b) / C :
705              M == g ? (b - r) / C + 2 :
706                       (r - g) / C + 4);
707         H = ((H + 360) % 6) * 60 / 360;
708         L = (M + m) / 2;
709         S = (C == 0 ? 0 :
710              L < .5 ? C / (2 * L) :
711                       C / (2 - 2 * L));
712         return {h: H, s: S, l: L, toString: hsltoString};
713     };
714     R._path2string = function () {
715         return this.join(",").replace(p2s, "$1");
716     };
717     function repush(array, item) {
718         for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) {
719             return array.push(array.splice(i, 1)[0]);
720         }
721     }
722     function cacher(f, scope, postprocessor) {
723         function newf() {
724             var arg = Array.prototype.slice.call(arguments, 0),
725                 args = arg.join("\u2400"),
726                 cache = newf.cache = newf.cache || {},
727                 count = newf.count = newf.count || [];
728             if (cache[has](args)) {
729                 repush(count, args);
730                 return postprocessor ? postprocessor(cache[args]) : cache[args];
731             }
732             count.length >= 1e3 && delete cache[count.shift()];
733             count.push(args);
734             cache[args] = f[apply](scope, arg);
735             return postprocessor ? postprocessor(cache[args]) : cache[args];
736         }
737         return newf;
738     }
739
740     function preload(src, f) {
741         var img = g.doc.createElement("img");
742         img.style.cssText = "position:absolute;left:-9999em;top-9999em";
743         img.onload = function () {
744             f.call(this);
745             this.onload = null;
746             g.doc.body.removeChild(this);
747         };
748         img.onerror = function () {
749             g.doc.body.removeChild(this);
750         };
751         g.doc.body.appendChild(img);
752         img.src = src;
753     }
754     
755     function clrToString() {
756         return this.hex;
757     }
758
759     /*\
760      * Raphael.getRGB
761      [ method ]
762      **
763      * Parses colour string as RGB object
764      > Parameters
765      - colour (string) colour string in one of formats:
766      # <ul>
767      #     <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
768      #     <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
769      #     <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
770      #     <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200,&nbsp;100,&nbsp;0)</code>”)</li>
771      #     <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>”)</li>
772      #     <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>”)</li>
773      #     <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
774      #     <li>hsl(•••, •••, •••) — same as hsb</li>
775      #     <li>hsl(•••%, •••%, •••%) — same as hsb</li>
776      # </ul>
777      = (object) RGB object in format:
778      o {
779      o     r (number) red,
780      o     g (number) green,
781      o     b (number) blue
782      o     hex (string) color in HTML/CSS format: #••••••,
783      o     error (boolean) true if string can’t be parsed
784      o }
785     \*/
786     R.getRGB = cacher(function (colour) {
787         if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
788             return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
789         }
790         if (colour == "none") {
791             return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString};
792         }
793         !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
794         var res,
795             red,
796             green,
797             blue,
798             opacity,
799             t,
800             values,
801             rgb = colour.match(colourRegExp);
802         if (rgb) {
803             if (rgb[2]) {
804                 blue = toInt(rgb[2].substring(5), 16);
805                 green = toInt(rgb[2].substring(3, 5), 16);
806                 red = toInt(rgb[2].substring(1, 3), 16);
807             }
808             if (rgb[3]) {
809                 blue = toInt((t = rgb[3].charAt(3)) + t, 16);
810                 green = toInt((t = rgb[3].charAt(2)) + t, 16);
811                 red = toInt((t = rgb[3].charAt(1)) + t, 16);
812             }
813             if (rgb[4]) {
814                 values = rgb[4].split(commaSpaces);
815                 red = toFloat(values[0]);
816                 values[0].slice(-1) == "%" && (red *= 2.55);
817                 green = toFloat(values[1]);
818                 values[1].slice(-1) == "%" && (green *= 2.55);
819                 blue = toFloat(values[2]);
820                 values[2].slice(-1) == "%" && (blue *= 2.55);
821                 rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
822                 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
823             }
824             if (rgb[5]) {
825                 values = rgb[5].split(commaSpaces);
826                 red = toFloat(values[0]);
827                 values[0].slice(-1) == "%" && (red *= 2.55);
828                 green = toFloat(values[1]);
829                 values[1].slice(-1) == "%" && (green *= 2.55);
830                 blue = toFloat(values[2]);
831                 values[2].slice(-1) == "%" && (blue *= 2.55);
832                 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
833                 rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
834                 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
835                 return R.hsb2rgb(red, green, blue, opacity);
836             }
837             if (rgb[6]) {
838                 values = rgb[6].split(commaSpaces);
839                 red = toFloat(values[0]);
840                 values[0].slice(-1) == "%" && (red *= 2.55);
841                 green = toFloat(values[1]);
842                 values[1].slice(-1) == "%" && (green *= 2.55);
843                 blue = toFloat(values[2]);
844                 values[2].slice(-1) == "%" && (blue *= 2.55);
845                 (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
846                 rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
847                 values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
848                 return R.hsl2rgb(red, green, blue, opacity);
849             }
850             rgb = {r: red, g: green, b: blue, toString: clrToString};
851             rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
852             R.is(opacity, "finite") && (rgb.opacity = opacity);
853             return rgb;
854         }
855         return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString};
856     }, R);
857     /*\
858      * Raphael.hsb
859      [ method ]
860      **
861      * Converts HSB values to hex representation of the colour.
862      > Parameters
863      - h (number) hue
864      - s (number) saturation
865      - b (number) value or brightness
866      = (string) hex representation of the colour.
867     \*/
868     R.hsb = cacher(function (h, s, b) {
869         return R.hsb2rgb(h, s, b).hex;
870     });
871     /*\
872      * Raphael.hsl
873      [ method ]
874      **
875      * Converts HSL values to hex representation of the colour.
876      > Parameters
877      - h (number) hue
878      - s (number) saturation
879      - l (number) luminosity
880      = (string) hex representation of the colour.
881     \*/
882     R.hsl = cacher(function (h, s, l) {
883         return R.hsl2rgb(h, s, l).hex;
884     });
885     /*\
886      * Raphael.rgb
887      [ method ]
888      **
889      * Converts RGB values to hex representation of the colour.
890      > Parameters
891      - r (number) red
892      - g (number) green
893      - b (number) blue
894      = (string) hex representation of the colour.
895     \*/
896     R.rgb = cacher(function (r, g, b) {
897         return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1);
898     });
899     /*\
900      * Raphael.getColor
901      [ method ]
902      **
903      * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset
904      > Parameters
905      - value (number) #optional brightness, default is `0.75`
906      = (string) hex representation of the colour.
907     \*/
908     R.getColor = function (value) {
909         var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75},
910             rgb = this.hsb2rgb(start.h, start.s, start.b);
911         start.h += .075;
912         if (start.h > 1) {
913             start.h = 0;
914             start.s -= .2;
915             start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b});
916         }
917         return rgb.hex;
918     };
919     /*\
920      * Raphael.getColor.reset
921      [ method ]
922      **
923      * Resets spectrum position for @Raphael.getColor back to red.
924     \*/
925     R.getColor.reset = function () {
926         delete this.start;
927     };
928
929     /*\
930      * Raphael.parsePathString
931      [ method ]
932      **
933      * Utility method
934      **
935      * Parses given path string into an array of arrays of path segments.
936      > Parameters
937      - pathString (string|array) path string or array of segments (in the last case it will be returned straight away)
938      = (array) array of segments.
939     \*/
940     R.parsePathString = cacher(function (pathString) {
941         if (!pathString) {
942             return null;
943         }
944         var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0},
945             data = [];
946         if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption
947             data = pathClone(pathString);
948         }
949         if (!data.length) {
950             Str(pathString).replace(pathCommand, function (a, b, c) {
951                 var params = [],
952                     name = lowerCase.call(b);
953                 c.replace(pathValues, function (a, b) {
954                     b && params.push(+b);
955                 });
956                 if (name == "m" && params.length > 2) {
957                     data.push([b][concat](params.splice(0, 2)));
958                     name = "l";
959                     b = b == "m" ? "l" : "L";
960                 }
961                 while (params.length >= paramCounts[name]) {
962                     data.push([b][concat](params.splice(0, paramCounts[name])));
963                     if (!paramCounts[name]) {
964                         break;
965                     }
966                 }
967             });
968         }
969         data.toString = R._path2string;
970         return data;
971     });
972     /*\
973      * Raphael.parseTransformString
974      [ method ]
975      **
976      * Utility method
977      **
978      * Parses given path string into an array of transformations.
979      > Parameters
980      - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away)
981      = (array) array of transformations.
982     \*/
983     R.parseTransformString = cacher(function (TString) {
984         if (!TString) {
985             return null;
986         }
987         var paramCounts = {r: 3, s: 4, t: 2, m: 6},
988             data = [];
989         if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption
990             data = pathClone(TString);
991         }
992         if (!data.length) {
993             Str(TString).replace(tCommand, function (a, b, c) {
994                 var params = [],
995                     name = lowerCase.call(b);
996                 c.replace(pathValues, function (a, b) {
997                     b && params.push(+b);
998                 });
999                 data.push([name][concat](params));
1000             });
1001         }
1002         data.toString = R._path2string;
1003         return data;
1004     });
1005     /*\
1006      * Raphael.findDotsAtSegment
1007      [ method ]
1008      **
1009      * Utility method
1010      **
1011      * Find dot coordinates on the given cubic bezier curve at the given t.
1012      > Parameters
1013      - p1x (number) x of the first point of the curve
1014      - p1y (number) y of the first point of the curve
1015      - c1x (number) x of the first anchor of the curve
1016      - c1y (number) y of the first anchor of the curve
1017      - c2x (number) x of the second anchor of the curve
1018      - c2y (number) y of the second anchor of the curve
1019      - p2x (number) x of the second point of the curve
1020      - p2y (number) y of the second point of the curve
1021      - t (number) position on the curve (0..1)
1022      = (object) point information in format:
1023      o {
1024      o     x: (number) x coordinate of the point
1025      o     y: (number) y coordinate of the point
1026      o     m: {
1027      o         x: (number) x coordinate of the left anchor
1028      o         y: (number) y coordinate of the left anchor
1029      o     }
1030      o     n: {
1031      o         x: (number) x coordinate of the right anchor
1032      o         y: (number) y coordinate of the right anchor
1033      o     }
1034      o     start: {
1035      o         x: (number) x coordinate of the start of the curve
1036      o         y: (number) y coordinate of the start of the curve
1037      o     }
1038      o     end: {
1039      o         x: (number) x coordinate of the end of the curve
1040      o         y: (number) y coordinate of the end of the curve
1041      o     }
1042      o     alpha: (number) angle of the curve derivative at the point
1043      o }
1044     \*/
1045     R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1046         var t1 = 1 - t,
1047             x = pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1048             y = pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y,
1049             mx = p1x + 2 * t * (c1x - p1x) + t * t * (c2x - 2 * c1x + p1x),
1050             my = p1y + 2 * t * (c1y - p1y) + t * t * (c2y - 2 * c1y + p1y),
1051             nx = c1x + 2 * t * (c2x - c1x) + t * t * (p2x - 2 * c2x + c1x),
1052             ny = c1y + 2 * t * (c2y - c1y) + t * t * (p2y - 2 * c2y + c1y),
1053             ax = (1 - t) * p1x + t * c1x,
1054             ay = (1 - t) * p1y + t * c1y,
1055             cx = (1 - t) * c2x + t * p2x,
1056             cy = (1 - t) * c2y + t * p2y,
1057             alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI);
1058         (mx > nx || my < ny) && (alpha += 180);
1059         return {x: x, y: y, m: {x: mx, y: my}, n: {x: nx, y: ny}, start: {x: ax, y: ay}, end: {x: cx, y: cy}, alpha: alpha};
1060     };
1061     var pathDimensions = cacher(function (path) {
1062         if (!path) {
1063             return {x: 0, y: 0, width: 0, height: 0};
1064         }
1065         path = path2curve(path);
1066         var x = 0, 
1067             y = 0,
1068             X = [],
1069             Y = [],
1070             p;
1071         for (var i = 0, ii = path.length; i < ii; i++) {
1072             p = path[i];
1073             if (p[0] == "M") {
1074                 x = p[1];
1075                 y = p[2];
1076                 X.push(x);
1077                 Y.push(y);
1078             } else {
1079                 var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
1080                 X = X[concat](dim.min.x, dim.max.x);
1081                 Y = Y[concat](dim.min.y, dim.max.y);
1082                 x = p[5];
1083                 y = p[6];
1084             }
1085         }
1086         var xmin = mmin[apply](0, X),
1087             ymin = mmin[apply](0, Y);
1088         return {
1089             x: xmin,
1090             y: ymin,
1091             width: mmax[apply](0, X) - xmin,
1092             height: mmax[apply](0, Y) - ymin
1093         };
1094     }, null, function (o) {
1095         return {
1096             x: o.x,
1097             y: o.y,
1098             width: o.width,
1099             height: o.height
1100         };
1101     }),
1102         pathClone = function (pathArray) {
1103             var res = [];
1104             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1105                 pathArray = R.parsePathString(pathArray);
1106             }
1107             for (var i = 0, ii = pathArray.length; i < ii; i++) {
1108                 res[i] = [];
1109                 for (var j = 0, jj = pathArray[i].length; j < jj; j++) {
1110                     res[i][j] = pathArray[i][j];
1111                 }
1112             }
1113             res.toString = R._path2string;
1114             return res;
1115         },
1116         pathToRelative = cacher(function (pathArray) {
1117             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1118                 pathArray = R.parsePathString(pathArray);
1119             }
1120             var res = [],
1121                 x = 0,
1122                 y = 0,
1123                 mx = 0,
1124                 my = 0,
1125                 start = 0;
1126             if (pathArray[0][0] == "M") {
1127                 x = pathArray[0][1];
1128                 y = pathArray[0][2];
1129                 mx = x;
1130                 my = y;
1131                 start++;
1132                 res.push(["M", x, y]);
1133             }
1134             for (var i = start, ii = pathArray.length; i < ii; i++) {
1135                 var r = res[i] = [],
1136                     pa = pathArray[i];
1137                 if (pa[0] != lowerCase.call(pa[0])) {
1138                     r[0] = lowerCase.call(pa[0]);
1139                     switch (r[0]) {
1140                         case "a":
1141                             r[1] = pa[1];
1142                             r[2] = pa[2];
1143                             r[3] = pa[3];
1144                             r[4] = pa[4];
1145                             r[5] = pa[5];
1146                             r[6] = +(pa[6] - x).toFixed(3);
1147                             r[7] = +(pa[7] - y).toFixed(3);
1148                             break;
1149                         case "v":
1150                             r[1] = +(pa[1] - y).toFixed(3);
1151                             break;
1152                         case "m":
1153                             mx = pa[1];
1154                             my = pa[2];
1155                         default:
1156                             for (var j = 1, jj = pa.length; j < jj; j++) {
1157                                 r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
1158                             }
1159                     }
1160                 } else {
1161                     r = res[i] = [];
1162                     if (pa[0] == "m") {
1163                         mx = pa[1] + x;
1164                         my = pa[2] + y;
1165                     }
1166                     for (var k = 0, kk = pa.length; k < kk; k++) {
1167                         res[i][k] = pa[k];
1168                     }
1169                 }
1170                 var len = res[i].length;
1171                 switch (res[i][0]) {
1172                     case "z":
1173                         x = mx;
1174                         y = my;
1175                         break;
1176                     case "h":
1177                         x += +res[i][len - 1];
1178                         break;
1179                     case "v":
1180                         y += +res[i][len - 1];
1181                         break;
1182                     default:
1183                         x += +res[i][len - 2];
1184                         y += +res[i][len - 1];
1185                 }
1186             }
1187             res.toString = R._path2string;
1188             return res;
1189         }, 0, pathClone),
1190         pathToAbsolute = cacher(function (pathArray) {
1191             if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption
1192                 pathArray = R.parsePathString(pathArray);
1193             }
1194             if (!pathArray || !pathArray.length) {
1195                 return [["M", 0, 0]];
1196             }
1197             var res = [],
1198                 x = 0,
1199                 y = 0,
1200                 mx = 0,
1201                 my = 0,
1202                 start = 0;
1203             if (pathArray[0][0] == "M") {
1204                 x = +pathArray[0][1];
1205                 y = +pathArray[0][2];
1206                 mx = x;
1207                 my = y;
1208                 start++;
1209                 res[0] = ["M", x, y];
1210             }
1211             for (var i = start, ii = pathArray.length; i < ii; i++) {
1212                 var r = res[i] = [],
1213                     pa = pathArray[i];
1214                 if (pa[0] != upperCase.call(pa[0])) {
1215                     r[0] = upperCase.call(pa[0]);
1216                     switch (r[0]) {
1217                         case "A":
1218                             r[1] = pa[1];
1219                             r[2] = pa[2];
1220                             r[3] = pa[3];
1221                             r[4] = pa[4];
1222                             r[5] = pa[5];
1223                             r[6] = +(pa[6] + x);
1224                             r[7] = +(pa[7] + y);
1225                             break;
1226                         case "V":
1227                             r[1] = +pa[1] + y;
1228                             break;
1229                         case "H":
1230                             r[1] = +pa[1] + x;
1231                             break;
1232                         case "M":
1233                             mx = +pa[1] + x;
1234                             my = +pa[2] + y;
1235                         default:
1236                             for (var j = 1, jj = pa.length; j < jj; j++) {
1237                                 r[j] = +pa[j] + ((j % 2) ? x : y);
1238                             }
1239                     }
1240                 } else {
1241                     for (var k = 0, kk = pa.length; k < kk; k++) {
1242                         res[i][k] = pa[k];
1243                     }
1244                 }
1245                 switch (r[0]) {
1246                     case "Z":
1247                         x = mx;
1248                         y = my;
1249                         break;
1250                     case "H":
1251                         x = r[1];
1252                         break;
1253                     case "V":
1254                         y = r[1];
1255                         break;
1256                     case "M":
1257                         mx = res[i][res[i].length - 2];
1258                         my = res[i][res[i].length - 1];
1259                     default:
1260                         x = res[i][res[i].length - 2];
1261                         y = res[i][res[i].length - 1];
1262                 }
1263             }
1264             res.toString = R._path2string;
1265             return res;
1266         }, null, pathClone),
1267         l2c = function (x1, y1, x2, y2) {
1268             return [x1, y1, x2, y2, x2, y2];
1269         },
1270         q2c = function (x1, y1, ax, ay, x2, y2) {
1271             var _13 = 1 / 3,
1272                 _23 = 2 / 3;
1273             return [
1274                     _13 * x1 + _23 * ax,
1275                     _13 * y1 + _23 * ay,
1276                     _13 * x2 + _23 * ax,
1277                     _13 * y2 + _23 * ay,
1278                     x2,
1279                     y2
1280                 ];
1281         },
1282         a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
1283             // for more information of where this math came from visit:
1284             // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1285             var _120 = PI * 120 / 180,
1286                 rad = PI / 180 * (+angle || 0),
1287                 res = [],
1288                 xy,
1289                 rotate = cacher(function (x, y, rad) {
1290                     var X = x * math.cos(rad) - y * math.sin(rad),
1291                         Y = x * math.sin(rad) + y * math.cos(rad);
1292                     return {x: X, y: Y};
1293                 });
1294             if (!recursive) {
1295                 xy = rotate(x1, y1, -rad);
1296                 x1 = xy.x;
1297                 y1 = xy.y;
1298                 xy = rotate(x2, y2, -rad);
1299                 x2 = xy.x;
1300                 y2 = xy.y;
1301                 var cos = math.cos(PI / 180 * angle),
1302                     sin = math.sin(PI / 180 * angle),
1303                     x = (x1 - x2) / 2,
1304                     y = (y1 - y2) / 2;
1305                 var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
1306                 if (h > 1) {
1307                     h = math.sqrt(h);
1308                     rx = h * rx;
1309                     ry = h * ry;
1310                 }
1311                 var rx2 = rx * rx,
1312                     ry2 = ry * ry,
1313                     k = (large_arc_flag == sweep_flag ? -1 : 1) *
1314                         math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
1315                     cx = k * rx * y / ry + (x1 + x2) / 2,
1316                     cy = k * -ry * x / rx + (y1 + y2) / 2,
1317                     f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
1318                     f2 = math.asin(((y2 - cy) / ry).toFixed(9));
1319
1320                 f1 = x1 < cx ? PI - f1 : f1;
1321                 f2 = x2 < cx ? PI - f2 : f2;
1322                 f1 < 0 && (f1 = PI * 2 + f1);
1323                 f2 < 0 && (f2 = PI * 2 + f2);
1324                 if (sweep_flag && f1 > f2) {
1325                     f1 = f1 - PI * 2;
1326                 }
1327                 if (!sweep_flag && f2 > f1) {
1328                     f2 = f2 - PI * 2;
1329                 }
1330             } else {
1331                 f1 = recursive[0];
1332                 f2 = recursive[1];
1333                 cx = recursive[2];
1334                 cy = recursive[3];
1335             }
1336             var df = f2 - f1;
1337             if (abs(df) > _120) {
1338                 var f2old = f2,
1339                     x2old = x2,
1340                     y2old = y2;
1341                 f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
1342                 x2 = cx + rx * math.cos(f2);
1343                 y2 = cy + ry * math.sin(f2);
1344                 res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
1345             }
1346             df = f2 - f1;
1347             var c1 = math.cos(f1),
1348                 s1 = math.sin(f1),
1349                 c2 = math.cos(f2),
1350                 s2 = math.sin(f2),
1351                 t = math.tan(df / 4),
1352                 hx = 4 / 3 * rx * t,
1353                 hy = 4 / 3 * ry * t,
1354                 m1 = [x1, y1],
1355                 m2 = [x1 + hx * s1, y1 - hy * c1],
1356                 m3 = [x2 + hx * s2, y2 - hy * c2],
1357                 m4 = [x2, y2];
1358             m2[0] = 2 * m1[0] - m2[0];
1359             m2[1] = 2 * m1[1] - m2[1];
1360             if (recursive) {
1361                 return [m2, m3, m4][concat](res);
1362             } else {
1363                 res = [m2, m3, m4][concat](res).join().split(",");
1364                 var newres = [];
1365                 for (var i = 0, ii = res.length; i < ii; i++) {
1366                     newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
1367                 }
1368                 return newres;
1369             }
1370         },
1371         findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
1372             var t1 = 1 - t;
1373             return {
1374                 x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
1375                 y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
1376             };
1377         },
1378         curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
1379             var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
1380                 b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
1381                 c = p1x - c1x,
1382                 t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
1383                 t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
1384                 y = [p1y, p2y],
1385                 x = [p1x, p2x],
1386                 dot;
1387             abs(t1) > "1e12" && (t1 = .5);
1388             abs(t2) > "1e12" && (t2 = .5);
1389             if (t1 > 0 && t1 < 1) {
1390                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1391                 x.push(dot.x);
1392                 y.push(dot.y);
1393             }
1394             if (t2 > 0 && t2 < 1) {
1395                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1396                 x.push(dot.x);
1397                 y.push(dot.y);
1398             }
1399             a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
1400             b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
1401             c = p1y - c1y;
1402             t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
1403             t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
1404             abs(t1) > "1e12" && (t1 = .5);
1405             abs(t2) > "1e12" && (t2 = .5);
1406             if (t1 > 0 && t1 < 1) {
1407                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
1408                 x.push(dot.x);
1409                 y.push(dot.y);
1410             }
1411             if (t2 > 0 && t2 < 1) {
1412                 dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
1413                 x.push(dot.x);
1414                 y.push(dot.y);
1415             }
1416             return {
1417                 min: {x: mmin[apply](0, x), y: mmin[apply](0, y)},
1418                 max: {x: mmax[apply](0, x), y: mmax[apply](0, y)}
1419             };
1420         }),
1421         path2curve = cacher(function (path, path2) {
1422             var p = pathToAbsolute(path),
1423                 p2 = path2 && pathToAbsolute(path2),
1424                 attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1425                 attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
1426                 processPath = function (path, d) {
1427                     var nx, ny;
1428                     if (!path) {
1429                         return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
1430                     }
1431                     !(path[0] in {T:1, Q:1}) && (d.qx = d.qy = null);
1432                     switch (path[0]) {
1433                         case "M":
1434                             d.X = path[1];
1435                             d.Y = path[2];
1436                             break;
1437                         case "A":
1438                             path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
1439                             break;
1440                         case "S":
1441                             nx = d.x + (d.x - (d.bx || d.x));
1442                             ny = d.y + (d.y - (d.by || d.y));
1443                             path = ["C", nx, ny][concat](path.slice(1));
1444                             break;
1445                         case "T":
1446                             d.qx = d.x + (d.x - (d.qx || d.x));
1447                             d.qy = d.y + (d.y - (d.qy || d.y));
1448                             path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
1449                             break;
1450                         case "Q":
1451                             d.qx = path[1];
1452                             d.qy = path[2];
1453                             path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
1454                             break;
1455                         case "L":
1456                             path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
1457                             break;
1458                         case "H":
1459                             path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
1460                             break;
1461                         case "V":
1462                             path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
1463                             break;
1464                         case "Z":
1465                             path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
1466                             break;
1467                     }
1468                     return path;
1469                 },
1470                 fixArc = function (pp, i) {
1471                     if (pp[i].length > 7) {
1472                         pp[i].shift();
1473                         var pi = pp[i];
1474                         while (pi.length) {
1475                             pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)));
1476                         }
1477                         pp.splice(i, 1);
1478                         ii = mmax(p.length, p2 && p2.length || 0);
1479                     }
1480                 },
1481                 fixM = function (path1, path2, a1, a2, i) {
1482                     if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
1483                         path2.splice(i, 0, ["M", a2.x, a2.y]);
1484                         a1.bx = 0;
1485                         a1.by = 0;
1486                         a1.x = path1[i][1];
1487                         a1.y = path1[i][2];
1488                         ii = mmax(p.length, p2 && p2.length || 0);
1489                     }
1490                 };
1491             for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
1492                 p[i] = processPath(p[i], attrs);
1493                 fixArc(p, i);
1494                 p2 && (p2[i] = processPath(p2[i], attrs2));
1495                 p2 && fixArc(p2, i);
1496                 fixM(p, p2, attrs, attrs2, i);
1497                 fixM(p2, p, attrs2, attrs, i);
1498                 var seg = p[i],
1499                     seg2 = p2 && p2[i],
1500                     seglen = seg.length,
1501                     seg2len = p2 && seg2.length;
1502                 attrs.x = seg[seglen - 2];
1503                 attrs.y = seg[seglen - 1];
1504                 attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
1505                 attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
1506                 attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
1507                 attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
1508                 attrs2.x = p2 && seg2[seg2len - 2];
1509                 attrs2.y = p2 && seg2[seg2len - 1];
1510             }
1511             return p2 ? [p, p2] : p;
1512         }, null, pathClone),
1513         parseDots = cacher(function (gradient) {
1514             var dots = [];
1515             for (var i = 0, ii = gradient.length; i < ii; i++) {
1516                 var dot = {},
1517                     par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
1518                 dot.color = R.getRGB(par[1]);
1519                 if (dot.color.error) {
1520                     return null;
1521                 }
1522                 dot.color = dot.color.hex;
1523                 par[2] && (dot.offset = par[2] + "%");
1524                 dots.push(dot);
1525             }
1526             for (i = 1, ii = dots.length - 1; i < ii; i++) {
1527                 if (!dots[i].offset) {
1528                     var start = toFloat(dots[i - 1].offset || 0),
1529                         end = 0;
1530                     for (var j = i + 1; j < ii; j++) {
1531                         if (dots[j].offset) {
1532                             end = dots[j].offset;
1533                             break;
1534                         }
1535                     }
1536                     if (!end) {
1537                         end = 100;
1538                         j = ii;
1539                     }
1540                     end = toFloat(end);
1541                     var d = (end - start) / (j - i + 1);
1542                     for (; i < j; i++) {
1543                         start += d;
1544                         dots[i].offset = start + "%";
1545                     }
1546                 }
1547             }
1548             return dots;
1549         }),
1550         getContainer = function (x, y, w, h) {
1551             var container;
1552             container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
1553             if (container == null) {
1554                 return;
1555             }
1556             if (container.tagName) {
1557                 if (y == null) {
1558                     return {
1559                         container: container,
1560                         width: container.style.pixelWidth || container.offsetWidth,
1561                         height: container.style.pixelHeight || container.offsetHeight
1562                     };
1563                 } else {
1564                     return {container: container, width: y, height: w};
1565                 }
1566             }
1567             return {container: 1, x: x, y: y, width: w, height: h};
1568         },
1569         plugins = function (con, add) {
1570             var that = this;
1571             for (var prop in add) {
1572                 if (add[has](prop) && !(prop in con)) {
1573                     switch (typeof add[prop]) {
1574                         case "function":
1575                             (function (f) {
1576                                 con[prop] = con === that ? f : function () { return f[apply](that, arguments); };
1577                             })(add[prop]);
1578                         break;
1579                         case "object":
1580                             con[prop] = con[prop] || {};
1581                             plugins.call(this, con[prop], add[prop]);
1582                         break;
1583                         default:
1584                             con[prop] = add[prop];
1585                         break;
1586                     }
1587                 }
1588             }
1589         },
1590         tear = function (el, paper) {
1591             el == paper.top && (paper.top = el.prev);
1592             el == paper.bottom && (paper.bottom = el.next);
1593             el.next && (el.next.prev = el.prev);
1594             el.prev && (el.prev.next = el.next);
1595         },
1596         tofront = function (el, paper) {
1597             if (paper.top === el) {
1598                 return;
1599             }
1600             tear(el, paper);
1601             el.next = null;
1602             el.prev = paper.top;
1603             paper.top.next = el;
1604             paper.top = el;
1605         },
1606         toback = function (el, paper) {
1607             if (paper.bottom === el) {
1608                 return;
1609             }
1610             tear(el, paper);
1611             el.next = paper.bottom;
1612             el.prev = null;
1613             paper.bottom.prev = el;
1614             paper.bottom = el;
1615         },
1616         insertafter = function (el, el2, paper) {
1617             tear(el, paper);
1618             el2 == paper.top && (paper.top = el);
1619             el2.next && (el2.next.prev = el);
1620             el.next = el2.next;
1621             el.prev = el2;
1622             el2.next = el;
1623         },
1624         insertbefore = function (el, el2, paper) {
1625             tear(el, paper);
1626             el2 == paper.bottom && (paper.bottom = el);
1627             el2.prev && (el2.prev.next = el);
1628             el.prev = el2.prev;
1629             el2.prev = el;
1630             el.next = el2;
1631         },
1632         removed = function (methodname) {
1633             return function () {
1634                 throw new Error("Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object");
1635             };
1636         },
1637         extractTransform = function (el, tstr) {
1638             if (tstr == null) {
1639                 return el._.transform;
1640             }
1641             tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
1642             var tdata = R.parseTransformString(tstr),
1643                 deg = 0,
1644                 dx = 0,
1645                 dy = 0,
1646                 sx = 1,
1647                 sy = 1,
1648                 _ = el._,
1649                 m = new Matrix;
1650             _.transform = tdata || [];
1651             if (tdata) {
1652                 for (var i = 0, ii = tdata.length; i < ii; i++) {
1653                     var t = tdata[i],
1654                         tlen = t.length,
1655                         bb;
1656                     t[0] = Str(t[0]).toLowerCase();
1657                     if (t[0] == "t" && tlen == 3) {
1658                         m.translate(t[1], t[2]);
1659                     } else if (t[0] == "r") {
1660                         if (tlen == 2) {
1661                             bb = bb || el.getBBox(1);
1662                             m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1663                             deg += t[1];
1664                         } else if (tlen == 4) {
1665                             m.rotate(t[1], t[2], t[3]);
1666                             deg += t[1];
1667                         }
1668                     } else if (t[0] == "s") {
1669                         if (tlen == 2 || tlen == 3) {
1670                             bb = bb || el.getBBox(1);
1671                             m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
1672                             sx *= t[1];
1673                             sy *= t[tlen - 1];
1674                         } else if (tlen == 5) {
1675                             m.scale(t[1], t[2], t[3], t[4]);
1676                             sx *= t[1];
1677                             sy *= t[2];
1678                         }
1679                     } else if (t[0] == "m" && tlen == 7) {
1680                         m.add(t[1], t[2], t[3], t[4], t[5], t[6]);
1681                     }
1682                     _.dirtyT = 1;
1683                     el.matrix = m;
1684                 }
1685             }
1686
1687             el.matrix = m;
1688
1689             _.sx = sx;
1690             _.sy = sy;
1691             _.deg = deg;
1692             _.dx = dx = m.e;
1693             _.dy = dy = m.f;
1694
1695             if (sx == 1 && sy == 1 && !deg && _.bbox) {
1696                 _.bbox.x += +dx;
1697                 _.bbox.y += +dy;
1698             } else {
1699                 _.dirtyT = 1;
1700             }
1701         },
1702         getEmpty = function (item) {
1703             switch (item[0]) {
1704                 case "t": return ["t", 0, 0];
1705                 case "m": return ["m", 1, 0, 0, 1, 0, 0];
1706                 case "r": if (item.length == 4) {
1707                     return ["r", 0, item[2], item[3]];
1708                 } else {
1709                     return ["r", 0];
1710                 }
1711                 case "s": if (item.length == 5) {
1712                     return ["s", 1, 1, item[3], item[4]];
1713                 } else if (item.length == 3) {
1714                     return ["s", 1, 1];
1715                 } else {
1716                     return ["s", 1];
1717                 }
1718             }
1719         },
1720         equaliseTransform = function (t1, t2) {
1721             t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
1722             t1 = R.parseTransformString(t1) || [];
1723             t2 = R.parseTransformString(t2) || [];
1724             var maxlength = mmax(t1.length, t2.length),
1725                 from = [],
1726                 to = [],
1727                 i = 0, j, jj,
1728                 tt1, tt2;
1729             for (; i < maxlength; i++) {
1730                 tt1 = t1[i] || getEmpty(t2[i]);
1731                 tt2 = t2[i] || getEmpty(tt1);
1732                 if ((tt1[0] != tt2[0]) ||
1733                     (tt1[0] == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
1734                     (tt1[0] == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
1735                     ) {
1736                     return;
1737                 }
1738                 from[i] = [];
1739                 to[i] = [];
1740                 for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
1741                     j in tt1 && (from[i][j] = tt1[j]);
1742                     j in tt2 && (to[i][j] = tt2[j]);
1743                 }
1744             }
1745             return {
1746                 from: from,
1747                 to: to
1748             };
1749         };
1750     /*\
1751      * Raphael.pathToRelative
1752      [ method ]
1753      **
1754      * Utility method
1755      **
1756      * Converts path to relative form
1757      > Parameters
1758      - pathString (string|array) path string or array of segments
1759      = (array) array of segments.
1760     \*/
1761     R.pathToRelative = pathToRelative;
1762     /*\
1763      * Raphael.path2curve
1764      [ method ]
1765      **
1766      * Utility method
1767      **
1768      * Converts path to a new path where all segments are cubic bezier curves.
1769      > Parameters
1770      - pathString (string|array) path string or array of segments
1771      = (array) array of segments.
1772     \*/
1773     R.path2curve = path2curve;
1774     /*\
1775      * Raphael.matrix
1776      [ method ]
1777      **
1778      * Utility method
1779      **
1780      * Returns matrix based on given parameters.
1781      > Parameters
1782      - a (number)
1783      - b (number)
1784      - c (number)
1785      - d (number)
1786      - e (number)
1787      - f (number)
1788      = (object) @Matrix
1789     \*/
1790     R.matrix = function (a, b, c, d, e, f) {
1791         return new Matrix(a, b, c, d, e, f);
1792     };
1793     function Matrix(a, b, c, d, e, f) {
1794         if (a != null) {
1795             this.a = +a;
1796             this.b = +b;
1797             this.c = +c;
1798             this.d = +d;
1799             this.e = +e;
1800             this.f = +f;
1801         } else {
1802             this.a = 1;
1803             this.b = 0;
1804             this.c = 0;
1805             this.d = 1;
1806             this.e = 0;
1807             this.f = 0;
1808         }
1809     }
1810     (function (matrixproto) {
1811         matrixproto.add = function (a, b, c, d, e, f) {
1812             var out = [[], [], []],
1813                 m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]],
1814                 matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
1815                 x, y, z, res;
1816
1817             if (a && a instanceof Matrix) {
1818                 matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]];
1819             }
1820
1821             for (x = 0; x < 3; x++) {
1822                 for (y = 0; y < 3; y++) {
1823                     res = 0;
1824                     for (z = 0; z < 3; z++) {
1825                         res += m[x][z] * matrix[z][y];
1826                     }
1827                     out[x][y] = res;
1828                 }
1829             }
1830             this.a = out[0][0];
1831             this.b = out[1][0];
1832             this.c = out[0][1];
1833             this.d = out[1][1];
1834             this.e = out[0][2];
1835             this.f = out[1][2];
1836         };
1837         matrixproto.invert = function () {
1838             var me = this,
1839                 x = me.a * me.d - me.b * me.c;
1840             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);
1841         };
1842         matrixproto.clone = function () {
1843             return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
1844         };
1845         matrixproto.translate = function (x, y) {
1846             this.add(1, 0, 0, 1, x, y);
1847         };
1848         matrixproto.scale = function (x, y, cx, cy) {
1849             y == null && (y = x);
1850             this.add(1, 0, 0, 1, cx, cy);
1851             this.add(x, 0, 0, y, 0, 0);
1852             this.add(1, 0, 0, 1, -cx, -cy);
1853         };
1854         matrixproto.rotate = function (a, x, y) {
1855             a = R.rad(a);
1856             var cos = +math.cos(a).toFixed(9),
1857                 sin = +math.sin(a).toFixed(9);
1858             this.add(cos, sin, -sin, cos, x, y);
1859             this.add(1, 0, 0, 1, -x, -y);
1860         };
1861         matrixproto.x = function (x, y) {
1862             return x * this.a + y * this.c + this.e;
1863         };
1864         matrixproto.y = function (x, y) {
1865             return x * this.b + y * this.d + this.f;
1866         };
1867         matrixproto.get = function (i) {
1868             return +this[Str.fromCharCode(97 + i)].toFixed(4);
1869         };
1870         matrixproto.toString = function () {
1871             return R.svg ?
1872                 "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" :
1873                 [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join();
1874         };
1875         matrixproto.toFilter = function () {
1876             return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) +
1877                 ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) +
1878                 ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')";
1879         };
1880         matrixproto.offset = function () {
1881             return [this.e.toFixed(4), this.f.toFixed(4)];
1882         };
1883         function norm(a) {
1884             return a[0] * a[0] + a[1] * a[1];
1885         }
1886         function normalize(a) {
1887             var mag = math.sqrt(norm(a));
1888             a[0] /= mag;
1889             a[1] /= mag;
1890         }
1891         matrixproto.split = function () {
1892             var out = {};
1893             // translation
1894             out.dx = this.e;
1895             out.dy = this.f;
1896
1897             // scale and shear
1898             var row = [[this.a, this.c], [this.b, this.d]];
1899             out.scalex = math.sqrt(norm(row[0]));
1900             normalize(row[0]);
1901
1902             out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
1903             row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
1904
1905             out.scaley = math.sqrt(norm(row[1]));
1906             normalize(row[1]);
1907             out.shear /= out.scaley;
1908
1909             // rotation
1910             var sin = -row[0][1],
1911                 cos = row[1][1];
1912             if (cos < 0) {
1913                 out.rotate = R.deg(math.acos(cos));
1914                 if (sin < 0) {
1915                     out.rotate = 360 - out.rotate;
1916                 }
1917             } else {
1918                 out.rotate = R.deg(math.asin(sin));
1919             }
1920
1921             out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
1922             out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
1923
1924             return out;
1925         };
1926         matrixproto.toTransformString = function () {
1927             var s = this.split();
1928             if (s.isSimple) {
1929                 return "t" + [s.dx, s.dy] + "s" + [s.scalex, s.scaley, 0, 0] + "r" + [s.rotate, 0, 0];
1930             } else {
1931                 return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)];
1932             }
1933         };
1934     })(Matrix.prototype);
1935     
1936     // SVG
1937     if (R.svg) {
1938         var xlink = "http://www.w3.org/1999/xlink",
1939             markers = {
1940                 block: "M5,0 0,2.5 5,5z",
1941                 classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z",
1942                 diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z",
1943                 open: "M6,1 1,3.5 6,6",
1944                 oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"
1945             },
1946             markerCounter = {};
1947         R.toString = function () {
1948             return  "Your browser supports SVG.\nYou are running Rapha\xebl " + this.version;
1949         };
1950         var $ = function (el, attr) {
1951             if (attr) {
1952                 if (typeof el == "string") {
1953                     el = $(el);
1954                 }
1955                 for (var key in attr) if (attr[has](key)) {
1956                     if (key.substring(0, 6) == "xlink:") {
1957                         el.setAttributeNS(xlink, key.substring(6), Str(attr[key]));
1958                     } else {
1959                         el[setAttribute](key, Str(attr[key]));
1960                     }
1961                 }
1962             } else {
1963                 el = g.doc.createElementNS("http://www.w3.org/2000/svg", el);
1964                 el.style && (el.style.webkitTapHighlightColor = "rgba(0,0,0,0)");
1965             }
1966             return el;
1967         },
1968         thePath = function (pathString, SVG) {
1969             var el = $("path");
1970             SVG.canvas && SVG.canvas.appendChild(el);
1971             var p = new Element(el, SVG);
1972             p.type = "path";
1973             setFillAndStroke(p, {fill: "none", stroke: "#000", path: pathString});
1974             return p;
1975         },
1976         gradients = {},
1977         rgGrad = /^url\(#(.*)\)$/,
1978         removeGradientFill = function (node, paper) {
1979             var oid = node.getAttribute(fillString);
1980             oid = oid && oid.match(rgGrad);
1981             if (oid && !--gradients[oid[1]]) {
1982                 delete gradients[oid[1]];
1983                 paper.defs.removeChild(g.doc.getElementById(oid[1]));
1984             }
1985         },
1986         addGradientFill = function (element, gradient) {
1987             var type = "linear",
1988                 id = element.id + gradient,
1989                 fx = .5, fy = .5,
1990                 o = element.node,
1991                 SVG = element.paper,
1992                 s = o.style,
1993                 el = g.doc.getElementById(id);
1994             if (!el) {
1995                 gradient = Str(gradient).replace(radial_gradient, function (all, _fx, _fy) {
1996                     type = "radial";
1997                     if (_fx && _fy) {
1998                         fx = toFloat(_fx);
1999                         fy = toFloat(_fy);
2000                         var dir = ((fy > .5) * 2 - 1);
2001                         pow(fx - .5, 2) + pow(fy - .5, 2) > .25 &&
2002                             (fy = math.sqrt(.25 - pow(fx - .5, 2)) * dir + .5) &&
2003                             fy != .5 &&
2004                             (fy = fy.toFixed(5) - 1e-5 * dir);
2005                     }
2006                     return E;
2007                 });
2008                 gradient = gradient.split(/\s*\-\s*/);
2009                 if (type == "linear") {
2010                     var angle = gradient.shift();
2011                     angle = -toFloat(angle);
2012                     if (isNaN(angle)) {
2013                         return null;
2014                     }
2015                     var vector = [0, 0, math.cos(R.rad(angle)), math.sin(R.rad(angle))],
2016                         max = 1 / (mmax(abs(vector[2]), abs(vector[3])) || 1);
2017                     vector[2] *= max;
2018                     vector[3] *= max;
2019                     if (vector[2] < 0) {
2020                         vector[0] = -vector[2];
2021                         vector[2] = 0;
2022                     }
2023                     if (vector[3] < 0) {
2024                         vector[1] = -vector[3];
2025                         vector[3] = 0;
2026                     }
2027                 }
2028                 var dots = parseDots(gradient);
2029                 if (!dots) {
2030                     return null;
2031                 }
2032                 if (element.gradient) {
2033                     SVG.defs.removeChild(element.gradient);
2034                     delete element.gradient;
2035                 }
2036
2037                 id = id.replace(/[\(\)\s,\xb0#]/g, "-");
2038                 el = $(type + "Gradient", {id: id});
2039                 element.gradient = el;
2040                 $(el, type == "radial" ? {
2041                     fx: fx,
2042                     fy: fy
2043                 } : {
2044                     x1: vector[0],
2045                     y1: vector[1],
2046                     x2: vector[2],
2047                     y2: vector[3],
2048                     gradientTransform: element.matrix.invert()
2049                 });
2050                 SVG.defs.appendChild(el);
2051                 for (var i = 0, ii = dots.length; i < ii; i++) {
2052                     el.appendChild($("stop", {
2053                         offset: dots[i].offset ? dots[i].offset : i ? "100%" : "0%",
2054                         "stop-color": dots[i].color || "#fff"
2055                     }));
2056                 }
2057             }
2058             $(o, {
2059                 fill: "url(#" + id + ")",
2060                 opacity: 1,
2061                 "fill-opacity": 1
2062             });
2063             s.fill = E;
2064             s.opacity = 1;
2065             s.fillOpacity = 1;
2066             return 1;
2067         },
2068         updatePosition = function (o) {
2069             var bbox = o.getBBox(1);
2070             $(o.pattern, {patternTransform: o.matrix.invert() + " translate(" + bbox.x + "," + bbox.y + ")"});
2071         },
2072         addArrow = function (o, value, isEnd) {
2073             if (o.type == "path") {
2074                 var values = Str(value).toLowerCase().split("-"),
2075                     p = o.paper,
2076                     se = isEnd ? "end" : "start",
2077                     node = o.node,
2078                     attrs = o.attrs,
2079                     stroke = attrs["stroke-width"],
2080                     i = values.length,
2081                     type = "classic",
2082                     from,
2083                     to,
2084                     dx,
2085                     refX,
2086                     attr,
2087                     w = 3,
2088                     h = 3,
2089                     t = 5;
2090                 while (i--) {
2091                     switch (values[i]) {
2092                         case "block":
2093                         case "classic":
2094                         case "oval":
2095                         case "diamond":
2096                         case "open":
2097                         case "none":
2098                             type = values[i];
2099                             break;
2100                         case "wide": h = 5; break;
2101                         case "narrow": h = 2; break;
2102                         case "long": w = 5; break;
2103                         case "short": w = 2; break;
2104                     }
2105                 }
2106                 if (type == "open") {
2107                     w += 2;
2108                     h += 2;
2109                     t += 2;
2110                     dx = 1;
2111                     refX = isEnd ? 4 : 1;
2112                     attr = {
2113                         fill: "none",
2114                         stroke: attrs.stroke
2115                     };
2116                 } else {
2117                     refX = dx = w / 2;
2118                     attr = {
2119                         fill: attrs.stroke,
2120                         stroke: "none"
2121                     };
2122                 }
2123                 if (o._.arrows) {
2124                     if (isEnd) {
2125                         o._.arrows.endPath && markerCounter[o._.arrows.endPath]--;
2126                         o._.arrows.endMarker && markerCounter[o._.arrows.endMarker]--;
2127                     } else {
2128                         o._.arrows.startPath && markerCounter[o._.arrows.startPath]--;
2129                         o._.arrows.startMarker && markerCounter[o._.arrows.startMarker]--;
2130                     }
2131                 } else {
2132                     o._.arrows = {};
2133                 }
2134                 if (type != "none") {
2135                     var pathId = "raphael-marker-" + type,
2136                         markerId = "raphael-marker-" + se + type + w + h;
2137                     if (!g.doc.getElementById(pathId)) {
2138                         p.defs.appendChild($($("path"), {
2139                             "stroke-linecap": "round",
2140                             d: markers[type],
2141                             id: pathId
2142                         }));
2143                         markerCounter[pathId] = 1;
2144                     } else {
2145                         markerCounter[pathId]++;
2146                     }
2147                     var marker = g.doc.getElementById(markerId),
2148                         use;
2149                     if (!marker) {
2150                         marker = $($("marker"), {
2151                             id: markerId,
2152                             markerHeight: h,
2153                             markerWidth: w,
2154                             orient: "auto",
2155                             refX: refX,
2156                             refY: h / 2
2157                         });
2158                         use = $($("use"), {
2159                             "xlink:href": "#" + pathId,
2160                             transform: (isEnd ? " rotate(180 " + w / 2 + " " + h / 2 + ") " : S) + "scale(" + w / t + "," + h / t + ")",
2161                             "stroke-width": 1 / ((w / t + h / t) / 2)
2162                         });
2163                         marker.appendChild(use);
2164                         p.defs.appendChild(marker);
2165                         markerCounter[markerId] = 1;
2166                     } else {
2167                         markerCounter[markerId]++;
2168                         use = marker.getElementsByTagName("use")[0];
2169                     }
2170                     $(use, attr);
2171                     var delta = dx * (type != "diamond" && type != "oval");
2172                     if (isEnd) {
2173                         from = o._.arrows.startdx * stroke || 0;
2174                         to = R.getTotalLength(attrs.path) - delta * stroke;
2175                     } else {
2176                         from = delta * stroke;
2177                         to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
2178                     }
2179                     attr = {};
2180                     attr["marker-" + se] = "url(#" + markerId + ")";
2181                     if (to || from) {
2182                         attr.d = Raphael.getSubpath(attrs.path, from, to);
2183                     }
2184                     $(node, attr);
2185                     o._.arrows[se + "Path"] = pathId;
2186                     o._.arrows[se + "Marker"] = markerId;
2187                     o._.arrows[se + "dx"] = delta;
2188                     o._.arrows[se + "Type"] = type;
2189                     o._.arrows[se + "String"] = value;
2190                 } else {
2191                     if (isEnd) {
2192                         from = o._.arrows.startdx * stroke || 0;
2193                         to = R.getTotalLength(attrs.path) - from;
2194                     } else {
2195                         from = 0;
2196                         to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0);
2197                     }
2198                     o._.arrows[se + "Path"] && $(node, {d: Raphael.getSubpath(attrs.path, from, to)});
2199                     delete o._.arrows[se + "Path"];
2200                     delete o._.arrows[se + "Marker"];
2201                     delete o._.arrows[se + "dx"];
2202                     delete o._.arrows[se + "Type"];
2203                     delete o._.arrows[se + "String"];
2204                 }
2205                 for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) {
2206                     var item = g.doc.getElementById(attr);
2207                     item && item.parentNode.removeChild(item);
2208                 }
2209             }
2210         },
2211         setFillAndStroke = function (o, params) {
2212             var dasharray = {
2213                     "": [0],
2214                     "none": [0],
2215                     "-": [3, 1],
2216                     ".": [1, 1],
2217                     "-.": [3, 1, 1, 1],
2218                     "-..": [3, 1, 1, 1, 1, 1],
2219                     ". ": [1, 3],
2220                     "- ": [4, 3],
2221                     "--": [8, 3],
2222                     "- .": [4, 3, 1, 3],
2223                     "--.": [8, 3, 1, 3],
2224                     "--..": [8, 3, 1, 3, 1, 3]
2225                 },
2226                 node = o.node,
2227                 attrs = o.attrs,
2228                 addDashes = function (o, value) {
2229                     value = dasharray[lowerCase.call(value)];
2230                     if (value) {
2231                         var width = o.attrs["stroke-width"] || "1",
2232                             butt = {round: width, square: width, butt: 0}[o.attrs["stroke-linecap"] || params["stroke-linecap"]] || 0,
2233                             dashes = [],
2234                             i = value.length;
2235                         while (i--) {
2236                             dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt;
2237                         }
2238                         $(node, {"stroke-dasharray": dashes.join(",")});
2239                     }
2240                 };
2241             for (var att in params) {
2242                 if (params[has](att)) {
2243                     if (!availableAttrs[has](att)) {
2244                         continue;
2245                     }
2246                     var value = params[att];
2247                     attrs[att] = value;
2248                     switch (att) {
2249                         case "blur":
2250                             o.blur(value);
2251                             break;
2252                         case "href":
2253                         case "title":
2254                         case "target":
2255                             var pn = node.parentNode;
2256                             if (lowerCase.call(pn.tagName) != "a") {
2257                                 var hl = $("a");
2258                                 pn.insertBefore(hl, node);
2259                                 hl.appendChild(node);
2260                                 pn = hl;
2261                             }
2262                             if (att == "target" && value == "blank") {
2263                                 pn.setAttributeNS(xlink, "show", "new");
2264                             } else {
2265                                 pn.setAttributeNS(xlink, att, value);
2266                             }
2267                             break;
2268                         case "cursor":
2269                             node.style.cursor = value;
2270                             break;
2271                         case "transform":
2272                             o.transform(value);
2273                             break;
2274                         case "arrow-start":
2275                             addArrow(o, value);
2276                             break;
2277                         case "arrow-end":
2278                             addArrow(o, value, 1);
2279                             break;
2280                         case "clip-rect":
2281                             var rect = Str(value).split(separator);
2282                             if (rect.length == 4) {
2283                                 o.clip && o.clip.parentNode.parentNode.removeChild(o.clip.parentNode);
2284                                 var el = $("clipPath"),
2285                                     rc = $("rect");
2286                                 el.id = createUUID();
2287                                 $(rc, {
2288                                     x: rect[0],
2289                                     y: rect[1],
2290                                     width: rect[2],
2291                                     height: rect[3]
2292                                 });
2293                                 el.appendChild(rc);
2294                                 o.paper.defs.appendChild(el);
2295                                 $(node, {"clip-path": "url(#" + el.id + ")"});
2296                                 o.clip = rc;
2297                             }
2298                             if (!value) {
2299                                 var clip = g.doc.getElementById(node.getAttribute("clip-path").replace(/(^url\(#|\)$)/g, E));
2300                                 clip && clip.parentNode.removeChild(clip);
2301                                 $(node, {"clip-path": E});
2302                                 delete o.clip;
2303                             }
2304                         break;
2305                         case "path":
2306                             if (o.type == "path") {
2307                                 $(node, {d: value ? attrs.path = pathToAbsolute(value) : "M0,0"});
2308                                 o._.dirty = 1;
2309                                 if (o._.arrows) {
2310                                     "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
2311                                     "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
2312                                 }
2313                             }
2314                             break;
2315                         case "width":
2316                             node[setAttribute](att, value);
2317                             o._.dirty = 1;
2318                             if (attrs.fx) {
2319                                 att = "x";
2320                                 value = attrs.x;
2321                             } else {
2322                                 break;
2323                             }
2324                         case "x":
2325                             if (attrs.fx) {
2326                                 value = -attrs.x - (attrs.width || 0);
2327                             }
2328                         case "rx":
2329                             if (att == "rx" && o.type == "rect") {
2330                                 break;
2331                             }
2332                         case "cx":
2333                             node[setAttribute](att, value);
2334                             o.pattern && updatePosition(o);
2335                             o._.dirty = 1;
2336                             break;
2337                         case "height":
2338                             node[setAttribute](att, value);
2339                             o._.dirty = 1;
2340                             if (attrs.fy) {
2341                                 att = "y";
2342                                 value = attrs.y;
2343                             } else {
2344                                 break;
2345                             }
2346                         case "y":
2347                             if (attrs.fy) {
2348                                 value = -attrs.y - (attrs.height || 0);
2349                             }
2350                         case "ry":
2351                             if (att == "ry" && o.type == "rect") {
2352                                 break;
2353                             }
2354                         case "cy":
2355                             node[setAttribute](att, value);
2356                             o.pattern && updatePosition(o);
2357                             o._.dirty = 1;
2358                             break;
2359                         case "r":
2360                             if (o.type == "rect") {
2361                                 $(node, {rx: value, ry: value});
2362                             } else {
2363                                 node[setAttribute](att, value);
2364                             }
2365                             o._.dirty = 1;
2366                             break;
2367                         case "src":
2368                             if (o.type == "image") {
2369                                 node.setAttributeNS(xlink, "href", value);
2370                             }
2371                             break;
2372                         case "stroke-width":
2373                             if (o._.sx != 1 || o._.sy != 1) {
2374                                 value /= mmax(abs(o._.sx), abs(o._.sy)) || 1;
2375                             }
2376                             if (o.paper._vbSize) {
2377                                 value *= o.paper._vbSize;
2378                             }
2379                             node[setAttribute](att, value);
2380                             if (attrs["stroke-dasharray"]) {
2381                                 addDashes(o, attrs["stroke-dasharray"]);
2382                             }
2383                             if (o._.arrows) {
2384                                 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
2385                                 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
2386                             }
2387                             break;
2388                         case "stroke-dasharray":
2389                             addDashes(o, value);
2390                             break;
2391                         case fillString:
2392                             var isURL = Str(value).match(ISURL);
2393                             if (isURL) {
2394                                 el = $("pattern");
2395                                 var ig = $("image");
2396                                 el.id = createUUID();
2397                                 $(el, {x: 0, y: 0, patternUnits: "userSpaceOnUse", height: 1, width: 1});
2398                                 $(ig, {x: 0, y: 0, "xlink:href": isURL[1]});
2399                                 el.appendChild(ig);
2400
2401                                 (function (el) {
2402                                     preload(isURL[1], function () {
2403                                         var w = this.offsetWidth,
2404                                             h = this.offsetHeight;
2405                                         $(el, {width: w, height: h});
2406                                         $(ig, {width: w, height: h});
2407                                         o.paper.safari();
2408                                     });
2409                                 })(el);
2410                                 o.paper.defs.appendChild(el);
2411                                 node.style.fill = "url(#" + el.id + ")";
2412                                 $(node, {fill: "url(#" + el.id + ")"});
2413                                 o.pattern = el;
2414                                 o.pattern && updatePosition(o);
2415                                 break;
2416                             }
2417                             var clr = R.getRGB(value);
2418                             if (!clr.error) {
2419                                 delete params.gradient;
2420                                 delete attrs.gradient;
2421                                 !R.is(attrs.opacity, "undefined") &&
2422                                     R.is(params.opacity, "undefined") &&
2423                                     $(node, {opacity: attrs.opacity});
2424                                 !R.is(attrs["fill-opacity"], "undefined") &&
2425                                     R.is(params["fill-opacity"], "undefined") &&
2426                                     $(node, {"fill-opacity": attrs["fill-opacity"]});
2427                             } else if ((o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value)) {
2428                                 if ("opacity" in attrs || "fill-opacity" in attrs) {
2429                                     var gradient = g.doc.getElementById(node.getAttribute(fillString).replace(/^url\(#|\)$/g, E));
2430                                     if (gradient) {
2431                                         var stops = gradient.getElementsByTagName("stop");
2432                                         $(stops[stops.length - 1], {"stop-opacity": ("opacity" in attrs ? attrs.opacity : 1) * ("fill-opacity" in attrs ? attrs["fill-opacity"] : 1)});
2433                                     }
2434                                 }
2435                                 attrs.gradient = value;
2436                                 attrs.fill = "none";
2437                                 break;
2438                             }
2439                             clr[has]("opacity") && $(node, {"fill-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
2440                         case "stroke":
2441                             clr = R.getRGB(value);
2442                             node[setAttribute](att, clr.hex);
2443                             att == "stroke" && clr[has]("opacity") && $(node, {"stroke-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity});
2444                             if (att == "stroke" && o._.arrows) {
2445                                 "startString" in o._.arrows && addArrow(o, o._.arrows.startString);
2446                                 "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1);
2447                             }
2448                             break;
2449                         case "gradient":
2450                             (o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value);
2451                             break;
2452                         case "opacity":
2453                             if (attrs.gradient && !attrs[has]("stroke-opacity")) {
2454                                 $(node, {"stroke-opacity": value > 1 ? value / 100 : value});
2455                             }
2456                             // fall
2457                         case "fill-opacity":
2458                             if (attrs.gradient) {
2459                                 gradient = g.doc.getElementById(node.getAttribute(fillString).replace(/^url\(#|\)$/g, E));
2460                                 if (gradient) {
2461                                     stops = gradient.getElementsByTagName("stop");
2462                                     $(stops[stops.length - 1], {"stop-opacity": value});
2463                                 }
2464                                 break;
2465                             }
2466                         default:
2467                             att == "font-size" && (value = toInt(value, 10) + "px");
2468                             var cssrule = att.replace(/(\-.)/g, function (w) {
2469                                 return upperCase.call(w.substring(1));
2470                             });
2471                             node.style[cssrule] = value;
2472                             o._.dirty = 1;
2473                             node[setAttribute](att, value);
2474                             break;
2475                     }
2476                 }
2477             }
2478
2479             tuneText(o, params);
2480         },
2481         leading = 1.2,
2482         tuneText = function (el, params) {
2483             if (el.type != "text" || !(params[has]("text") || params[has]("font") || params[has]("font-size") || params[has]("x") || params[has]("y"))) {
2484                 return;
2485             }
2486             var a = el.attrs,
2487                 node = el.node,
2488                 fontSize = node.firstChild ? toInt(g.doc.defaultView.getComputedStyle(node.firstChild, E).getPropertyValue("font-size"), 10) : 10;
2489
2490             if (params[has]("text")) {
2491                 a.text = params.text;
2492                 while (node.firstChild) {
2493                     node.removeChild(node.firstChild);
2494                 }
2495                 var texts = Str(params.text).split("\n"),
2496                     tspans = [],
2497                     tspan;
2498                 for (var i = 0, ii = texts.length; i < ii; i++) {
2499                     tspan = $("tspan");
2500                     i && $(tspan, {dy: fontSize * leading, x: a.x});
2501                     tspan.appendChild(g.doc.createTextNode(texts[i]));
2502                     node.appendChild(tspan);
2503                     tspans[i] = tspan;
2504                 }
2505             } else {
2506                 tspans = node.getElementsByTagName("tspan");
2507                 for (i = 0, ii = tspans.length; i < ii; i++) if (i) {
2508                     $(tspans[i], {dy: fontSize * leading, x: a.x});
2509                 } else {
2510                     $(tspans[0], {dy: 0});
2511                 }
2512             }
2513             $(node, {x: a.x, y: a.y});
2514             el._.dirty = 1;
2515             var bb = el._getBBox(),
2516                 dif = a.y - (bb.y + bb.height / 2);
2517             dif && R.is(dif, "finite") && $(tspans[0], {dy: dif});
2518         },
2519         Element = function (node, svg) {
2520             var X = 0,
2521                 Y = 0;
2522             /*\
2523              * Element.node
2524              [ property (object) ]
2525              **
2526              * Gives you a reference to the DOM object, so you can assign event handlers or just mess around.
2527              > Usage
2528              | // draw a circle at coordinate 10,10 with radius of 10
2529              | var c = paper.circle(10, 10, 10);
2530              | c.node.onclick = function () {
2531              |     c.attr("fill", "red");
2532              | };
2533             \*/
2534             this[0] = this.node = node;
2535             /*\
2536              * Element.raphael
2537              [ property (object) ]
2538              **
2539              * Internal reference to @Raphael object. In case it is not available.
2540              > Usage
2541              | Raphael.el.red = function () {
2542              |     var hsb = this.paper.raphael.rgb2hsb(this.attr("fill"));
2543              |     hsb.h = 1;
2544              |     this.attr({fill: this.paper.raphael.hsb2rgb(hsb).hex});
2545              | }
2546             \*/
2547             node.raphael = true;
2548             /*\
2549              * Element.id
2550              [ property (number) ]
2551              **
2552              * Unique id of the element. Especially usesful when you want to listen to events of the element, 
2553              * because all events are fired in format `<module>.<action>.<id>`. Also useful for @Paper.getById method.
2554             \*/
2555             this.id = R._oid++;
2556             node.raphaelid = this.id;
2557             this.matrix = new Matrix;
2558             this.realPath = null;
2559             /*\
2560              * Element.paper
2561              [ property (object) ]
2562              **
2563              * Internal reference to “paper” where object drawn. Mainly for use in plugins and element extensions.
2564              > Usage
2565              | Raphael.el.cross = function () {
2566              |     this.attr({fill: "red"});
2567              |     this.paper.path("M10,10L50,50M50,10L10,50")
2568              |         .attr({stroke: "red"});
2569              | }
2570             \*/
2571             this.paper = svg;
2572             this.attrs = this.attrs || {};
2573             this._ = {
2574                 transform: [],
2575                 sx: 1,
2576                 sy: 1,
2577                 deg: 0,
2578                 dx: 0,
2579                 dy: 0,
2580                 dirty: 1
2581             };
2582             !svg.bottom && (svg.bottom = this);
2583             /*\
2584              * Element.prev
2585              [ property (object) ]
2586              **
2587              * Reference to the previous element in the hierarchy.
2588             \*/
2589             this.prev = svg.top;
2590             svg.top && (svg.top.next = this);
2591             svg.top = this;
2592             /*\
2593              * Element.next
2594              [ property (object) ]
2595              **
2596              * Reference to the next element in the hierarchy.
2597             \*/
2598             this.next = null;
2599         },
2600         elproto = Element.prototype;
2601         /*\
2602          * Element.rotate
2603          [ method ]
2604          **
2605          * Adds rotation by given angle around given point to the list of
2606          * transformations of the element.
2607          > Parameters
2608          - deg (number) angle in degrees
2609          - cx (number) #optional x coordinate of the centre of rotation
2610          - cy (number) #optional y coordinate of the centre of rotation
2611          * If cx & cy aren’t specified centre of the shape is used as a point of rotation.
2612          = (object) @Element
2613         \*/
2614         elproto.rotate = function (deg, cx, cy) {
2615             if (this.removed) {
2616                 return this;
2617             }
2618             deg = Str(deg).split(separator);
2619             if (deg.length - 1) {
2620                 cx = toFloat(deg[1]);
2621                 cy = toFloat(deg[2]);
2622             }
2623             deg = toFloat(deg[0]);
2624             (cy == null) && (cx = cy);
2625             if (cx == null || cy == null) {
2626                 var bbox = this.getBBox(1);
2627                 cx = bbox.x + bbox.width / 2;
2628                 cy = bbox.y + bbox.height / 2;
2629             }
2630             this.transform(this._.transform.concat([["r", deg, cx, cy]]));
2631             return this;
2632         };
2633         /*\
2634          * Element.scale
2635          [ method ]
2636          **
2637          * Adds scale by given amount relative to given point to the list of
2638          * transformations of the element.
2639          > Parameters
2640          - sx (number) horisontal scale amount
2641          - sy (number) vertical scale amount
2642          - cx (number) #optional x coordinate of the centre of scale
2643          - cy (number) #optional y coordinate of the centre of scale
2644          * If cx & cy aren’t specified centre of the shape is used instead.
2645          = (object) @Element
2646         \*/
2647         elproto.scale = function (sx, sy, cx, cy) {
2648             if (this.removed) {
2649                 return this;
2650             }
2651             sx = Str(sx).split(separator);
2652             if (sx.length - 1) {
2653                 sy = toFloat(sx[1]);
2654                 cx = toFloat(sx[2]);
2655                 cy = toFloat(sx[3]);
2656             }
2657             sx = toFloat(sx[0]);
2658             (sy == null) && (sy = sx);
2659             (cy == null) && (cx = cy);
2660             if (cx == null || cy == null) {
2661                 var bbox = this.getBBox(1);
2662             }
2663             cx = cx == null ? bbox.x + bbox.width / 2 : cx;
2664             cy = cy == null ? bbox.y + bbox.height / 2 : cy;
2665             this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
2666             return this;
2667         };
2668         /*\
2669          * Element.translate
2670          [ method ]
2671          **
2672          * Adds translation by given amount to the list of transformations of the element.
2673          > Parameters
2674          - dx (number) horisontal shift
2675          - dy (number) vertical shift
2676          = (object) @Element
2677         \*/
2678         elproto.translate = function (dx, dy) {
2679             if (this.removed) {
2680                 return this;
2681             }
2682             dx = Str(dx).split(separator);
2683             if (dx.length - 1) {
2684                 dy = toFloat(dx[1]);
2685             }
2686             dx = toFloat(dx[0]) || 0;
2687             dy = +dy || 0;
2688             this.transform(this._.transform.concat([["t", dx, dy]]));
2689             return this;
2690         };
2691         /*\
2692          * Element.transform
2693          [ method ]
2694          **
2695          * Adds transformation to the element which is separate to other attributes,
2696          * i.e. translation doesn’t change `x` or `y` of the rectange. The format
2697          * of transformation string is similar to the path string syntax:
2698          | "t100,100r30,100,100s2,2,100,100r45s1.5"
2699          * Each letter is a command. There are four commands: `t` is for translate, `r` is for rotate, `s` is for
2700          * scale and `m` is for matrix.
2701          *
2702          * So, the example line above could be read like “translate by 100, 100; rotate 30° around 100, 100; scale twice around 100, 100;
2703          * rotate 45° around centre; scale 1.5 times relative to centre”. As you can see rotate and scale commands have origin
2704          * coordinates as optional parameters, the default is the centre point of the element.
2705          * Matrix accepts six parameters.
2706          > Usage
2707          | var el = paper.rect(10, 20, 300, 200);
2708          | // translate 100, 100, rotate 45°, translate -100, 0
2709          | el.transform("t100,100r45t-100,0");
2710          | // if you want you can append or prepend transformations
2711          | el.transform("...t50,50");
2712          | el.transform("s2...");
2713          | // or even wrap
2714          | el.transform("t50,50...t-50-50");
2715          | // to reset transformation call method with empty string
2716          | el.transform("");
2717          | // to get current value call it without parameters
2718          | console.log(el.transform());
2719          > Parameters
2720          - tstr (string) #optional transformation string
2721          * If tstr isn’t specified
2722          = (string) current transformation string
2723          * else
2724          = (object) @Element
2725         \*/
2726         elproto.transform = function (tstr) {
2727             var _ = this._;
2728             if (tstr == null) {
2729                 return _.transform;
2730             }
2731             extractTransform(this, tstr);
2732
2733             this.clip && $(this.clip, {transform: this.matrix.invert()});
2734             this.pattern && updatePosition(this);
2735             this.node && $(this.node, {transform: this.matrix});
2736             
2737             if (_.sx != 1 || _.sy != 1) {
2738                 var sw = this.attrs[has]("stroke-width") ? this.attrs["stroke-width"] : 1;
2739                 this.attr({"stroke-width": sw});
2740             }
2741
2742             return this;
2743         };
2744         /*\
2745          * Element.hide
2746          [ method ]
2747          **
2748          * Makes element invisible. See @Element.show.
2749          = (object) @Element
2750         \*/
2751         elproto.hide = function () {
2752             !this.removed && this.paper.safari(this.node.style.display = "none");
2753             return this;
2754         };
2755         /*\
2756          * Element.show
2757          [ method ]
2758          **
2759          * Makes element visible. See @Element.hide.
2760          = (object) @Element
2761         \*/
2762         elproto.show = function () {
2763             !this.removed && this.paper.safari(this.node.style.display = "");
2764             return this;
2765         };
2766         /*\
2767          * Element.remove
2768          [ method ]
2769          **
2770          * Removes element form the paper.
2771         \*/
2772         elproto.remove = function () {
2773             if (this.removed) {
2774                 return;
2775             }
2776             eve.unbind("*.*." + this.id);
2777             tear(this, this.paper);
2778             this.node.parentNode.removeChild(this.node);
2779             for (var i in this) {
2780                 delete this[i];
2781             }
2782             this.removed = true;
2783         };
2784         elproto._getBBox = function () {
2785             if (this.node.style.display == "none") {
2786                 this.show();
2787                 var hide = true;
2788             }
2789             var bbox = {};
2790             try {
2791                 bbox = this.node.getBBox();
2792             } catch(e) {
2793                 // Firefox 3.0.x plays badly here
2794             } finally {
2795                 bbox = bbox || {};
2796             }
2797             hide && this.hide();
2798             return bbox;
2799         };
2800         /*\
2801          * Element.attr
2802          [ method ]
2803          **
2804          * Sets the attributes of the element.
2805          > Parameters
2806          - attrName (string) attribute’s name
2807          - value (string) value
2808          * or
2809          - params (object) object of name/value pairs
2810          * or
2811          - attrName (string) attribute’s name
2812          * or
2813          - attrNames (array) in this case method returns array of current values for given attribute names
2814          = (object) @Element if attrsName & value or params are passed in.
2815          = (...) value of the attribute if only attrsName is passed in.
2816          = (array) array of values of the attribute if attrsNames is passed in.
2817          = (object) object of attributes if nothing is passed in.
2818          > Possible parameters
2819          # <p>Please refer to the <a href="http://www.w3.org/TR/SVG/" title="The W3C Recommendation for the SVG language describes these properties in detail.">SVG specification</a> for an explanation of these parameters.</p>
2820          o arrow-end (string) arrowhead on the end of the path. The format for string is `<type>[-<width>[-<length>]]`. Possible types: `classic`, `block`, `open`, `oval`, `diamond`, `none`, width: `wide`, `narrow`, `midium`, length: `long`, `short`, `midium`.
2821          o clip-rect (string) comma or space separated values: x, y, width and height
2822          o cursor (string) CSS type of the cursor
2823          o cx (number)
2824          o cy (number)
2825          o fill (string) colour, gradient or image
2826          o fill-opacity (number)
2827          o font (string)
2828          o font-family (string)
2829          o font-size (number) font size in pixels
2830          o font-weight (string)
2831          o height (number)
2832          o href (string) URL, if specified element behaves as hyperlink
2833          o opacity (number)
2834          o path (string) SVG path string format
2835          o r (number)
2836          o rx (number)
2837          o ry (number)
2838          o src (string) image URL, only works for @Element.image element
2839          o stroke (string) stroke colour
2840          o stroke-dasharray (string) [“”, “`-`”, “`.`”, “`-.`”, “`-..`”, “`. `”, “`- `”, “`--`”, “`- .`”, “`--.`”, “`--..`”]
2841          o stroke-linecap (string) [“`butt`”, “`square`”, “`round`”]
2842          o stroke-linejoin (string) [“`bevel`”, “`round`”, “`miter`”]
2843          o stroke-miterlimit (number)
2844          o stroke-opacity (number)
2845          o stroke-width (number) stroke width in pixels, default is '1'
2846          o target (string) used with href
2847          o text (string) contents of the text element. Use `\n` for multiline text
2848          o text-anchor (string) [“`start`”, “`middle`”, “`end`”], default is “`middle`”
2849          o title (string) will create tooltip with a given text
2850          o transform (string) see @Element.transform
2851          o width (number)
2852          o x (number)
2853          o y (number)
2854          > Gradients
2855          * Linear gradient format: “`‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`90-#fff-#000`” – 90°
2856          * gradient from white to black or “`0-#fff-#f00:20-#000`” – 0° gradient from white via red (at 20%) to black.
2857          *
2858          * radial gradient: “`r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`r#fff-#000`” –
2859          * gradient from white to black or “`r(0.25, 0.75)#fff-#000`” – gradient from white to black with focus point
2860          * at 0.25, 0.75. Focus point coordinates are in 0..1 range. Radial gradients can only be applied to circles and ellipses.
2861          > Path String
2862          # <p>Please refer to <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 documentation regarding path string</a>. Raphaël fully supports it.</p>
2863          > Colour Parsing
2864          # <ul>
2865          #     <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li>
2866          #     <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li>
2867          #     <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li>
2868          #     <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200,&nbsp;100,&nbsp;0)</code>”)</li>
2869          #     <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>”)</li>
2870          #     <li>rgba(•••, •••, •••, •••) — red, green and blue channels’ values: (“<code>rgba(200,&nbsp;100,&nbsp;0, .5)</code>”)</li>
2871          #     <li>rgba(•••%, •••%, •••%, •••%) — same as above, but in %: (“<code>rgba(100%,&nbsp;175%,&nbsp;0%, 50%)</code>”)</li>
2872          #     <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>”)</li>
2873          #     <li>hsb(•••%, •••%, •••%) — same as above, but in %</li>
2874          #     <li>hsba(•••, •••, •••, •••) — same as above, but with opacity</li>
2875          #     <li>hsl(•••, •••, •••) — almost the same as hsb, see <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" title="HSL and HSV - Wikipedia, the free encyclopedia">Wikipedia page</a></li>
2876          #     <li>hsl(•••%, •••%, •••%) — same as above, but in %</li>
2877          #     <li>hsla(•••, •••, •••) — same as above, but with opacity</li>
2878          #     <li>Optionally for hsb and hsl you could specify hue as a degree: “<code>hsl(240deg,&nbsp;1,&nbsp;.5)</code>” or, if you want to go fancy, “<code>hsl(240°,&nbsp;1,&nbsp;.5)</code>”</li>
2879          # </ul>
2880         \*/
2881         elproto.attr = function (name, value) {
2882             if (this.removed) {
2883                 return this;
2884             }
2885             if (name == null) {
2886                 var res = {};
2887                 for (var a in this.attrs) if (this.attrs[has](a)) {
2888                     res[a] = this.attrs[a];
2889                 }
2890                 res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
2891                 res.transform = this._.transform;
2892                 return res;
2893             }
2894             if (value == null && R.is(name, string)) {
2895                 if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
2896                     return this.attrs.gradient;
2897                 }
2898                 if (name == "transform") {
2899                     return this._.transform;
2900                 }
2901                 var names = name.split(separator),
2902                     out = {};
2903                 for (var i = 0, ii = names.length; i < ii; i++) {
2904                     name = names[i];
2905                     if (name in this.attrs) {
2906                         out[name] = this.attrs[name];
2907                     } else if (R.is(this.paper.customAttributes[name], "function")) {
2908                         out[name] = this.paper.customAttributes[name].def;
2909                     } else {
2910                         out[name] = availableAttrs[name];
2911                     }
2912                 }
2913                 return ii - 1 ? out : out[names[0]];
2914             }
2915             if (value == null && R.is(name, array)) {
2916                 out = {};
2917                 for (i = 0, ii = name.length; i < ii; i++) {
2918                     out[name[i]] = this.attr(name[i]);
2919                 }
2920                 return out;
2921             }
2922             if (value != null) {
2923                 var params = {};
2924                 params[name] = value;
2925             } else if (name != null && R.is(name, "object")) {
2926                 params = name;
2927             }
2928             for (var key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
2929                 var par = this.paper.customAttributes[key].apply(this, [][concat](params[key]));
2930                 this.attrs[key] = params[key];
2931                 for (var subkey in par) if (par[has](subkey)) {
2932                     params[subkey] = par[subkey];
2933                 }
2934             }
2935             setFillAndStroke(this, params);
2936             return this;
2937         };
2938         /*\
2939          * Element.toFront
2940          [ method ]
2941          **
2942          * Moves the element so it is the closest to the viewer’s eyes, on top of other elements.
2943          = (object) @Element
2944         \*/
2945         elproto.toFront = function () {
2946             if (this.removed) {
2947                 return this;
2948             }
2949             this.node.parentNode.appendChild(this.node);
2950             var svg = this.paper;
2951             svg.top != this && tofront(this, svg);
2952             return this;
2953         };
2954         /*\
2955          * Element.toBack
2956          [ method ]
2957          **
2958          * Moves the element so it is the furthest from the viewer’s eyes, behind other elements.
2959          = (object) @Element
2960         \*/
2961         elproto.toBack = function () {
2962             if (this.removed) {
2963                 return this;
2964             }
2965             if (this.node.parentNode.firstChild != this.node) {
2966                 this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
2967                 toback(this, this.paper);
2968                 var svg = this.paper;
2969             }
2970             return this;
2971         };
2972         /*\
2973          * Element.insertAfter
2974          [ method ]
2975          **
2976          * Inserts current object after the given one.
2977          = (object) @Element
2978         \*/
2979         elproto.insertAfter = function (element) {
2980             if (this.removed) {
2981                 return this;
2982             }
2983             var node = element.node || element[element.length - 1].node;
2984             if (node.nextSibling) {
2985                 node.parentNode.insertBefore(this.node, node.nextSibling);
2986             } else {
2987                 node.parentNode.appendChild(this.node);
2988             }
2989             insertafter(this, element, this.paper);
2990             return this;
2991         };
2992         /*\
2993          * Element.insertBefore
2994          [ method ]
2995          **
2996          * Inserts current object before the given one.
2997          = (object) @Element
2998         \*/
2999         elproto.insertBefore = function (element) {
3000             if (this.removed) {
3001                 return this;
3002             }
3003             var node = element.node || element[0].node;
3004             node.parentNode.insertBefore(this.node, node);
3005             insertbefore(this, element, this.paper);
3006             return this;
3007         };
3008         elproto.blur = function (size) {
3009             // Experimental. No Safari support. Use it on your own risk.
3010             var t = this;
3011             if (+size !== 0) {
3012                 var fltr = $("filter"),
3013                     blur = $("feGaussianBlur");
3014                 t.attrs.blur = size;
3015                 fltr.id = createUUID();
3016                 $(blur, {stdDeviation: +size || 1.5});
3017                 fltr.appendChild(blur);
3018                 t.paper.defs.appendChild(fltr);
3019                 t._blur = fltr;
3020                 $(t.node, {filter: "url(#" + fltr.id + ")"});
3021             } else {
3022                 if (t._blur) {
3023                     t._blur.parentNode.removeChild(t._blur);
3024                     delete t._blur;
3025                     delete t.attrs.blur;
3026                 }
3027                 t.node.removeAttribute("filter");
3028             }
3029         };
3030         var theCircle = function (svg, x, y, r) {
3031             var el = $("circle");
3032             svg.canvas && svg.canvas.appendChild(el);
3033             var res = new Element(el, svg);
3034             res.attrs = {cx: x, cy: y, r: r, fill: "none", stroke: "#000"};
3035             res.type = "circle";
3036             $(el, res.attrs);
3037             return res;
3038         },
3039         theRect = function (svg, x, y, w, h, r) {
3040             var el = $("rect");
3041             svg.canvas && svg.canvas.appendChild(el);
3042             var res = new Element(el, svg);
3043             res.attrs = {x: x, y: y, width: w, height: h, r: r || 0, rx: r || 0, ry: r || 0, fill: "none", stroke: "#000"};
3044             res.type = "rect";
3045             $(el, res.attrs);
3046             return res;
3047         },
3048         theEllipse = function (svg, x, y, rx, ry) {
3049             var el = $("ellipse");
3050             svg.canvas && svg.canvas.appendChild(el);
3051             var res = new Element(el, svg);
3052             res.attrs = {cx: x, cy: y, rx: rx, ry: ry, fill: "none", stroke: "#000"};
3053             res.type = "ellipse";
3054             $(el, res.attrs);
3055             return res;
3056         },
3057         theImage = function (svg, src, x, y, w, h) {
3058             var el = $("image");
3059             $(el, {x: x, y: y, width: w, height: h, preserveAspectRatio: "none"});
3060             el.setAttributeNS(xlink, "href", src);
3061             svg.canvas && svg.canvas.appendChild(el);
3062             var res = new Element(el, svg);
3063             res.attrs = {x: x, y: y, width: w, height: h, src: src};
3064             res.type = "image";
3065             return res;
3066         },
3067         theText = function (svg, x, y, text) {
3068             var el = $("text");
3069             // $(el, {x: x, y: y, "text-anchor": "middle"});
3070             svg.canvas && svg.canvas.appendChild(el);
3071             var res = new Element(el, svg);
3072             res.attrs = {
3073                 x: x,
3074                 y: y,
3075                 "text-anchor": "middle",
3076                 text: text,
3077                 font: availableAttrs.font,
3078                 stroke: "none",
3079                 fill: "#000"
3080             };
3081             res.type = "text";
3082             setFillAndStroke(res, res.attrs);
3083             return res;
3084         },
3085         setSize = function (width, height) {
3086             this.width = width || this.width;
3087             this.height = height || this.height;
3088             this.canvas[setAttribute]("width", this.width);
3089             this.canvas[setAttribute]("height", this.height);
3090             if (this._viewBox) {
3091                 this.setViewBox.apply(this, this._viewBox);
3092             }
3093             return this;
3094         },
3095         create = function () {
3096             var con = getContainer[apply](0, arguments),
3097                 container = con && con.container,
3098                 x = con.x,
3099                 y = con.y,
3100                 width = con.width,
3101                 height = con.height;
3102             if (!container) {
3103                 throw new Error("SVG container not found.");
3104             }
3105             var cnvs = $("svg"),
3106                 css = "overflow:hidden;",
3107                 isFloating;
3108             x = x || 0;
3109             y = y || 0;
3110             width = width || 512;
3111             height = height || 342;
3112             $(cnvs, {
3113                 height: height,
3114                 version: 1.1,
3115                 width: width,
3116                 xmlns: "http://www.w3.org/2000/svg"
3117             });
3118             if (container == 1) {
3119                 cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px";
3120                 g.doc.body.appendChild(cnvs);
3121                 isFloating = 1;
3122             } else {
3123                 cnvs.style.cssText = css + "position:relative";
3124                 if (container.firstChild) {
3125                     container.insertBefore(cnvs, container.firstChild);
3126                 } else {
3127                     container.appendChild(cnvs);
3128                 }
3129             }
3130             container = new Paper;
3131             container.width = width;
3132             container.height = height;
3133             container.canvas = cnvs;
3134             plugins.call(container, container, R.fn);
3135             container.clear();
3136             container._left = container._top = 0;
3137             isFloating && (container.renderfix = fun);
3138             container.renderfix();
3139             return container;
3140         },
3141         
3142         setViewBox = function (x, y, w, h, fit) {
3143             eve("setViewBox", this, this._viewBox, [x, y, w, h, fit]);
3144             var size = mmax(w / this.width, h / this.height),
3145                 top = this.top,
3146                 aspectRatio = fit ? "meet" : "xMinYMin",
3147                 vb,
3148                 sw;
3149             if (x == null) {
3150                 if (this._vbSize) {
3151                     size = 1;
3152                 }
3153                 delete this._vbSize;
3154                 vb = "0 0 " + this.width + S + this.height;
3155             } else {
3156                 this._vbSize = size;
3157                 vb = x + S + y + S + w + S + h;
3158             }
3159             $(this.canvas, {
3160                 viewBox: vb,
3161                 preserveAspectRatio: aspectRatio
3162             });
3163             while (size && top) {
3164                 sw = "stroke-width" in top.attrs ? top.attrs["stroke-width"] : 1;
3165                 top.attr({"stroke-width": sw});
3166                 top._.dirty = 1;
3167                 top._.dirtyT = 1;
3168                 top = top.prev;
3169             }
3170             this._viewBox = [x, y, w, h, !!fit];
3171             return this;
3172         };
3173         /*\
3174          * Paper.renderfix
3175          [ method ]
3176          **
3177          * Fixes the issue of Firefox and IE9 regarding subpixel rendering. If paper is dependant
3178          * on other elements after reflow it could shift half pixel which cause for lines to lost their crispness.
3179          * This method fixes the issue.
3180          **
3181            Special thanks to Mariusz Nowak (http://www.medikoo.com/) for this method.
3182         \*/
3183         paperproto.renderfix = function () {
3184             var cnvs = this.canvas,
3185                 s = cnvs.style,
3186                 pos = cnvs.getScreenCTM(),
3187                 left = -pos.e % 1,
3188                 top = -pos.f % 1;
3189             if (left || top) {
3190                 if (left) {
3191                     this._left = (this._left + left) % 1;
3192                     s.left = this._left + "px";
3193                 }
3194                 if (top) {
3195                     this._top = (this._top + top) % 1;
3196                     s.top = this._top + "px";
3197                 }
3198             }
3199         };
3200         /*\
3201          * Paper.clear
3202          [ method ]
3203          **
3204          * Clears the paper, i.e. removes all the elements.
3205         \*/
3206         paperproto.clear = function () {
3207             eve("clear", this);
3208             var c = this.canvas;
3209             while (c.firstChild) {
3210                 c.removeChild(c.firstChild);
3211             }
3212             this.bottom = this.top = null;
3213             (this.desc = $("desc")).appendChild(g.doc.createTextNode("Created with Rapha\xebl " + R.version));
3214             c.appendChild(this.desc);
3215             c.appendChild(this.defs = $("defs"));
3216         };
3217         /*\
3218          * Paper.remove
3219          [ method ]
3220          **
3221          * Removes the paper from the DOM.
3222         \*/
3223         paperproto.remove = function () {
3224             eve("remove", this);
3225             this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
3226             for (var i in this) {
3227                 this[i] = removed(i);
3228             }
3229         };
3230     }
3231
3232     // VML
3233     if (R.vml) {
3234         var map = {M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x"},
3235             bites = /([clmz]),?([^clmz]*)/gi,
3236             blurregexp = / progid:\S+Blur\([^\)]+\)/g,
3237             val = /-?[^,\s-]+/g,
3238             cssDot = "position:absolute;left:0;top:0;width:1px;height:1px",
3239             zoom = 21600,
3240             pathTypes = {path: 1, rect: 1},
3241             ovalTypes = {circle: 1, ellipse: 1},
3242             path2vml = function (path) {
3243                 var total =  /[ahqstv]/ig,
3244                     command = pathToAbsolute;
3245                 Str(path).match(total) && (command = path2curve);
3246                 total = /[clmz]/g;
3247                 if (command == pathToAbsolute && !Str(path).match(total)) {
3248                     var res = Str(path).replace(bites, function (all, command, args) {
3249                         var vals = [],
3250                             isMove = lowerCase.call(command) == "m",
3251                             res = map[command];
3252                         args.replace(val, function (value) {
3253                             if (isMove && vals.length == 2) {
3254                                 res += vals + map[command == "m" ? "l" : "L"];
3255                                 vals = [];
3256                             }
3257                             vals.push(round(value * zoom));
3258                         });
3259                         return res + vals;
3260                     });
3261                     return res;
3262                 }
3263                 var pa = command(path), p, r;
3264                 res = [];
3265                 for (var i = 0, ii = pa.length; i < ii; i++) {
3266                     p = pa[i];
3267                     r = lowerCase.call(pa[i][0]);
3268                     r == "z" && (r = "x");
3269                     for (var j = 1, jj = p.length; j < jj; j++) {
3270                         r += round(p[j] * zoom) + (j != jj - 1 ? "," : E);
3271                     }
3272                     res.push(r);
3273                 }
3274                 return res.join(S);
3275             },
3276             compensation = function (deg, dx, dy) {
3277                 var m = new Matrix;
3278                 m.rotate(-deg, .5, .5);
3279                 return {
3280                     dx: m.x(dx, dy),
3281                     dy: m.y(dx, dy)
3282                 };
3283             },
3284             setCoords = function (p, sx, sy, dx, dy, deg) {
3285                 var _ = p._,
3286                     m = p.matrix,
3287                     // sp = m.split(),
3288                     // sx = sp.scalex,
3289                     // sy = sp.scaley,
3290                     // deg = sp.rotate,
3291                     // dx = sp.dx,
3292                     // dy = sp.dy,
3293                     fillpos = _.fillpos,
3294                     o = p.node,
3295                     s = o.style,
3296                     y = 1,
3297                     flip = "",
3298                     dxdy,
3299                     kx = zoom / sx,
3300                     ky = zoom / sy;
3301                 s.visibility = "hidden";
3302                 o.coordsize = abs(kx) + S + abs(ky);
3303                 s.rotation = deg * (sx * sy < 0 ? -1 : 1);
3304                 if (deg) {
3305                     var c = compensation(deg, dx, dy);
3306                     dx = c.dx;
3307                     dy = c.dy;
3308                 }
3309                 sx < 0 && (flip += "x");
3310                 sy < 0 && (flip += " y") && (y = -1);
3311                 s.flip = flip;
3312                 o.coordorigin = (dx * -kx) + S + (dy * -ky);
3313                 if (fillpos || _.fillsize) {
3314                     var fill = o.getElementsByTagName(fillString);
3315                     fill = fill && fill[0];
3316                     o.removeChild(fill);
3317                     if (fillpos) {
3318                         c = compensation(deg, m.x(fillpos[0], fillpos[1]), m.y(fillpos[0], fillpos[1]));
3319                         fill.position = c.dx * y + S + c.dy * y;
3320                     }
3321                     if (_.fillsize) {
3322                         fill.size = _.fillsize[0] * abs(sx) + S + _.fillsize[1] * abs(sy);
3323                     }
3324                     o.appendChild(fill);
3325                 }
3326                 s.visibility = "visible";
3327             };
3328         R.toString = function () {
3329             return  "Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl " + this.version;
3330         };
3331         addArrow = function (o, value, isEnd) {
3332             var values = Str(value).toLowerCase().split("-"),
3333                 se = isEnd ? "end" : "start",
3334                 i = values.length,
3335                 type = "classic",
3336                 w = "medium",
3337                 h = "medium";
3338             while (i--) {
3339                 switch (values[i]) {
3340                     case "block":
3341                     case "classic":
3342                     case "oval":
3343                     case "diamond":
3344                     case "open":
3345                     case "none":
3346                         type = values[i];
3347                         break;
3348                     case "wide":
3349                     case "narrow": h = values[i]; break;
3350                     case "long":
3351                     case "short": w = values[i]; break;
3352                 }
3353             }
3354             var stroke = o.node.getElementsByTagName("stroke")[0];
3355             stroke[se + "arrow"] = type;
3356             stroke[se + "arrowlength"] = w;
3357             stroke[se + "arrowwidth"] = h;
3358         };
3359         setFillAndStroke = function (o, params) {
3360             o.paper.canvas.style.display = "none";
3361             o.attrs = o.attrs || {};
3362             var node = o.node,
3363                 a = o.attrs,
3364                 s = node.style,
3365                 xy,
3366                 newpath = pathTypes[o.type] && (params.x != a.x || params.y != a.y || params.width != a.width || params.height != a.height || params.cx != a.cx || params.cy != a.cy || params.rx != a.rx || params.ry != a.ry || params.r != a.r),
3367                 isOval = ovalTypes[o.type] && (a.cx != params.cx || a.cy != params.cy || a.r != params.r || a.rx != params.rx || a.ry != params.ry),
3368                 res = o;
3369
3370
3371             for (var par in params) if (params[has](par)) {
3372                 a[par] = params[par];
3373             }
3374             if (newpath) {
3375                 a.path = getPath[o.type](o);
3376                 o._.dirty = 1;
3377             }
3378             params.href && (node.href = params.href);
3379             params.title && (node.title = params.title);
3380             params.target && (node.target = params.target);
3381             params.cursor && (s.cursor = params.cursor);
3382             "blur" in params && o.blur(params.blur);
3383             "transform" in params && o.transform(params.transform);
3384             if (params.path && o.type == "path" || newpath) {
3385                 node.path = path2vml(a.path);
3386             }
3387             if (isOval) {
3388                 var cx = a.cx,
3389                     cy = a.cy,
3390                     rx = a.rx || a.r || 0,
3391                     ry = a.ry || a.r || 0;
3392                 node.path = R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", round((cx - rx) * zoom), round((cy - ry) * zoom), round((cx + rx) * zoom), round((cy + ry) * zoom), round(cx * zoom));
3393             }
3394             if ("clip-rect" in params) {
3395                 var rect = Str(params["clip-rect"]).split(separator);
3396                 if (rect.length == 4) {
3397                     rect[2] = +rect[2] + (+rect[0]);
3398                     rect[3] = +rect[3] + (+rect[1]);
3399                     var div = node.clipRect || g.doc.createElement("div"),
3400                         dstyle = div.style,
3401                         group = node.parentNode;
3402                     dstyle.clip = R.format("rect({1}px {2}px {3}px {0}px)", rect);
3403                     if (!node.clipRect) {
3404                         dstyle.position = "absolute";
3405                         dstyle.top = 0;
3406                         dstyle.left = 0;
3407                         dstyle.width = o.paper.width + "px";
3408                         dstyle.height = o.paper.height + "px";
3409                         group.parentNode.insertBefore(div, group);
3410                         div.appendChild(group);
3411                         node.clipRect = div;
3412                     }
3413                 }
3414                 if (!params["clip-rect"]) {
3415                     node.clipRect && (node.clipRect.style.clip = E);
3416                 }
3417             }
3418             if (o.textpath) {
3419                 var textpathStyle = o.textpath.style;
3420                 params.font && (textpathStyle.font = params.font);
3421                 params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"');
3422                 params["font-size"] && (textpathStyle.fontSize = params["font-size"]);
3423                 params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]);
3424                 params["font-style"] && (textpathStyle.fontStyle = params["font-style"]);
3425             }
3426             if ("arrow-start" in params) {
3427                 addArrow(res, params["arrow-start"]);
3428             }
3429             if ("arrow-end" in params) {
3430                 addArrow(res, params["arrow-end"], 1);
3431             }
3432             if (params.opacity != null || 
3433                 params["stroke-width"] != null ||
3434                 params.fill != null ||
3435                 params.src != null ||
3436                 params.stroke != null ||
3437                 params["stroke-width"] != null ||
3438                 params["stroke-opacity"] != null ||
3439                 params["fill-opacity"] != null ||
3440                 params["stroke-dasharray"] != null ||
3441                 params["stroke-miterlimit"] != null ||
3442                 params["stroke-linejoin"] != null ||
3443                 params["stroke-linecap"] != null) {
3444                 var fill = node.getElementsByTagName(fillString),
3445                     newfill = false;
3446                 fill = fill && fill[0];
3447                 !fill && (newfill = fill = createNode(fillString));
3448                 if (o.type == "image" && params.src) {
3449                     fill.src = params.src;
3450                 }
3451                 if ("fill-opacity" in params || "opacity" in params) {
3452                     var opacity = ((+a["fill-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+R.getRGB(params.fill).o + 1 || 2) - 1);
3453                     opacity = mmin(mmax(opacity, 0), 1);
3454                     fill.opacity = opacity;
3455                 }
3456                 params.fill && (fill.on = true);
3457                 if (fill.on == null || params.fill == "none" || params.fill === null) {
3458                     fill.on = false;
3459                 }
3460                 if (fill.on && params.fill) {
3461                     var isURL = Str(params.fill).match(ISURL);
3462                     if (isURL) {
3463                         fill.parentNode == node && node.removeChild(fill);
3464                         fill.rotate = true;
3465                         fill.src = isURL[1];
3466                         fill.type = "tile";
3467                         var bbox = o.getBBox(1);
3468                         fill.position = bbox.x + S + bbox.y;
3469                         o._.fillpos = [bbox.x, bbox.y];
3470
3471                         preload(isURL[1], function () {
3472                             o._.fillsize = [this.offsetWidth, this.offsetHeight];
3473                         });
3474                     } else {
3475                         fill.color = R.getRGB(params.fill).hex;
3476                         fill.src = E;
3477                         fill.type = "solid";
3478                         if (R.getRGB(params.fill).error && (res.type in {circle: 1, ellipse: 1} || Str(params.fill).charAt() != "r") && addGradientFill(res, params.fill, fill)) {
3479                             a.fill = "none";
3480                             a.gradient = params.fill;
3481                             fill.rotate = false;
3482                         }
3483                     }
3484                 }
3485                 node.appendChild(fill);
3486                 var stroke = (node.getElementsByTagName("stroke") && node.getElementsByTagName("stroke")[0]),
3487                 newstroke = false;
3488                 !stroke && (newstroke = stroke = createNode("stroke"));
3489                 if ((params.stroke && params.stroke != "none") ||
3490                     params["stroke-width"] ||
3491                     params["stroke-opacity"] != null ||
3492                     params["stroke-dasharray"] ||
3493                     params["stroke-miterlimit"] ||
3494                     params["stroke-linejoin"] ||
3495                     params["stroke-linecap"]) {
3496                     stroke.on = true;
3497                 }
3498                 (params.stroke == "none" || params.stroke === null || stroke.on == null || params.stroke == 0 || params["stroke-width"] == 0) && (stroke.on = false);
3499                 var strokeColor = R.getRGB(params.stroke);
3500                 stroke.on && params.stroke && (stroke.color = strokeColor.hex);
3501                 opacity = ((+a["stroke-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+strokeColor.o + 1 || 2) - 1);
3502                 var width = (toFloat(params["stroke-width"]) || 1) * .75;
3503                 opacity = mmin(mmax(opacity, 0), 1);
3504                 params["stroke-width"] == null && (width = a["stroke-width"]);
3505                 params["stroke-width"] && (stroke.weight = width);
3506                 width && width < 1 && (opacity *= width) && (stroke.weight = 1);
3507                 stroke.opacity = opacity;
3508                 
3509                 params["stroke-linejoin"] && (stroke.joinstyle = params["stroke-linejoin"] || "miter");
3510                 stroke.miterlimit = params["stroke-miterlimit"] || 8;
3511                 params["stroke-linecap"] && (stroke.endcap = params["stroke-linecap"] == "butt" ? "flat" : params["stroke-linecap"] == "square" ? "square" : "round");
3512                 if (params["stroke-dasharray"]) {
3513                     var dasharray = {
3514                         "-": "shortdash",
3515                         ".": "shortdot",
3516                         "-.": "shortdashdot",
3517                         "-..": "shortdashdotdot",
3518                         ". ": "dot",
3519                         "- ": "dash",
3520                         "--": "longdash",
3521                         "- .": "dashdot",
3522                         "--.": "longdashdot",
3523                         "--..": "longdashdotdot"
3524                     };
3525                     stroke.dashstyle = dasharray[has](params["stroke-dasharray"]) ? dasharray[params["stroke-dasharray"]] : E;
3526                 }
3527                 newstroke && node.appendChild(stroke);
3528             }
3529             if (res.type == "text") {
3530                 res.paper.canvas.style.display = E;
3531                 var span = res.paper.span,
3532                     m = 100,
3533                     fontSize = a.font && a.font.match(/\d+(?:\.\d*)?(?=px)/);
3534                 s = span.style;
3535                 a.font && (s.font = a.font);
3536                 a["font-family"] && (s.fontFamily = a["font-family"]);
3537                 a["font-weight"] && (s.fontWeight = a["font-weight"]);
3538                 a["font-style"] && (s.fontStyle = a["font-style"]);
3539                 fontSize = toFloat(fontSize ? fontSize[0] : a["font-size"]);
3540                 s.fontSize = fontSize * m + "px";
3541                 res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/</g, "&#60;").replace(/&/g, "&#38;").replace(/\n/g, "<br>"));
3542                 var brect = span.getBoundingClientRect();
3543                 res.W = a.w = (brect.right - brect.left) / m;
3544                 res.H = a.h = (brect.bottom - brect.top) / m;
3545                 res.paper.canvas.style.display = "none";
3546                 res.X = a.x;
3547                 res.Y = a.y + res.H / 2;
3548
3549                 ("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1));
3550                 var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"];
3551                 for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) {
3552                     res._.dirty = 1;
3553                     break;
3554                 }
3555                 
3556                 // text-anchor emulation
3557                 switch (a["text-anchor"]) {
3558                     case "start":
3559                         res.textpath.style["v-text-align"] = "left";
3560                         res.bbx = res.W / 2;
3561                     break;
3562                     case "end":
3563                         res.textpath.style["v-text-align"] = "right";
3564                         res.bbx = -res.W / 2;
3565                     break;
3566                     default:
3567                         res.textpath.style["v-text-align"] = "center";
3568                         res.bbx = 0;
3569                     break;
3570                 }
3571                 res.textpath.style["v-text-kern"] = true;
3572             }
3573             res.paper.canvas.style.display = E;
3574         };
3575         addGradientFill = function (o, gradient, fill) {
3576             o.attrs = o.attrs || {};
3577             var attrs = o.attrs,
3578                 opacity,
3579                 oindex,
3580                 type = "linear",
3581                 fxfy = ".5 .5";
3582             o.attrs.gradient = gradient;
3583             gradient = Str(gradient).replace(radial_gradient, function (all, fx, fy) {
3584                 type = "radial";
3585                 if (fx && fy) {
3586                     fx = toFloat(fx);
3587                     fy = toFloat(fy);
3588                     pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * ((fy > .5) * 2 - 1) + .5);
3589                     fxfy = fx + S + fy;
3590                 }
3591                 return E;
3592             });
3593             gradient = gradient.split(/\s*\-\s*/);
3594             if (type == "linear") {
3595                 var angle = gradient.shift();
3596                 angle = -toFloat(angle);
3597                 if (isNaN(angle)) {
3598                     return null;
3599                 }
3600             }
3601             var dots = parseDots(gradient);
3602             if (!dots) {
3603                 return null;
3604             }
3605             o = o.shape || o.node;
3606             if (dots.length) {
3607                 o.removeChild(fill);
3608                 fill.on = true;
3609                 fill.method = "none";
3610                 fill.color = dots[0].color;
3611                 fill.color2 = dots[dots.length - 1].color;
3612                 var clrs = [];
3613                 for (var i = 0, ii = dots.length; i < ii; i++) {
3614                     dots[i].offset && clrs.push(dots[i].offset + S + dots[i].color);
3615                 }
3616                 fill.colors = clrs.length ? clrs.join() : "0% " + fill.color;
3617                 if (type == "radial") {
3618                     fill.type = "gradientTitle";
3619                     fill.focus = "100%";
3620                     fill.focussize = "0 0";
3621                     fill.focusposition = fxfy;
3622                     fill.angle = 0;
3623                 } else {
3624                     // fill.rotate= true;
3625                     fill.type = "gradient";
3626                     fill.angle = (270 - angle) % 360;
3627                 }
3628                 o.appendChild(fill);
3629             }
3630             return 1;
3631         };
3632         Element = function (node, vml) {
3633             this[0] = this.node = node;
3634             node.raphael = true;
3635             this.id = R._oid++;
3636             node.raphaelid = this.id;
3637             this.X = 0;
3638             this.Y = 0;
3639             this.attrs = {};
3640             this.paper = vml;
3641             this.matrix = new Matrix;
3642             this._ = {
3643                 transform: [],
3644                 sx: 1,
3645                 sy: 1,
3646                 dx: 0,
3647                 dy: 0,
3648                 deg: 0,
3649                 dirty: 1,
3650                 dirtyT: 1
3651             };
3652             !vml.bottom && (vml.bottom = this);
3653             this.prev = vml.top;
3654             vml.top && (vml.top.next = this);
3655             vml.top = this;
3656             this.next = null;
3657         };
3658         elproto = Element.prototype;
3659         elproto.transform = function (tstr) {
3660             if (tstr == null) {
3661                 return this._.transform;
3662             }
3663             extractTransform(this, tstr);
3664             var matrix = this.matrix.clone(),
3665                 vbs = this.paper._viewBoxShift,
3666                 skew = this.skew,
3667                 o = this.node,
3668                 split,
3669                 isGrad = Str(this.attrs.fill).indexOf("-") + 1;
3670             matrix.translate(-.5, -.5);
3671             if (vbs) {
3672                 matrix.scale(vbs.scale, vbs.scale, -1, -1);
3673                 matrix.translate(vbs.dx, vbs.dy);
3674             }
3675             if (isGrad || this.type == "image") {
3676                 skew.matrix = "1 0 0 1";
3677                 skew.offset = "0 0";
3678                 // just translation?
3679                 if (isGrad || !(split = matrix.split()).isSimple) {
3680                     o.style.filter = matrix.toFilter();
3681                     var bb = this.getBBox(),
3682                         bbt = this.getBBox(1),
3683                         dx = bb.x - bbt.x,
3684                         dy = bb.y - bbt.y;
3685                     o.coordorigin = (dx * -zoom) + S + (dy * -zoom);
3686                     setCoords(this, 1, 1, dx, dy, 0);
3687                 } else {
3688                     o.style.filter = E;
3689                     setCoords(this, split.scalex, split.scaley, split.dx, split.dy, split.rotate);
3690                 }
3691             } else {
3692                 o.style.filter = E;
3693                 skew.matrix = Str(matrix);
3694                 skew.offset = matrix.offset();
3695             }
3696             return this;
3697         };
3698         elproto.rotate = function (deg, cx, cy) {
3699             if (this.removed) {
3700                 return this;
3701             }
3702             if (deg == null) {
3703                 return;
3704             }
3705             deg = Str(deg).split(separator);
3706             if (deg.length - 1) {
3707                 cx = toFloat(deg[1]);
3708                 cy = toFloat(deg[2]);
3709             }
3710             deg = toFloat(deg[0]);
3711             (cy == null) && (cx = cy);
3712             if (cx == null || cy == null) {
3713                 var bbox = this.getBBox(1);
3714                 cx = bbox.x + bbox.width / 2;
3715                 cy = bbox.y + bbox.height / 2;
3716             }
3717             this._.dirtyT = 1;
3718             this.transform(this._.transform.concat([["r", deg, cx, cy]]));
3719             return this;
3720         };
3721         elproto.translate = function (dx, dy) {
3722             if (this.removed) {
3723                 return this;
3724             }
3725             dx = Str(dx).split(separator);
3726             if (dx.length - 1) {
3727                 dy = toFloat(dx[1]);
3728             }
3729             dx = toFloat(dx[0]) || 0;
3730             dy = +dy || 0;
3731             if (this._.bbox) {
3732                 this._.bbox.x += dx;
3733                 this._.bbox.y += dy;
3734             }
3735             this.transform(this._.transform.concat([["t", dx, dy]]));
3736             return this;
3737         };
3738         elproto.scale = function (sx, sy, cx, cy) {
3739             if (this.removed) {
3740                 return this;
3741             }
3742             sx = Str(sx).split(separator);
3743             if (sx.length - 1) {
3744                 sy = toFloat(sx[1]);
3745                 cx = toFloat(sx[2]);
3746                 cy = toFloat(sx[3]);
3747                 isNaN(cx) && (cx = null);
3748                 isNaN(cy) && (cy = null);
3749             }
3750             sx = toFloat(sx[0]);
3751             (sy == null) && (sy = sx);
3752             (cy == null) && (cx = cy);
3753             if (cx == null || cy == null) {
3754                 var bbox = this.getBBox(1);
3755             }
3756             cx = cx == null ? bbox.x + bbox.width / 2 : cx;
3757             cy = cy == null ? bbox.y + bbox.height / 2 : cy;
3758             
3759             this.transform(this._.transform.concat([["s", sx, sy, cx, cy]]));
3760             this._.dirtyT = 1;
3761             return this;
3762         };
3763         elproto.hide = function () {
3764             !this.removed && (this.node.style.display = "none");
3765             return this;
3766         };
3767         elproto.show = function () {
3768             !this.removed && (this.node.style.display = E);
3769             return this;
3770         };
3771         elproto._getBBox = function () {
3772             if (this.removed) {
3773                 return {};
3774             }
3775             if (this.type == "text") {
3776                 return {
3777                     x: this.X + (this.bbx || 0) - this.W / 2,
3778                     y: this.Y - this.H,
3779                     width: this.W,
3780                     height: this.H
3781                 };
3782             } else {
3783                 return pathDimensions(this.attrs.path);
3784             }
3785         };
3786         elproto.remove = function () {
3787             if (this.removed) {
3788                 return;
3789             }
3790             eve.unbind("*.*." + this.id);
3791             tear(this, this.paper);
3792             this.node.parentNode.removeChild(this.node);
3793             this.shape && this.shape.parentNode.removeChild(this.shape);
3794             for (var i in this) {
3795                 delete this[i];
3796             }
3797             this.removed = true;
3798         };
3799         elproto.attr = function (name, value) {
3800             if (this.removed) {
3801                 return this;
3802             }
3803             if (name == null) {
3804                 var res = {};
3805                 for (var a in this.attrs) if (this.attrs[has](a)) {
3806                     res[a] = this.attrs[a];
3807                 }
3808                 res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
3809                 res.transform = this._.transform;
3810                 return res;
3811             }
3812             if (value == null && R.is(name, "string")) {
3813                 if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
3814                     return this.attrs.gradient;
3815                 }
3816                 var names = name.split(separator),
3817                     out = {};
3818                 for (var i = 0, ii = names.length; i < ii; i++) {
3819                     name = names[i];
3820                     if (name in this.attrs) {
3821                         out[name] = this.attrs[name];
3822                     } else if (R.is(this.paper.customAttributes[name], "function")) {
3823                         out[name] = this.paper.customAttributes[name].def;
3824                     } else {
3825                         out[name] = availableAttrs[name];
3826                     }
3827                 }
3828                 return ii - 1 ? out : out[names[0]];
3829             }
3830             if (this.attrs && value == null && R.is(name, array)) {
3831                 out = {};
3832                 for (i = 0, ii = name.length; i < ii; i++) {
3833                     out[name[i]] = this.attr(name[i]);
3834                 }
3835                 return out;
3836             }
3837             var params;
3838             if (value != null) {
3839                 params = {};
3840                 params[name] = value;
3841             }
3842             value == null && R.is(name, "object") && (params = name);
3843             for (var key in params) {
3844                 eve("attr." + key + "." + this.id, this, params[key]);
3845             }
3846             if (params) {
3847                 for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
3848                     var par = this.paper.customAttributes[key].apply(this, [][concat](params[key]));
3849                     this.attrs[key] = params[key];
3850                     for (var subkey in par) if (par[has](subkey)) {
3851                         params[subkey] = par[subkey];
3852                     }
3853                 }
3854                 // this.paper.canvas.style.display = "none";
3855                 if (params.text && this.type == "text") {
3856                     this.textpath.string = params.text;
3857                 }
3858                 setFillAndStroke(this, params);
3859                 // this.paper.canvas.style.display = E;
3860             }
3861             return this;
3862         };
3863         elproto.toFront = function () {
3864             !this.removed && this.node.parentNode.appendChild(this.node);
3865             this.paper && this.paper.top != this && tofront(this, this.paper);
3866             return this;
3867         };
3868         elproto.toBack = function () {
3869             if (this.removed) {
3870                 return this;
3871             }
3872             if (this.node.parentNode.firstChild != this.node) {
3873                 this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
3874                 toback(this, this.paper);
3875             }
3876             return this;
3877         };
3878         elproto.insertAfter = function (element) {
3879             if (this.removed) {
3880                 return this;
3881             }
3882             if (element.constructor == Set) {
3883                 element = element[element.length - 1];
3884             }
3885             if (element.node.nextSibling) {
3886                 element.node.parentNode.insertBefore(this.node, element.node.nextSibling);
3887             } else {
3888                 element.node.parentNode.appendChild(this.node);
3889             }
3890             insertafter(this, element, this.paper);
3891             return this;
3892         };
3893         elproto.insertBefore = function (element) {
3894             if (this.removed) {
3895                 return this;
3896             }
3897             if (element.constructor == Set) {
3898                 element = element[0];
3899             }
3900             element.node.parentNode.insertBefore(this.node, element.node);
3901             insertbefore(this, element, this.paper);
3902             return this;
3903         };
3904         elproto.blur = function (size) {
3905             var s = this.node.runtimeStyle,
3906                 f = s.filter;
3907             f = f.replace(blurregexp, E);
3908             if (+size !== 0) {
3909                 this.attrs.blur = size;
3910                 s.filter = f + S + ms + ".Blur(pixelradius=" + (+size || 1.5) + ")";
3911                 s.margin = R.format("-{0}px 0 0 -{0}px", round(+size || 1.5));
3912             } else {
3913                 s.filter = f;
3914                 s.margin = 0;
3915                 delete this.attrs.blur;
3916             }
3917         };
3918
3919         thePath = function (pathString, vml) {
3920             var el = createNode("shape");
3921             el.style.cssText = cssDot;
3922             el.coordsize = zoom + S + zoom;
3923             el.coordorigin = vml.coordorigin;
3924             var p = new Element(el, vml),
3925                 attr = {fill: "none", stroke: "#000"};
3926             pathString && (attr.path = pathString);
3927             p.type = "path";
3928             p.path = [];
3929             p.Path = E;
3930             setFillAndStroke(p, attr);
3931             vml.canvas.appendChild(el);
3932             var skew = createNode("skew");
3933             skew.on = true;
3934             el.appendChild(skew);
3935             p.skew = skew;
3936             p.transform(E);
3937             return p;
3938         };
3939         theRect = function (vml, x, y, w, h, r) {
3940             var path = rectPath(x, y, w, h, r),
3941                 res = vml.path(path),
3942                 a = res.attrs;
3943             res.X = a.x = x;
3944             res.Y = a.y = y;
3945             res.W = a.width = w;
3946             res.H = a.height = h;
3947             a.r = r;
3948             a.path = path;
3949             res.type = "rect";
3950             return res;
3951         };
3952         theEllipse = function (vml, x, y, rx, ry) {
3953             var res = vml.path(),
3954                 a = res.attrs;
3955             res.X = x - rx;
3956             res.Y = y - ry;
3957             res.W = rx * 2;
3958             res.H = ry * 2;
3959             res.type = "ellipse";
3960             setFillAndStroke(res, {
3961                 cx: x,
3962                 cy: y,
3963                 rx: rx,
3964                 ry: ry
3965             });
3966             return res;
3967         };
3968         theCircle = function (vml, x, y, r) {
3969             var res = vml.path(),
3970                 a = res.attrs;
3971             res.X = x - r;
3972             res.Y = y - r;
3973             res.W = res.H = r * 2;
3974             res.type = "circle";
3975             setFillAndStroke(res, {
3976                 cx: x,
3977                 cy: y,
3978                 r: r
3979             });
3980             return res;
3981         };
3982         theImage = function (vml, src, x, y, w, h) {
3983             var path = rectPath(x, y, w, h),
3984                 res = vml.path(path).attr({stroke: "none"}),
3985                 a = res.attrs,
3986                 node = res.node,
3987                 fill = node.getElementsByTagName(fillString)[0];
3988             a.src = src;
3989             res.X = a.x = x;
3990             res.Y = a.y = y;
3991             res.W = a.width = w;
3992             res.H = a.height = h;
3993             a.path = path;
3994             res.type = "image";
3995             fill.parentNode == node && node.removeChild(fill);
3996             fill.rotate = true;
3997             fill.src = src;
3998             fill.type = "tile";
3999             res._.fillpos = [x, y];
4000             res._.fillsize = [w, h];
4001             node.appendChild(fill);
4002             setCoords(res, 1, 1, 0, 0, 0);
4003             return res;
4004         };
4005         theText = function (vml, x, y, text) {
4006             var el = createNode("shape"),
4007                 path = createNode("path"),
4008                 o = createNode("textpath");
4009             x = x || 0;
4010             y = y || 0;
4011             text = text || "";
4012             path.v = R.format("m{0},{1}l{2},{1}", round(x * zoom), round(y * zoom), round(x * zoom) + 1);
4013             path.textpathok = true;
4014             o.string = Str(text);
4015             o.on = true;
4016             el.style.cssText = "position:absolute;left:0;top:0;width:1px;height:1px";
4017             el.coordsize = zoom + S + zoom;
4018             el.coordorigin = "0 0";
4019             var p = new Element(el, vml),
4020                 attr = {fill: "#000", stroke: "none", font: availableAttrs.font, text: text};
4021             p.shape = el;
4022             p.path = path;
4023             p.textpath = o;
4024             p.type = "text";
4025             p.attrs.text = Str(text);
4026             p.attrs.x = x;
4027             p.attrs.y = y;
4028             p.attrs.w = 1;
4029             p.attrs.h = 1;
4030             setFillAndStroke(p, attr);
4031             el.appendChild(o);
4032             el.appendChild(path);
4033             vml.canvas.appendChild(el);
4034             var skew = createNode("skew");
4035             skew.on = true;
4036             el.appendChild(skew);
4037             p.skew = skew;
4038             p.transform(E);
4039             return p;
4040         };
4041         setSize = function (width, height) {
4042             var cs = this.canvas.style;
4043             this.width = width;
4044             this.height = height;
4045             width == +width && (width += "px");
4046             height == +height && (height += "px");
4047             cs.width = width;
4048             cs.height = height;
4049             cs.clip = "rect(0 " + width + " " + height + " 0)";
4050             if (this._viewBox) {
4051                 setViewBox.apply(this, this._viewBox);
4052             }
4053             return this;
4054         };
4055         setViewBox = function (x, y, w, h, fit) {
4056             eve("setViewBox", this, this._viewBox, [x, y, w, h, fit]);
4057             var width = this.width,
4058                 height = this.height,
4059                 size = 1 / mmax(w / width, h / height),
4060                 H, W;
4061             if (fit) {
4062                 H = height / h;
4063                 W = width / w;
4064                 if (w * H < width) {
4065                     x -= (width - w * H) / 2 / H;
4066                 }
4067                 if (h * W < height) {
4068                     y -= (height - h * W) / 2 / W;
4069                 }
4070             }
4071             this._viewBox = [x, y, w, h, !!fit];
4072             this._viewBoxShift = {
4073                 dx: -x,
4074                 dy: -y,
4075                 scale: size
4076             };
4077             this.forEach(function (el) {
4078                 el.transform("...");
4079             });
4080             return this;
4081         };
4082         var createNode,
4083             initWin = function (win) {
4084                 var doc = win.document;
4085                 doc.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
4086                 try {
4087                     !doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
4088                     createNode = function (tagName) {
4089                         return doc.createElement('<rvml:' + tagName + ' class="rvml">');
4090                     };
4091                 } catch (e) {
4092                     createNode = function (tagName) {
4093                         return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
4094                     };
4095                 }
4096             };
4097         initWin(g.win);
4098         create = function () {
4099             var con = getContainer[apply](0, arguments),
4100                 container = con.container,
4101                 height = con.height,
4102                 s,
4103                 width = con.width,
4104                 x = con.x,
4105                 y = con.y;
4106             if (!container) {
4107                 throw new Error("VML container not found.");
4108             }
4109             var res = new Paper,
4110                 c = res.canvas = g.doc.createElement("div"),
4111                 cs = c.style;
4112             x = x || 0;
4113             y = y || 0;
4114             width = width || 512;
4115             height = height || 342;
4116             res.width = width;
4117             res.height = height;
4118             width == +width && (width += "px");
4119             height == +height && (height += "px");
4120             res.coordsize = zoom * 1e3 + S + zoom * 1e3;
4121             res.coordorigin = "0 0";
4122             res.span = g.doc.createElement("span");
4123             res.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";
4124             c.appendChild(res.span);
4125             cs.cssText = R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", width, height);
4126             if (container == 1) {
4127                 g.doc.body.appendChild(c);
4128                 cs.left = x + "px";
4129                 cs.top = y + "px";
4130                 cs.position = "absolute";
4131             } else {
4132                 if (container.firstChild) {
4133                     container.insertBefore(c, container.firstChild);
4134                 } else {
4135                     container.appendChild(c);
4136                 }
4137             }
4138             plugins.call(res, res, R.fn);
4139             res.renderfix = fun;
4140             return res;
4141         };
4142         paperproto.clear = function () {
4143             eve("clear", this);
4144             this.canvas.innerHTML = E;
4145             this.span = g.doc.createElement("span");
4146             this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";
4147             this.canvas.appendChild(this.span);
4148             this.bottom = this.top = null;
4149         };
4150         paperproto.remove = function () {
4151             eve("remove", this);
4152             this.canvas.parentNode.removeChild(this.canvas);
4153             for (var i in this) {
4154                 this[i] = removed(i);
4155             }
4156             return true;
4157         };
4158     }
4159  
4160     // WebKit rendering bug workaround method
4161     var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
4162     if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") ||
4163         (navigator.vendor == "Google Inc." && version && version[1] < 8)) {
4164         /*\
4165          * Paper.safari
4166          [ method ]
4167          **
4168          * There is an inconvenient rendering bug in Safari (WebKit):
4169          * sometimes the rendering should be forced.
4170          * This method should help with dealing with this bug.
4171         \*/
4172         paperproto.safari = function () {
4173             var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"});
4174             setTimeout(function () {rect.remove();});
4175         };
4176     } else {
4177         paperproto.safari = fun;
4178     }
4179  
4180     // Events
4181     var preventDefault = function () {
4182         this.returnValue = false;
4183     },
4184     preventTouch = function () {
4185         return this.originalEvent.preventDefault();
4186     },
4187     stopPropagation = function () {
4188         this.cancelBubble = true;
4189     },
4190     stopTouch = function () {
4191         return this.originalEvent.stopPropagation();
4192     },
4193     addEvent = (function () {
4194         if (g.doc.addEventListener) {
4195             return function (obj, type, fn, element) {
4196                 var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
4197                     f = function (e) {
4198                         var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
4199                             scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
4200                             x = e.clientX + scrollX,
4201                             y = e.clientY + scrollY;
4202                     if (supportsTouch && touchMap[has](type)) {
4203                         for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
4204                             if (e.targetTouches[i].target == obj) {
4205                                 var olde = e;
4206                                 e = e.targetTouches[i];
4207                                 e.originalEvent = olde;
4208                                 e.preventDefault = preventTouch;
4209                                 e.stopPropagation = stopTouch;
4210                                 break;
4211                             }
4212                         }
4213                     }
4214                     return fn.call(element, e, x, y);
4215                 };
4216                 obj.addEventListener(realName, f, false);
4217                 return function () {
4218                     obj.removeEventListener(realName, f, false);
4219                     return true;
4220                 };
4221             };
4222         } else if (g.doc.attachEvent) {
4223             return function (obj, type, fn, element) {
4224                 var f = function (e) {
4225                     e = e || g.win.event;
4226                     var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
4227                         scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
4228                         x = e.clientX + scrollX,
4229                         y = e.clientY + scrollY;
4230                     e.preventDefault = e.preventDefault || preventDefault;
4231                     e.stopPropagation = e.stopPropagation || stopPropagation;
4232                     return fn.call(element, e, x, y);
4233                 };
4234                 obj.attachEvent("on" + type, f);
4235                 var detacher = function () {
4236                     obj.detachEvent("on" + type, f);
4237                     return true;
4238                 };
4239                 return detacher;
4240             };
4241         }
4242     })(),
4243     drag = [],
4244     dragMove = function (e) {
4245         var x = e.clientX,
4246             y = e.clientY,
4247             scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
4248             scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
4249             dragi,
4250             j = drag.length;
4251         while (j--) {
4252             dragi = drag[j];
4253             if (supportsTouch) {
4254                 var i = e.touches.length,
4255                     touch;
4256                 while (i--) {
4257                     touch = e.touches[i];
4258                     if (touch.identifier == dragi.el._drag.id) {
4259                         x = touch.clientX;
4260                         y = touch.clientY;
4261                         (e.originalEvent ? e.originalEvent : e).preventDefault();
4262                         break;
4263                     }
4264                 }
4265             } else {
4266                 e.preventDefault();
4267             }
4268             var node = dragi.el.node,
4269                 o,
4270                 next = node.nextSibling,
4271                 parent = node.parentNode,
4272                 display = node.style.display;
4273             g.win.opera && parent.removeChild(node);
4274             node.style.display = "none";
4275             o = dragi.el.paper.getElementByPoint(x, y);
4276             node.style.display = display;
4277             g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
4278             o && eve("drag.over." + dragi.el.id, dragi.el, o);
4279             x += scrollX;
4280             y += scrollY;
4281             eve("drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e);
4282         }
4283     },
4284     dragUp = function (e) {
4285         R.unmousemove(dragMove).unmouseup(dragUp);
4286         var i = drag.length,
4287             dragi;
4288         while (i--) {
4289             dragi = drag[i];
4290             dragi.el._drag = {};
4291             eve("drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e);
4292         }
4293         drag = [];
4294     };
4295     for (var i = events.length; i--;) {
4296         (function (eventName) {
4297             R[eventName] = Element.prototype[eventName] = function (fn, scope) {
4298                 if (R.is(fn, "function")) {
4299                     this.events = this.events || [];
4300                     this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)});
4301                 }
4302                 return this;
4303             };
4304             R["un" + eventName] = Element.prototype["un" + eventName] = function (fn) {
4305                 var events = this.events,
4306                     l = events.length;
4307                 while (l--) if (events[l].name == eventName && events[l].f == fn) {
4308                     events[l].unbind();
4309                     events.splice(l, 1);
4310                     !events.length && delete this.events;
4311                     return this;
4312                 }
4313                 return this;
4314             };
4315         })(events[i]);
4316     }
4317     /*\
4318      * Element.hover
4319      [ method ]
4320      **
4321      * Adds event handlers for hover for the element.
4322      > Parameters
4323      - f_in (function) handler for hover in
4324      - f_out (function) handler for hover out
4325      - icontext (object) #optional context for hover in handler
4326      - ocontext (object) #optional context for hover out handler
4327      = (object) @Element
4328     \*/
4329     elproto.hover = function (f_in, f_out, scope_in, scope_out) {
4330         return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in);
4331     };
4332     /*\
4333      * Element.unhover
4334      [ method ]
4335      **
4336      * Removes event handlers for hover for the element.
4337      > Parameters
4338      - f_in (function) handler for hover in
4339      - f_out (function) handler for hover out
4340      = (object) @Element
4341     \*/
4342     elproto.unhover = function (f_in, f_out) {
4343         return this.unmouseover(f_in).unmouseout(f_out);
4344     };
4345     /*\
4346      * Element.drag
4347      [ method ]
4348      **
4349      * Adds event handlers for drag of the element.
4350      > Parameters
4351      - onmove (function) handler for moving
4352      - onstart (function) handler for drag start
4353      - onend (function) handler for drag end
4354      - mcontext (object) #optional context for moving handler
4355      - scontext (object) #optional context for drag start handler
4356      - econtext (object) #optional context for drag end handler
4357      * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start, 
4358      * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element 
4359      * `drag.over.<id>` will be fired as well.
4360      *
4361      * Start event and start handler will be called in specified context or in context of the element with following parameters:
4362      o x (number) x position of the mouse
4363      o y (number) y position of the mouse
4364      o event (object) DOM event object
4365      * Move event and move handler will be called in specified context or in context of the element with following parameters:
4366      o dx (number) shift by x from the start point
4367      o dy (number) shift by y from the start point
4368      o x (number) x position of the mouse
4369      o y (number) y position of the mouse
4370      o event (object) DOM event object
4371      * End event and end handler will be called in specified context or in context of the element with following parameters:
4372      o event (object) DOM event object
4373      = (object) @Element
4374     \*/
4375     elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
4376         function start(e) {
4377             (e.originalEvent || e).preventDefault();
4378             var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
4379                 scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
4380             this._drag.x = e.clientX + scrollX;
4381             this._drag.y = e.clientY + scrollY;
4382             this._drag.id = e.identifier;
4383             !drag.length && R.mousemove(dragMove).mouseup(dragUp);
4384             drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
4385             onstart && eve.on("drag.start." + this.id, onstart);
4386             onmove && eve.on("drag.move." + this.id, onmove);
4387             onend && eve.on("drag.end." + this.id, onend);
4388             eve("drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e);
4389         }
4390         this._drag = {};
4391         this.mousedown(start);
4392         return this;
4393     };
4394     /*\
4395      * Element.onDragOver
4396      [ method ]
4397      **
4398      * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id).
4399      > Parameters
4400      - f (function) handler for event
4401     \*/
4402     elproto.onDragOver = function (f) {
4403         f ? eve.on("drag.over." + this.id, f) : eve.unbind("drag.over." + this.id);
4404     };
4405     /*\
4406      * Element.undrag
4407      [ method ]
4408      **
4409      * Removes all drag event handlers from given element.
4410     \*/
4411     elproto.undrag = function () {
4412         var i = drag.length;
4413         while (i--) if (drag[i].el == this) {
4414             R.unmousedown(drag[i].start);
4415             drag.splice(i++, 1);
4416             eve.unbind("drag.*." + this.id);
4417         }
4418         !drag.length && R.unmousemove(dragMove).unmouseup(dragUp);
4419     };
4420     /*\
4421      * Paper.circle
4422      [ method ]
4423      **
4424      * Draws a circle.
4425      **
4426      > Parameters
4427      **
4428      - x (number) x coordinate of the centre
4429      - y (number) y coordinate of the centre
4430      - r (number) radius
4431      = (object) Raphaël element object with type “circle”
4432      **
4433      > Usage
4434      | var c = paper.circle(50, 50, 40);
4435     \*/
4436     paperproto.circle = function (x, y, r) {
4437         return theCircle(this, x || 0, y || 0, r || 0);
4438     };
4439     /*\
4440      * Paper.rect
4441      [ method ]
4442      *
4443      * Draws a rectangle.
4444      **
4445      > Parameters
4446      **
4447      - x (number) x coordinate of the top left corner
4448      - y (number) y coordinate of the top left corner
4449      - width (number) width
4450      - height (number) height
4451      - r (number) #optional radius for rounded corners, default is 0
4452      = (object) Raphaël element object with type “rect”
4453      **
4454      > Usage
4455      | // regular rectangle
4456      | var c = paper.rect(10, 10, 50, 50);
4457      | // rectangle with rounded corners
4458      | var c = paper.rect(40, 40, 50, 50, 10);
4459     \*/
4460     paperproto.rect = function (x, y, w, h, r) {
4461         return theRect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
4462     };
4463     /*\
4464      * Paper.ellipse
4465      [ method ]
4466      **
4467      * Draws an ellipse.
4468      **
4469      > Parameters
4470      **
4471      - x (number) x coordinate of the centre
4472      - y (number) y coordinate of the centre
4473      - rx (number) horizontal radius
4474      - ry (number) vertical radius
4475      = (object) Raphaël element object with type “ellipse”
4476      **
4477      > Usage
4478      | var c = paper.ellipse(50, 50, 40, 20);
4479     \*/
4480     paperproto.ellipse = function (x, y, rx, ry) {
4481         return theEllipse(this, x || 0, y || 0, rx || 0, ry || 0);
4482     };
4483     /*\
4484      * Paper.path
4485      [ method ]
4486      **
4487      * Creates a path element by given path data string.
4488      **
4489      > Parameters
4490      **
4491      - pathString (string) path data in SVG path string format.
4492      = (object) Raphaël element object with type “ellipse”
4493      # Details of a path's data attribute's format are described in the <a href="http://www.w3.org/TR/SVG/paths.html#PathData">SVG specification</a>.
4494      **
4495      > Usage
4496      | var c = paper.path("M10 10L90 90");
4497      | // draw a diagonal line:
4498      | // move to 10,10, line to 90,90
4499     \*/
4500     paperproto.path = function (pathString) {
4501         pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
4502         return thePath(R.format[apply](R, arguments), this);
4503     };
4504     /*\
4505      * Paper.image
4506      [ method ]
4507      **
4508      * Embeds an image into the surface.
4509      **
4510      > Parameters
4511      **
4512      - src (string) URI of the source image
4513      - x (number) x coordinate position
4514      - y (number) y coordinate position
4515      - width (number) width of the image
4516      - height (number) height of the image
4517      = (object) Raphaël element object with type “image”
4518      **
4519      > Usage
4520      | var c = paper.image("apple.png", 10, 10, 80, 80);
4521     \*/
4522     paperproto.image = function (src, x, y, w, h) {
4523         return theImage(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
4524     };
4525     /*\
4526      * Paper.text
4527      [ method ]
4528      **
4529      * Draws a text string. If you need line breaks, put “\n” in the string.
4530      **
4531      > Parameters
4532      **
4533      - x (number) x coordinate position
4534      - y (number) y coordinate position
4535      - text (string) The text string to draw
4536      = (object) Raphaël element object with type “text”
4537      **
4538      > Usage
4539      | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
4540     \*/
4541     paperproto.text = function (x, y, text) {
4542         return theText(this, x || 0, y || 0, Str(text));
4543     };
4544     /*\
4545      * Paper.set
4546      [ method ]
4547      **
4548      * Creates array-like object to keep and operate several elements at once.
4549      * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements.
4550      * Sets act as pseudo elements — all methods available to an element can be used on a set.
4551      = (object) array-like object that represents set of elements
4552      **
4553      > Usage
4554      | var st = paper.set();
4555      | st.push(
4556      |     paper.circle(10, 10, 5),
4557      |     paper.circle(30, 10, 5)
4558      | );
4559      | st.attr({fill: "red"});
4560     \*/
4561     paperproto.set = function (itemsArray) {
4562         !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
4563         return new Set(itemsArray);
4564     };
4565     /*\
4566      * Paper.setSize
4567      [ method ]
4568      **
4569      * If you need to change dimensions of the canvas call this method
4570      **
4571      > Parameters
4572      **
4573      - width (number) new width of the canvas
4574      - height (number) new height of the canvas
4575      > Usage
4576      | var st = paper.set();
4577      | st.push(
4578      |     paper.circle(10, 10, 5),
4579      |     paper.circle(30, 10, 5)
4580      | );
4581      | st.attr({fill: "red"});
4582     \*/
4583     paperproto.setSize = setSize;
4584     /*\
4585      * Paper.setViewBox
4586      [ method ]
4587      **
4588      * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by 
4589      * specifying new boundaries.
4590      **
4591      > Parameters
4592      **
4593      x, y, w, h, fit
4594      - x (number) new x position, default is `0`
4595      - y (number) new y position, default is `0`
4596      - w (number) new width of the canvas
4597      - h (number) new height of the canvas
4598      - fit (boolean) `true` if you want graphics to fit into new boundary box
4599     \*/
4600     paperproto.setViewBox = setViewBox;
4601     /*\
4602      * Paper.top
4603      [ property ]
4604      **
4605      * Points to the topmost element on the paper
4606     \*/
4607     /*\
4608      * Paper.bottom
4609      [ property ]
4610      **
4611      * Points to the bottom element on the paper
4612     \*/
4613     paperproto.top = paperproto.bottom = null;
4614     /*\
4615      * Paper.raphael
4616      [ property ]
4617      **
4618      * Points to the @Raphael object/function
4619     \*/
4620     paperproto.raphael = R;
4621     var getOffset = function (elem) {
4622         var box = elem.getBoundingClientRect(),
4623             doc = elem.ownerDocument,
4624             body = doc.body,
4625             docElem = doc.documentElement,
4626             clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
4627             top  = box.top  + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop,
4628             left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
4629         return {
4630             y: top,
4631             x: left
4632         };
4633     };
4634     /*\
4635      * Paper.getElementByPoint
4636      [ method ]
4637      **
4638      * Returns you topmost element under given point.
4639      **
4640      = (object) Raphaël element object
4641      > Parameters
4642      **
4643      - x (number) x coordinate from the top left corner of the window
4644      - y (number) y coordinate from the top left corner of the window
4645      > Usage
4646      | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"});
4647     \*/
4648     paperproto.getElementByPoint = function (x, y) {
4649         var paper = this,
4650             svg = paper.canvas,
4651             target = g.doc.elementFromPoint(x, y);
4652         if (g.win.opera && target.tagName == "svg") {
4653             var so = getOffset(svg),
4654                 sr = svg.createSVGRect();
4655             sr.x = x - so.x;
4656             sr.y = y - so.y;
4657             sr.width = sr.height = 1;
4658             var hits = svg.getIntersectionList(sr, null);
4659             if (hits.length) {
4660                 target = hits[hits.length - 1];
4661             }
4662         }
4663         if (!target) {
4664             return null;
4665         }
4666         while (target.parentNode && target != svg.parentNode && !target.raphael) {
4667             target = target.parentNode;
4668         }
4669         target == paper.canvas.parentNode && (target = svg);
4670         target = target && target.raphael ? paper.getById(target.raphaelid) : null;
4671         return target;
4672     };
4673     /*\
4674      * Paper.getById
4675      [ method ]
4676      **
4677      * Returns you element by its internal ID.
4678      **
4679      > Parameters
4680      **
4681      - id (number) id
4682      = (object) Raphaël element object
4683     \*/
4684     paperproto.getById = function (id) {
4685         var bot = this.bottom;
4686         while (bot) {
4687             if (bot.id == id) {
4688                 return bot;
4689             }
4690             bot = bot.next;
4691         }
4692         return null;
4693     };
4694     /*\
4695      * Paper.forEach
4696      [ method ]
4697      **
4698      * Executes given function for each element on the paper
4699      *
4700      * If callback function returns `false` it will stop loop running.
4701      **
4702      > Parameters
4703      **
4704      - callback (function) function to run
4705      - thisArg (object) context object for the callback
4706      = (object) Paper object
4707     \*/
4708     paperproto.forEach = function (callback, thisArg) {
4709         var bot = this.bottom;
4710         while (bot) {
4711             if (callback.call(thisArg, bot) === false) {
4712                 return this;
4713             }
4714             bot = bot.next;
4715         }
4716         return this;
4717     };
4718     function x_y() {
4719         return this.x + S + this.y;
4720     }
4721     function x_y_w_h() {
4722         return this.x + S + this.y + S + this.width + "\xd7" + this.height;
4723     }
4724     /*\
4725      * Element.getBBox
4726      [ method ]
4727      **
4728      * Return bounding box for a given element
4729      **
4730      > Parameters
4731      **
4732      - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`.
4733      = (object) Bounding box object:
4734      o {
4735      o     x: (number) top left corner x
4736      o     y: (number) top left corner y
4737      o     width: (number) width
4738      o     height: (number) height
4739      o }
4740     \*/
4741     elproto.getBBox = function (isWithoutTransform) {
4742         if (this.removed) {
4743             return {};
4744         }
4745         var _ = this._;
4746         if (isWithoutTransform) {
4747             if (_.dirty || !_.bboxwt) {
4748                 this.realPath = getPath[this.type](this);
4749                 _.bboxwt = pathDimensions(this.realPath);
4750                 _.bboxwt.toString = x_y_w_h;
4751                 _.dirty = 0;
4752             }
4753             return _.bboxwt;
4754         }
4755         if (_.dirty || _.dirtyT || !_.bbox) {
4756             if (_.dirty || !this.realPath) {
4757                 _.bboxwt = 0;
4758                 this.realPath = getPath[this.type](this);
4759             }
4760             _.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
4761             _.bbox.toString = x_y_w_h;
4762             _.dirty = _.dirtyT = 0;
4763         }
4764         return _.bbox;
4765     };
4766     /*\
4767      * Element.clone
4768      [ method ]
4769      **
4770      = (object) clone of a given element
4771      **
4772     \*/
4773     elproto.clone = function () {
4774         if (this.removed) {
4775             return null;
4776         }
4777         return this.paper[this.type]().attr(this.attr());
4778     };
4779     /*\
4780      * Element.glow
4781      [ method ]
4782      **
4783      * Return set of elements that create glow-like effect around given element. See @Paper.set.
4784      *
4785      * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself.
4786      **
4787      > Parameters
4788      **
4789      - glow (object) #optional parameters object with all properties optional:
4790      o {
4791      o     width (number) size of the glow, default is `10`
4792      o     fill (boolean) will it be filled, default is `false`
4793      o     opacity: opacity, default is `0.5`
4794      o     offsetx: horizontal offset, default is `0`
4795      o     offsety: vertical offset, default is `0`
4796      o     color: glow colour, default is `black`
4797      o }
4798      = (object) @Paper.set of elements that represents glow
4799     \*/
4800     elproto.glow = function (glow) {
4801         if (this.type == "text") {
4802             return null;
4803         }
4804         glow = glow || {};
4805         var s = {
4806             width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
4807             fill: glow.fill || false,
4808             opacity: glow.opacity || .5,
4809             offsetx: glow.offsetx || 0,
4810             offsety: glow.offsety || 0,
4811             color: glow.color || "#000"
4812         },
4813             c = s.width / 2,
4814             r = this.paper,
4815             out = r.set(),
4816             path = this.realPath || getPath[this.type](this);
4817         path = this.matrix ? mapPath(path, this.matrix) : path;
4818         for (var i = 1; i < c + 1; i++) {
4819             out.push(r.path(path).attr({
4820                 stroke: s.color,
4821                 fill: s.fill ? s.color : "none",
4822                 "stroke-linejoin": "round",
4823                 "stroke-linecap": "round",
4824                 "stroke-width": +(s.width / c * i).toFixed(3),
4825                 opacity: +(s.opacity / c).toFixed(3)
4826             }));
4827         }
4828         return out.insertBefore(this).translate(s.offsetx, s.offsety);
4829     };
4830     var curveslengths = {},
4831     getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
4832         var len = 0,
4833             precision = 100,
4834             name = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y].join(),
4835             cache = curveslengths[name],
4836             old, dot;
4837         !cache && (curveslengths[name] = cache = {data: []});
4838         cache.timer && clearTimeout(cache.timer);
4839         cache.timer = setTimeout(function () {delete curveslengths[name];}, 2e3);
4840         if (length != null && !cache.precision) {
4841             var total = getPointAtSegmentLength(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y);
4842             cache.precision = ~~total * 10;
4843             cache.data = [];
4844         }
4845         precision = cache.precision || precision;
4846         for (var i = 0; i < precision + 1; i++) {
4847             if (cache.data[i * precision]) {
4848                 dot = cache.data[i * precision];
4849             } else {
4850                 dot = R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, i / precision);
4851                 cache.data[i * precision] = dot;
4852             }
4853             i && (len += pow(pow(old.x - dot.x, 2) + pow(old.y - dot.y, 2), .5));
4854             if (length != null && len >= length) {
4855                 return dot;
4856             }
4857             old = dot;
4858         }
4859         if (length == null) {
4860             return len;
4861         }
4862     },
4863     getLengthFactory = function (istotal, subpath) {
4864         return function (path, length, onlystart) {
4865             path = path2curve(path);
4866             var x, y, p, l, sp = "", subpaths = {}, point,
4867                 len = 0;
4868             for (var i = 0, ii = path.length; i < ii; i++) {
4869                 p = path[i];
4870                 if (p[0] == "M") {
4871                     x = +p[1];
4872                     y = +p[2];
4873                 } else {
4874                     l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
4875                     if (len + l > length) {
4876                         if (subpath && !subpaths.start) {
4877                             point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
4878                             sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
4879                             if (onlystart) {return sp;}
4880                             subpaths.start = sp;
4881                             sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
4882                             len += l;
4883                             x = +p[5];
4884                             y = +p[6];
4885                             continue;
4886                         }
4887                         if (!istotal && !subpath) {
4888                             point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
4889                             return {x: point.x, y: point.y, alpha: point.alpha};
4890                         }
4891                     }
4892                     len += l;
4893                     x = +p[5];
4894                     y = +p[6];
4895                 }
4896                 sp += p.shift() + p;
4897             }
4898             subpaths.end = sp;
4899             point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[1], p[2], p[3], p[4], p[5], p[6], 1);
4900             point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha});
4901             return point;
4902         };
4903     };
4904     var getTotalLength = getLengthFactory(1),
4905         getPointAtLength = getLengthFactory(),
4906         getSubpathsAtLength = getLengthFactory(0, 1);
4907     /*\
4908      * Raphael.getTotalLength
4909      [ method ]
4910      **
4911      * Returns length of the given path in pixels.
4912      **
4913      > Parameters
4914      **
4915      - path (string) SVG path string.
4916      **
4917      = (number) length.
4918     \*/
4919     R.getTotalLength = getTotalLength;
4920     /*\
4921      * Raphael.getPointAtLength
4922      [ method ]
4923      **
4924      * Return coordinates of the point located at the given length on the given path.
4925      **
4926      > Parameters
4927      **
4928      - path (string) SVG path string
4929      - length (number)
4930      **
4931      = (object) representation of the point:
4932      o {
4933      o     x: (number) x coordinate
4934      o     y: (number) y coordinate
4935      o     alpha: (number) angle of derivative
4936      o }
4937     \*/
4938     R.getPointAtLength = getPointAtLength;
4939     /*\
4940      * Raphael.getSubpath
4941      [ method ]
4942      **
4943      * Return subpath of a given path from given length to given length.
4944      **
4945      > Parameters
4946      **
4947      - path (string) SVG path string
4948      - from (number) position of the start of the segment
4949      - to (number) position of the end of the segment
4950      **
4951      = (string) pathstring for the segment
4952     \*/
4953     R.getSubpath = function (path, from, to) {
4954         if (abs(this.getTotalLength(path) - to) < 1e-6) {
4955             return getSubpathsAtLength(path, from).end;
4956         }
4957         var a = getSubpathsAtLength(path, to, 1);
4958         return from ? getSubpathsAtLength(a, from).end : a;
4959     };
4960     /*\
4961      * Element.getTotalLength
4962      [ method ]
4963      **
4964      * Returns length of the path in pixels. Only works for element of “path” type.
4965      = (number) length.
4966     \*/
4967     elproto.getTotalLength = function () {
4968         if (this.type != "path") {return;}
4969         if (this.node.getTotalLength) {
4970             return this.node.getTotalLength();
4971         }
4972         return getTotalLength(this.attrs.path);
4973     };
4974     /*\
4975      * Element.getPointAtLength
4976      [ method ]
4977      **
4978      * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type.
4979      **
4980      > Parameters
4981      **
4982      - length (number)
4983      **
4984      = (object) representation of the point:
4985      o {
4986      o     x: (number) x coordinate
4987      o     y: (number) y coordinate
4988      o     alpha: (number) angle of derivative
4989      o }
4990     \*/
4991     elproto.getPointAtLength = function (length) {
4992         if (this.type != "path") {return;}
4993         return getPointAtLength(this.attrs.path, length);
4994     };
4995     /*\
4996      * Element.getSubpath
4997      [ method ]
4998      **
4999      * Return subpath of a given element from given length to given length. Only works for element of “path” type.
5000      **
5001      > Parameters
5002      **
5003      - from (number) position of the start of the segment
5004      - to (number) position of the end of the segment
5005      **
5006      = (string) pathstring for the segment
5007     \*/
5008     elproto.getSubpath = function (from, to) {
5009         if (this.type != "path") {return;}
5010         return R.getSubpath(this.attrs.path, from, to);
5011     };
5012     /*\
5013      * Raphael.easing_formulas
5014      [ property ]
5015      **
5016      * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing:
5017      # <ul>
5018      #     <li>“linear”</li>
5019      #     <li>“&lt;” or “easeIn” or “ease-in”</li>
5020      #     <li>“>” or “easeOut” or “ease-out”</li>
5021      #     <li>“&lt;>” or “easeInOut” or “ease-in-out”</li>
5022      #     <li>“backIn” or “back-in”</li>
5023      #     <li>“backOut” or “back-out”</li>
5024      #     <li>“elastic”</li>
5025      #     <li>“bounce”</li>
5026      # </ul>
5027      # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p>
5028     \*/
5029     var ef = R.easing_formulas = {
5030         linear: function (n) {
5031             return n;
5032         },
5033         "<": function (n) {
5034             return pow(n, 1.7);
5035         },
5036         ">": function (n) {
5037             return pow(n, .48);
5038         },
5039         "<>": function (n) {
5040             var q = .48 - n / 1.04,
5041                 Q = math.sqrt(.1734 + q * q),
5042                 x = Q - q,
5043                 X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
5044                 y = -Q - q,
5045                 Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
5046                 t = X + Y + .5;
5047             return (1 - t) * 3 * t * t + t * t * t;
5048         },
5049         backIn: function (n) {
5050             var s = 1.70158;
5051             return n * n * ((s + 1) * n - s);
5052         },
5053         backOut: function (n) {
5054             n = n - 1;
5055             var s = 1.70158;
5056             return n * n * ((s + 1) * n + s) + 1;
5057         },
5058         elastic: function (n) {
5059             if (n == !!n) {
5060                 return n;
5061             }
5062             return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1;
5063         },
5064         bounce: function (n) {
5065             var s = 7.5625,
5066                 p = 2.75,
5067                 l;
5068             if (n < (1 / p)) {
5069                 l = s * n * n;
5070             } else {
5071                 if (n < (2 / p)) {
5072                     n -= (1.5 / p);
5073                     l = s * n * n + .75;
5074                 } else {
5075                     if (n < (2.5 / p)) {
5076                         n -= (2.25 / p);
5077                         l = s * n * n + .9375;
5078                     } else {
5079                         n -= (2.625 / p);
5080                         l = s * n * n + .984375;
5081                     }
5082                 }
5083             }
5084             return l;
5085         }
5086     };
5087     ef.easeIn = ef["ease-in"] = ef["<"];
5088     ef.easeOut = ef["ease-out"] = ef[">"];
5089     ef.easeInOut = ef["ease-in-out"] = ef["<>"];
5090     ef["back-in"] = ef.backIn;
5091     ef["back-out"] = ef.backOut;
5092
5093     var animationElements = [],
5094         requestAnimFrame = window.requestAnimationFrame       ||
5095                            window.webkitRequestAnimationFrame ||
5096                            window.mozRequestAnimationFrame    ||
5097                            window.oRequestAnimationFrame      ||
5098                            window.msRequestAnimationFrame     ||
5099                            function (callback) {
5100                                setTimeout(callback, 16);
5101                            },
5102         animation = function () {
5103             var Now = +new Date,
5104                 l = 0;
5105             for (; l < animationElements.length; l++) {
5106                 var e = animationElements[l];
5107                 if (e.el.removed || e.paused) {
5108                     continue;
5109                 }
5110                 var time = Now - e.start,
5111                     ms = e.ms,
5112                     easing = e.easing,
5113                     from = e.from,
5114                     diff = e.diff,
5115                     to = e.to,
5116                     t = e.t,
5117                     that = e.el,
5118                     set = {},
5119                     now;
5120                 if (e.initstatus) {
5121                     time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
5122                     e.status = e.initstatus;
5123                     delete e.initstatus;
5124                     e.stop && animationElements.splice(l--, 1);
5125                 } else {
5126                     e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top;
5127                 }
5128                 if (time < 0) {
5129                     continue;
5130                 }
5131                 if (time < ms) {
5132                     var pos = easing(time / ms);
5133                     for (var attr in from) if (from[has](attr)) {
5134                         switch (availableAnimAttrs[attr]) {
5135                             case nu:
5136                                 now = +from[attr] + pos * ms * diff[attr];
5137                                 break;
5138                             case "colour":
5139                                 now = "rgb(" + [
5140                                     upto255(round(from[attr].r + pos * ms * diff[attr].r)),
5141                                     upto255(round(from[attr].g + pos * ms * diff[attr].g)),
5142                                     upto255(round(from[attr].b + pos * ms * diff[attr].b))
5143                                 ].join(",") + ")";
5144                                 break;
5145                             case "path":
5146                                 now = [];
5147                                 for (var i = 0, ii = from[attr].length; i < ii; i++) {
5148                                     now[i] = [from[attr][i][0]];
5149                                     for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
5150                                         now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j];
5151                                     }
5152                                     now[i] = now[i].join(S);
5153                                 }
5154                                 now = now.join(S);
5155                                 break;
5156                             case "transform":
5157                                 if (diff[attr].real) {
5158                                     now = [];
5159                                     for (i = 0, ii = from[attr].length; i < ii; i++) {
5160                                         now[i] = [from[attr][i][0]];
5161                                         for (j = 1, jj = from[attr][i].length; j < jj; j++) {
5162                                             now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j];
5163                                         }
5164                                     }
5165                                 } else {
5166                                     var get = function (i) {
5167                                         return +from[attr][i] + pos * ms * diff[attr][i];
5168                                     };
5169                                     // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]];
5170                                     now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]];
5171                                 }
5172                                 break;
5173                             case "csv":
5174                                 if (attr == "clip-rect") {
5175                                     now = [];
5176                                     i = 4;
5177                                     while (i--) {
5178                                         now[i] = +from[attr][i] + pos * ms * diff[attr][i];
5179                                     }
5180                                 }
5181                                 break;
5182                             default:
5183                                 var from2 = [].concat(from[attr]);
5184                                 now = [];
5185                                 i = that.paper.customAttributes[attr].length;
5186                                 while (i--) {
5187                                     now[i] = +from2[i] + pos * ms * diff[attr][i];
5188                                 }
5189                                 break;
5190                         }
5191                         set[attr] = now;
5192                     }
5193                     that.attr(set);
5194                     (function (id, that, anim) {
5195                         setTimeout(function () {
5196                             eve("anim.frame." + id, that, anim);
5197                         });
5198                     })(that.id, that, e.anim);
5199                 } else {
5200                     (function(f, el, a) {
5201                         setTimeout(function() {
5202                             eve("anim.frame." + el.id, el, a);
5203                             eve("anim.finish." + el.id, el, a);
5204                             R.is(f, "function") && f.call(el);
5205                         });
5206                     })(e.callback, that, e.anim);
5207                     that.attr(to);
5208                     animationElements.splice(l--, 1);
5209                     if (e.repeat > 1 && !e.next) {
5210                         runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1);
5211                     }
5212                     if (e.next && !e.stop) {
5213                         runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat);
5214                     }
5215                 }
5216             }
5217             R.svg && that && that.paper && that.paper.safari();
5218             animationElements.length && requestAnimFrame(animation);
5219         },
5220         upto255 = function (color) {
5221             return color > 255 ? 255 : color < 0 ? 0 : color;
5222         };
5223     /*\
5224      * Element.animateWith
5225      [ method ]
5226      **
5227      * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element.
5228      **
5229      > Parameters
5230      **
5231      - params (object) final attributes for the element, see also @Element.attr
5232      - ms (number) number of milliseconds for animation to run
5233      - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
5234      - callback (function) #optional callback function. Will be called at the end of animation.
5235      * or
5236      - animation (object) animation object, see @Raphael.animation
5237      **
5238      = (object) original element
5239     \*/
5240     elproto.animateWith = function (element, params, ms, easing, callback) {
5241         this.animate(params, ms, easing, callback);
5242         var start, el;
5243         for (var i = 0, ii = animationElements.length; i < ii; i++) {
5244             el = animationElements[i];
5245             if (el.el.id == element.id) {
5246                 start = el.timestamp;
5247             } else if (el.el.id == this.id) {
5248                 el.start = start;
5249             }
5250         }
5251         return this.animate(params, ms, easing, callback);
5252     };
5253     function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
5254         var cx = 3 * p1x,
5255             bx = 3 * (p2x - p1x) - cx,
5256             ax = 1 - cx - bx,
5257             cy = 3 * p1y,
5258             by = 3 * (p2y - p1y) - cy,
5259             ay = 1 - cy - by;
5260         function sampleCurveX(t) {
5261             return ((ax * t + bx) * t + cx) * t;
5262         }
5263         function solve(x, epsilon) {
5264             var t = solveCurveX(x, epsilon);
5265             return ((ay * t + by) * t + cy) * t;
5266         }
5267         function solveCurveX(x, epsilon) {
5268             var t0, t1, t2, x2, d2, i;
5269             for(t2 = x, i = 0; i < 8; i++) {
5270                 x2 = sampleCurveX(t2) - x;
5271                 if (abs(x2) < epsilon) {
5272                     return t2;
5273                 }
5274                 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
5275                 if (abs(d2) < 1e-6) {
5276                     break;
5277                 }
5278                 t2 = t2 - x2 / d2;
5279             }
5280             t0 = 0;
5281             t1 = 1;
5282             t2 = x;
5283             if (t2 < t0) {
5284                 return t0;
5285             }
5286             if (t2 > t1) {
5287                 return t1;
5288             }
5289             while (t0 < t1) {
5290                 x2 = sampleCurveX(t2);
5291                 if (abs(x2 - x) < epsilon) {
5292                     return t2;
5293                 }
5294                 if (x > x2) {
5295                     t0 = t2;
5296                 } else {
5297                     t1 = t2;
5298                 }
5299                 t2 = (t1 - t0) / 2 + t0;
5300             }
5301             return t2;
5302         }
5303         return solve(t, 1 / (200 * duration));
5304     }
5305     elproto.onAnimation = function (f) {
5306         f ? eve.on("anim.frame." + this.id, f) : eve.unbind("anim.frame." + this.id);
5307         return this;
5308     };
5309     function Animation(anim, ms) {
5310         var percents = [];
5311         this.anim = anim;
5312         this.ms = ms;
5313         this.times = 1;
5314         if (this.anim) {
5315             for (var attr in this.anim) if (this.anim[has](attr)) {
5316                 percents.push(+attr);
5317             }
5318             percents.sort(sortByNumber);
5319         }
5320         this.top = percents[percents.length - 1];
5321         this.percents = percents;
5322     }
5323     /*\
5324      * Animation.delay
5325      [ method ]
5326      **
5327      * Creates a copy of existing animation object with given delay.
5328      **
5329      > Parameters
5330      **
5331      - delay (number) number of ms to pass between animation start and actual animation
5332      **
5333      = (object) new altered Animation object
5334     \*/
5335     Animation.prototype.delay = function (delay) {
5336         var a = new Animation(this.anim, this.ms);
5337         a.times = this.times;
5338         a.del = +delay || 0;
5339         return a;
5340     };
5341     /*\
5342      * Animation.repeat
5343      [ method ]
5344      **
5345      * Creates a copy of existing animation object with given repetition.
5346      **
5347      > Parameters
5348      **
5349      - repeat (number) number iterations of animation. For infinite animation pass `Infinity`
5350      **
5351      = (object) new altered Animation object
5352     \*/
5353     Animation.prototype.repeat = function (times) { 
5354         var a = new Animation(this.anim, this.ms);
5355         a.del = this.del;
5356         a.times = math.floor(mmax(times, 0)) || 1;
5357         return a;
5358     };
5359     function runAnimation(anim, element, percent, status, totalOrigin, times) {
5360         percent = toFloat(percent);
5361         var params,
5362             isInAnim,
5363             isInAnimSet,
5364             percents = [],
5365             next,
5366             prev,
5367             timestamp,
5368             ms = anim.ms,
5369             from = {},
5370             to = {},
5371             diff = {};
5372         if (status) {
5373             for (i = 0, ii = animationElements.length; i < ii; i++) {
5374                 var e = animationElements[i];
5375                 if (e.el.id == element.id && e.anim == anim) {
5376                     if (e.percent != percent) {
5377                         animationElements.splice(i, 1);
5378                         isInAnimSet = 1;
5379                     } else {
5380                         isInAnim = e;
5381                     }
5382                     element.attr(e.totalOrigin);
5383                     break;
5384                 }
5385             }
5386         } else {
5387             status = +to; // NaN
5388         }
5389         for (var i = 0, ii = anim.percents.length; i < ii; i++) {
5390             if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
5391                 percent = anim.percents[i];
5392                 prev = anim.percents[i - 1] || 0;
5393                 ms = ms / anim.top * (percent - prev);
5394                 next = anim.percents[i + 1];
5395                 params = anim.anim[percent];
5396                 break;
5397             } else if (status) {
5398                 element.attr(anim.anim[anim.percents[i]]);
5399             }
5400         }
5401         if (!params) {
5402             return;
5403         }
5404         if (!isInAnim) {
5405             for (attr in params) if (params[has](attr)) {
5406                 if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
5407                     from[attr] = element.attr(attr);
5408                     (from[attr] == null) && (from[attr] = availableAttrs[attr]);
5409                     to[attr] = params[attr];
5410                     switch (availableAnimAttrs[attr]) {
5411                         case nu:
5412                             diff[attr] = (to[attr] - from[attr]) / ms;
5413                             break;
5414                         case "colour":
5415                             from[attr] = R.getRGB(from[attr]);
5416                             var toColour = R.getRGB(to[attr]);
5417                             diff[attr] = {
5418                                 r: (toColour.r - from[attr].r) / ms,
5419                                 g: (toColour.g - from[attr].g) / ms,
5420                                 b: (toColour.b - from[attr].b) / ms
5421                             };
5422                             break;
5423                         case "path":
5424                             var pathes = path2curve(from[attr], to[attr]),
5425                                 toPath = pathes[1];
5426                             from[attr] = pathes[0];
5427                             diff[attr] = [];
5428                             for (i = 0, ii = from[attr].length; i < ii; i++) {
5429                                 diff[attr][i] = [0];
5430                                 for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
5431                                     diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms;
5432                                 }
5433                             }
5434                             break;
5435                         case "transform":
5436                             var _ = element._,
5437                                 eq = equaliseTransform(_[attr], to[attr]);
5438                             if (eq) {
5439                                 from[attr] = eq.from;
5440                                 to[attr] = eq.to;
5441                                 diff[attr] = [];
5442                                 diff[attr].real = true;
5443                                 for (i = 0, ii = from[attr].length; i < ii; i++) {
5444                                     diff[attr][i] = [from[attr][i][0]];
5445                                     for (j = 1, jj = from[attr][i].length; j < jj; j++) {
5446                                         diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms;
5447                                     }
5448                                 }
5449                             } else {
5450                                 var m = (element.matrix || new Matrix),
5451                                     to2 = {_:{transform: _.transform}, getBBox: function () { return element.getBBox(); }};
5452                                 from[attr] = [
5453                                     m.a,
5454                                     m.b,
5455                                     m.c,
5456                                     m.d,
5457                                     m.e,
5458                                     m.f
5459                                 ];
5460                                 extractTransform(to2, to[attr]);
5461                                 to[attr] = to2._.transform;
5462                                 diff[attr] = [
5463                                     (to2.matrix.a - m.a) / ms,
5464                                     (to2.matrix.b - m.b) / ms,
5465                                     (to2.matrix.c - m.c) / ms,
5466                                     (to2.matrix.d - m.d) / ms,
5467                                     (to2.matrix.e - m.e) / ms,
5468                                     (to2.matrix.e - m.f) / ms
5469                                 ];
5470                                 // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy];
5471                                 // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }};
5472                                 // extractTransform(to2, to[attr]);
5473                                 // diff[attr] = [
5474                                 //     (to2._.sx - _.sx) / ms,
5475                                 //     (to2._.sy - _.sy) / ms,
5476                                 //     (to2._.deg - _.deg) / ms,
5477                                 //     (to2._.dx - _.dx) / ms,
5478                                 //     (to2._.dy - _.dy) / ms
5479                                 // ];
5480                             }
5481                             break;
5482                         case "csv":
5483                             var values = Str(params[attr]).split(separator),
5484                                 from2 = Str(from[attr]).split(separator);
5485                             if (attr == "clip-rect") {
5486                                 from[attr] = from2;
5487                                 diff[attr] = [];
5488                                 i = from2.length;
5489                                 while (i--) {
5490                                     diff[attr][i] = (values[i] - from[attr][i]) / ms;
5491                                 }
5492                             }
5493                             to[attr] = values;
5494                             break;
5495                         default:
5496                             values = [].concat(params[attr]);
5497                             from2 = [].concat(from[attr]);
5498                             diff[attr] = [];
5499                             i = element.paper.customAttributes[attr].length;
5500                             while (i--) {
5501                                 diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms;
5502                             }
5503                             break;
5504                     }
5505                 }
5506             }
5507             var easing = params.easing,
5508                 easyeasy = R.easing_formulas[easing];
5509             if (!easyeasy) {
5510                 easyeasy = Str(easing).match(bezierrg);
5511                 if (easyeasy && easyeasy.length == 5) {
5512                     var curve = easyeasy;
5513                     easyeasy = function (t) {
5514                         return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms);
5515                     };
5516                 } else {
5517                     easyeasy = pipe;
5518                 }
5519             }
5520             timestamp = params.start || anim.start || +new Date;
5521             e = {
5522                 anim: anim,
5523                 percent: percent,
5524                 timestamp: timestamp,
5525                 start: timestamp + (anim.del || 0),
5526                 status: 0,
5527                 initstatus: status || 0,
5528                 stop: false,
5529                 ms: ms,
5530                 easing: easyeasy,
5531                 from: from,
5532                 diff: diff,
5533                 to: to,
5534                 el: element,
5535                 callback: params.callback,
5536                 prev: prev,
5537                 next: next,
5538                 repeat: times || anim.times,
5539                 origin: element.attr(),
5540                 totalOrigin: totalOrigin
5541             };
5542             animationElements.push(e);
5543             if (status && !isInAnim) {
5544                 e.stop = true;
5545                 e.start = new Date - ms * status;
5546                 if (animationElements.length == 1) {
5547                     return animation();
5548                 }
5549             }
5550             animationElements.length == 1 && requestAnimFrame(animation);
5551         } else {
5552             isInAnim.initstatus = status;
5553             isInAnim.start = new Date - isInAnim.ms * status;
5554         }
5555         eve("anim.start." + element.id, element, anim);
5556     }
5557     /*\
5558      * Raphael.animation
5559      [ method ]
5560      **
5561      * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods.
5562      * See also @Animation.delay and @Animation.repeat methods.
5563      **
5564      > Parameters
5565      **
5566      - params (object) final attributes for the element, see also @Element.attr
5567      - ms (number) number of milliseconds for animation to run
5568      - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
5569      - callback (function) #optional callback function. Will be called at the end of animation.
5570      **
5571      = (object) @Animation
5572     \*/
5573     R.animation = function (params, ms, easing, callback) {
5574         if (R.is(easing, "function") || !easing) {
5575             callback = callback || easing || null;
5576             easing = null;
5577         }
5578         params = Object(params);
5579         ms = +ms || 0;
5580         var p = {},
5581             json,
5582             attr;
5583         for (attr in params) if (params[has](attr) && toFloat(attr) != attr) {
5584             json = true;
5585             p[attr] = params[attr];
5586         }
5587         if (!json) {
5588             return new Animation(params, ms);
5589         } else {
5590             easing && (p.easing = easing);
5591             callback && (p.callback = callback);
5592             return new Animation({100: p}, ms);
5593         }
5594     };
5595     /*\
5596      * Element.animate
5597      [ method ]
5598      **
5599      * Creates and starts animation for given element.
5600      **
5601      > Parameters
5602      **
5603      - params (object) final attributes for the element, see also @Element.attr
5604      - ms (number) number of milliseconds for animation to run
5605      - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)`
5606      - callback (function) #optional callback function. Will be called at the end of animation.
5607      * or
5608      - animation (object) animation object, see @Raphael.animation
5609      **
5610      = (object) original element
5611     \*/
5612     elproto.animate = function (params, ms, easing, callback) {
5613         var element = this;
5614         if (element.removed) {
5615             callback && callback.call(element);
5616             return element;
5617         }
5618         var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
5619         runAnimation(anim, element, anim.percents[0], null, element.attr());
5620         return element;
5621     };
5622     /*\
5623      * Element.setTime
5624      [ method ]
5625      **
5626      * Sets the status of animation of the element in milliseconds. Similar to @Element.status method.
5627      **
5628      > Parameters
5629      **
5630      - anim (object) animation object
5631      - value (number) number of milliseconds from the beginning of the animation
5632      **
5633      = (object) original element if `value` is specified
5634      * Note, that during animation following events are triggered:
5635      *
5636      * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`.
5637     \*/
5638     elproto.setTime = function (anim, value) {
5639         if (anim && value != null) {
5640             this.status(anim, mmin(value, anim.ms) / anim.ms);
5641         }
5642         return this;
5643     };
5644     /*\
5645      * Element.status
5646      [ method ]
5647      **
5648      * Gets or sets the status of animation of the element.
5649      **
5650      > Parameters
5651      **
5652      - anim (object) #optional animation object
5653      - 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.
5654      **
5655      = (number) status
5656      * or
5657      = (array) status if `anim` is not specified. Array of objects in format:
5658      o {
5659      o     anim: (object) animation object
5660      o     status: (number) status
5661      o }
5662      * or
5663      = (object) original element if `value` is specified
5664     \*/
5665     elproto.status = function (anim, value) {
5666         var out = [],
5667             i = 0,
5668             len,
5669             e;
5670         if (value != null) {
5671             runAnimation(anim, this, -1, mmin(value, 1));
5672             return this;
5673         } else {
5674             len = animationElements.length;
5675             for (; i < len; i++) {
5676                 e = animationElements[i];
5677                 if (e.el.id == this.id && (!anim || e.anim == anim)) {
5678                     if (anim) {
5679                         return e.status;
5680                     }
5681                     out.push({anim: e.anim, status: e.status});
5682                 }
5683             }
5684             if (anim) {
5685                 return 0;
5686             }
5687             return out;
5688         }
5689     };
5690     /*\
5691      * Element.pause
5692      [ method ]
5693      **
5694      * Stops animation of the element with ability to resume it later on.
5695      **
5696      > Parameters
5697      **
5698      - anim (object) #optional animation object
5699      **
5700      = (object) original element
5701     \*/
5702     elproto.pause = function (anim) {
5703         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
5704             if (eve("anim.pause." + this.id, this, animationElements[i].anim) !== false) {
5705                 animationElements[i].paused = true;
5706             }
5707         }
5708         return this;
5709     };
5710     /*\
5711      * Element.resume
5712      [ method ]
5713      **
5714      * Resumes animation if it was paused with @Element.pause method.
5715      **
5716      > Parameters
5717      **
5718      - anim (object) #optional animation object
5719      **
5720      = (object) original element
5721     \*/
5722     elproto.resume = function (anim) {
5723         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
5724             var e = animationElements[i];
5725             if (eve("anim.resume." + this.id, this, e.anim) !== false) {
5726                 delete e.paused;
5727                 this.status(e.anim, e.status);
5728             }
5729         }
5730         return this;
5731     };
5732     /*\
5733      * Element.stop
5734      [ method ]
5735      **
5736      * Stops animation of the element.
5737      **
5738      > Parameters
5739      **
5740      - anim (object) #optional animation object
5741      **
5742      = (object) original element
5743     \*/
5744     elproto.stop = function (anim) {
5745         for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
5746             if (eve("anim.stop." + this.id, this, animationElements[i].anim) !== false) {
5747                 animationElements.splice(i--, 1);
5748             }
5749         }
5750         return this;
5751     };
5752     elproto.toString = function () {
5753         return "Rapha\xebl\u2019s object";
5754     };
5755
5756     // Set
5757     var Set = function (items) {
5758         this.items = [];
5759         this.length = 0;
5760         this.type = "set";
5761         if (items) {
5762             for (var i = 0, ii = items.length; i < ii; i++) {
5763                 if (items[i] && (items[i].constructor == Element || items[i].constructor == Set)) {
5764                     this[this.items.length] = this.items[this.items.length] = items[i];
5765                     this.length++;
5766                 }
5767             }
5768         }
5769     },
5770     setproto = Set.prototype;
5771     /*\
5772      * Set.push
5773      [ method ]
5774      **
5775      * Adds each argument to the current set.
5776      = (object) original element
5777     \*/
5778     setproto.push = function () {
5779         var item,
5780             len;
5781         for (var i = 0, ii = arguments.length; i < ii; i++) {
5782             item = arguments[i];
5783             if (item && (item.constructor == Element || item.constructor == Set)) {
5784                 len = this.items.length;
5785                 this[len] = this.items[len] = item;
5786                 this.length++;
5787             }
5788         }
5789         return this;
5790     };
5791     /*\
5792      * Set.pop
5793      [ method ]
5794      **
5795      * Removes last element and returns it.
5796      = (object) element
5797     \*/
5798     setproto.pop = function () {
5799         this.length && delete this[this.length--];
5800         return this.items.pop();
5801     };
5802     /*\
5803      * Set.forEach
5804      [ method ]
5805      **
5806      * Executes given function for each element in the set.
5807      *
5808      * If function returns `false` it will stop loop running.
5809      **
5810      > Parameters
5811      **
5812      - callback (function) function to run
5813      - thisArg (object) context object for the callback
5814      = (object) Set object
5815     \*/
5816     setproto.forEach = function (callback, thisArg) {
5817         for (var i = 0, ii = this.items.length; i < ii; i++) {
5818             if (callback.call(thisArg, this.items[i]) === false) {
5819                 return this;
5820             }
5821         }
5822         return this;
5823     };
5824     for (var method in elproto) if (elproto[has](method)) {
5825         setproto[method] = (function (methodname) {
5826             return function () {
5827                 var arg = arguments;
5828                 return this.forEach(function (el) {
5829                     el[methodname][apply](el, arg);
5830                 });
5831             };
5832         })(method);
5833     }
5834     setproto.attr = function (name, value) {
5835         if (name && R.is(name, array) && R.is(name[0], "object")) {
5836             for (var j = 0, jj = name.length; j < jj; j++) {
5837                 this.items[j].attr(name[j]);
5838             }
5839         } else {
5840             for (var i = 0, ii = this.items.length; i < ii; i++) {
5841                 this.items[i].attr(name, value);
5842             }
5843         }
5844         return this;
5845     };
5846     setproto.clear = function () {
5847         while (this.length) {
5848             this.pop();
5849         }
5850     };
5851     setproto.animate = function (params, ms, easing, callback) {
5852         (R.is(easing, "function") || !easing) && (callback = easing || null);
5853         var len = this.items.length,
5854             i = len,
5855             item,
5856             set = this,
5857             collector;
5858         if (!len) {
5859             return this;
5860         }
5861         callback && (collector = function () {
5862             !--len && callback.call(set);
5863         });
5864         easing = R.is(easing, string) ? easing : collector;
5865         var anim = params instanceof Animation ? params : R.animation(params, ms, easing, collector);
5866         item = this.items[--i].animate(anim);
5867         while (i--) {
5868             this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim);
5869         }
5870         return this;
5871     };
5872     setproto.insertAfter = function (el) {
5873         var i = this.items.length;
5874         while (i--) {
5875             this.items[i].insertAfter(el);
5876         }
5877         return this;
5878     };
5879     setproto.getBBox = function () {
5880         var x = [],
5881             y = [],
5882             w = [],
5883             h = [];
5884         for (var i = this.items.length; i--;) if (!this.items[i].removed) {
5885             var box = this.items[i].getBBox();
5886             x.push(box.x);
5887             y.push(box.y);
5888             w.push(box.x + box.width);
5889             h.push(box.y + box.height);
5890         }
5891         x = mmin[apply](0, x);
5892         y = mmin[apply](0, y);
5893         return {
5894             x: x,
5895             y: y,
5896             width: mmax[apply](0, w) - x,
5897             height: mmax[apply](0, h) - y
5898         };
5899     };
5900     setproto.clone = function (s) {
5901         s = new Set;
5902         for (var i = 0, ii = this.items.length; i < ii; i++) {
5903             s.push(this.items[i].clone());
5904         }
5905         return s;
5906     };
5907     setproto.toString = function () {
5908         return "Rapha\xebl\u2018s set";
5909     };
5910
5911     R.registerFont = function (font) {
5912         if (!font.face) {
5913             return font;
5914         }
5915         this.fonts = this.fonts || {};
5916         var fontcopy = {
5917                 w: font.w,
5918                 face: {},
5919                 glyphs: {}
5920             },
5921             family = font.face["font-family"];
5922         for (var prop in font.face) if (font.face[has](prop)) {
5923             fontcopy.face[prop] = font.face[prop];
5924         }
5925         if (this.fonts[family]) {
5926             this.fonts[family].push(fontcopy);
5927         } else {
5928             this.fonts[family] = [fontcopy];
5929         }
5930         if (!font.svg) {
5931             fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
5932             for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) {
5933                 var path = font.glyphs[glyph];
5934                 fontcopy.glyphs[glyph] = {
5935                     w: path.w,
5936                     k: {},
5937                     d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) {
5938                             return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M";
5939                         }) + "z"
5940                 };
5941                 if (path.k) {
5942                     for (var k in path.k) if (path[has](k)) {
5943                         fontcopy.glyphs[glyph].k[k] = path.k[k];
5944                     }
5945                 }
5946             }
5947         }
5948         return font;
5949     };
5950     paperproto.getFont = function (family, weight, style, stretch) {
5951         stretch = stretch || "normal";
5952         style = style || "normal";
5953         weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400;
5954         if (!R.fonts) {
5955             return;
5956         }
5957         var font = R.fonts[family];
5958         if (!font) {
5959             var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
5960             for (var fontName in R.fonts) if (R.fonts[has](fontName)) {
5961                 if (name.test(fontName)) {
5962                     font = R.fonts[fontName];
5963                     break;
5964                 }
5965             }
5966         }
5967         var thefont;
5968         if (font) {
5969             for (var i = 0, ii = font.length; i < ii; i++) {
5970                 thefont = font[i];
5971                 if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
5972                     break;
5973                 }
5974             }
5975         }
5976         return thefont;
5977     };
5978     paperproto.print = function (x, y, string, font, size, origin, letter_spacing) {
5979         origin = origin || "middle"; // baseline|middle
5980         letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
5981         var out = this.set(),
5982             letters = Str(string).split(E),
5983             shift = 0,
5984             path = E,
5985             scale;
5986         R.is(font, string) && (font = this.getFont(font));
5987         if (font) {
5988             scale = (size || 16) / font.face["units-per-em"];
5989             var bb = font.face.bbox.split(separator),
5990                 top = +bb[0],
5991                 height = +bb[1] + (origin == "baseline" ? bb[3] - bb[1] + (+font.face.descent) : (bb[3] - bb[1]) / 2);
5992             for (var i = 0, ii = letters.length; i < ii; i++) {
5993                 var prev = i && font.glyphs[letters[i - 1]] || {},
5994                     curr = font.glyphs[letters[i]];
5995                 shift += i ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0;
5996                 curr && curr.d && out.push(this.path(curr.d).attr({fill: "#000", stroke: "none", transform: [["t", shift, 0]]}));
5997             }
5998             out.scale(scale, scale, top, height).translate(x - top, y - height);
5999         }
6000         return out;
6001     };
6002
6003     R.format = function (token, params) {
6004         var args = R.is(params, array) ? [0][concat](params) : arguments;
6005         token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) {
6006             return args[++i] == null ? E : args[i];
6007         }));
6008         return token || E;
6009     };
6010     R.ninja = function () {
6011         oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael;
6012         return R;
6013     };
6014     /*\
6015      * Raphael.el
6016      [ property (object) ]
6017      **
6018      * You can add your own method to elements. This is usefull when you want to hack default functionality or
6019      * want to wrap some common transformation or attributes in one method. In difference to canvas methods,
6020      * you can redefine element method at any time. Expending element methods wouldn’t affect set.
6021      > Usage
6022      | Raphael.el.red = function () {
6023      |     this.attr({fill: "#f00"});
6024      | };
6025      | // then use it
6026      | paper.circle(100, 100, 20).red();
6027     \*/
6028     R.el = elproto;
6029     R.st = setproto;
6030     // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
6031     (function (doc, loaded, f) {
6032         if (doc.readyState == null && doc.addEventListener){
6033             doc.addEventListener(loaded, f = function () {
6034                 doc.removeEventListener(loaded, f, false);
6035                 doc.readyState = "complete";
6036             }, false);
6037             doc.readyState = "loading";
6038         }
6039         function isLoaded() {
6040             (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : eve("DOMload");
6041         }
6042         isLoaded();
6043     })(document, "DOMContentLoaded");
6044
6045     oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R);
6046
6047     /*
6048      * Eve 0.2.3 - JavaScript Events Library
6049      *
6050      * Copyright (c) 2010 Dmitry Baranovskiy (http://dmitry.baranovskiy.com/)
6051      * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
6052      */
6053
6054     var eve = R.eve = (function () {
6055         var version = "0.2.3",
6056             has = "hasOwnProperty",
6057             separator = /[\.\/]/,
6058             wildcard = "*",
6059             fun = function () {},
6060             numsort = function (a, b) {
6061                 return a - b;
6062             },
6063             current_event,
6064             events = {n: {}},
6065         /*\
6066          * eve
6067          [ method ]
6068          **
6069          * Fires event with given `name`, given scope and other parameters.
6070          **
6071          > Arguments
6072          **
6073          - name (string) name of the event, dot (`.`) or slash (`/`) separated
6074          - scope (object) context for the event handlers
6075          - varargs (...) the rest of arguments will be sent to event handlers
6076          **
6077          = (array) array of errors, if any. Each element of the array is in format:
6078          o {
6079          o     error (string) error message
6080          o     func (function) handler that caused error
6081          o }
6082         \*/
6083             eve = function (name, scope) {
6084                 var e = events,
6085                     args = Array.prototype.slice.call(arguments, 2),
6086                     listeners = eve.listeners(name),
6087                     z = 0,
6088                     f = false,
6089                     l,
6090                     indexed = [],
6091                     queue = {},
6092                     errors = [];
6093                 current_event = name;
6094                 for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) {
6095                     indexed.push(listeners[i].zIndex);
6096                     if (listeners[i].zIndex < 0) {
6097                         queue[listeners[i].zIndex] = listeners[i];
6098                     }
6099                 }
6100                 indexed.sort(numsort);
6101                 while (indexed[z] < 0) {
6102                     l = queue[indexed[z++]];
6103                     if (l.apply(scope, args) === f) {
6104                         return f;
6105                     }
6106                 }
6107                 for (i = 0; i < ii; i++) {
6108                     l = listeners[i];
6109                     if ("zIndex" in l) {
6110                         if (l.zIndex == indexed[z]) {
6111                             if (l.apply(scope, args) === f) {
6112                                 return f;
6113                             }
6114                             do {
6115                                 z++;
6116                                 l = queue[indexed[z]];
6117                                 if (l) {
6118                                     if (l.apply(scope, args) === f) {
6119                                         return f;
6120                                     }
6121                                 }
6122                             } while (l)
6123                         } else {
6124                             queue[l.zIndex] = l;
6125                         }
6126                     } else {
6127                         if (l.apply(scope, args) === f) {
6128                             return f;
6129                         }
6130                     }
6131                 }
6132             };
6133         /*\
6134          * eve.listeners
6135          [ method ]
6136          **
6137          * Internal method which gives you array of all event handlers that will be triggered by the given `name`.
6138          **
6139          > Arguments
6140          **
6141          - name (string) name of the event, dot (`.`) or slash (`/`) separated
6142          **
6143          = (array) array of event handlers
6144         \*/
6145         eve.listeners = function (name) {
6146             var names = name.split(separator),
6147                 e = events,
6148                 item,
6149                 items,
6150                 k,
6151                 i,
6152                 ii,
6153                 j,
6154                 jj,
6155                 nes,
6156                 es = [e],
6157                 out = [];
6158             for (i = 0, ii = names.length; i < ii; i++) {
6159                 nes = [];
6160                 for (j = 0, jj = es.length; j < jj; j++) {
6161                     e = es[j].n;
6162                     items = [e[names[i]], e[wildcard]];
6163                     k = 2;
6164                     while (k--) {
6165                         item = items[k];
6166                         if (item) {
6167                             nes.push(item);
6168                             out = out.concat(item.f || []);
6169                         }
6170                     }
6171                 }
6172                 es = nes;
6173             }
6174             return out;
6175         };
6176     
6177         /*\
6178          * eve.on
6179          [ method ]
6180          **
6181          * Binds given event handler with a given name. You can use wildcards “`*`” for the names:
6182          | eve.on("*.under.*", f);
6183          | eve("mouse.under.floor"); // triggers f
6184          * Use @eve to trigger the listener.
6185          **
6186          > Arguments
6187          **
6188          - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
6189          - f (function) event handler function
6190          **
6191          = (function) returned function accept one number parameter that represents z-index of the handler. It is optional feature and only used when you need to ensure that some subset of handlers will be invoked in a given order, despite of the order of assignment. 
6192          > Example:
6193          | eve.on("mouse", eat)(2);
6194          | eve.on("mouse", scream);
6195          | eve.on("mouse", catch)(1);
6196          * This will ensure that `catch` function will be called before `eat`.
6197          * If you want to put you hadler before not indexed handlers specify negative value.
6198          * Note: I assume most of the time you don’t need to worry about z-index, but it’s nice to have this feature “just in case”.
6199         \*/
6200         eve.on = function (name, f) {
6201             var names = name.split(separator),
6202                 e = events;
6203             for (var i = 0, ii = names.length; i < ii; i++) {
6204                 e = e.n;
6205                 !e[names[i]] && (e[names[i]] = {n: {}});
6206                 e = e[names[i]];
6207             }
6208             e.f = e.f || [];
6209             for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
6210                 return fun;
6211             }
6212             e.f.push(f);
6213             return function (zIndex) {
6214                 if (+zIndex == +zIndex) {
6215                     f.zIndex = +zIndex;
6216                 }
6217             };
6218         };
6219         /*\
6220          * eve.nt
6221          [ method ]
6222          **
6223          * Could be used inside event handler to figure out actual name of the event.
6224          **
6225          > Arguments
6226          **
6227          - subname (string) #optional subname of the event
6228          **
6229          = (string) name of the event, if `subname` is not specified
6230          * or
6231          = (boolean) `true`, if current event’s name contains `subname`
6232         \*/
6233         eve.nt = function (subname) {
6234             if (subname) {
6235                 return new RegExp("(?:\\.|\\/|^)" + subname + "(?:\\.|\\/|$)").test(current_event);
6236             }
6237             return current_event;
6238         };
6239         /*\
6240          * eve.unbind
6241          [ method ]
6242          **
6243          * Removes given function from the list of event listeners assigned to given name.
6244          **
6245          > Arguments
6246          **
6247          - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards
6248          - f (function) event handler function
6249         \*/
6250         eve.unbind = function (name, f) {
6251             var names = name.split(separator),
6252                 e,
6253                 key,
6254                 splice,
6255                 cur = [events];
6256             for (var i = 0, ii = names.length; i < ii; i++) {
6257                 for (var j = 0; j < cur.length; j += splice.length - 2) {
6258                     splice = [j, 1];
6259                     e = cur[j].n;
6260                     if (names[i] != wildcard) {
6261                         if (e[names[i]]) {
6262                             splice.push(e[names[i]]);
6263                         }
6264                     } else {
6265                         for (key in e) if (e[has](key)) {
6266                             splice.push(e[key]);
6267                         }
6268                     }
6269                     cur.splice.apply(cur, splice);
6270                 }
6271             }
6272             for (i = 0, ii = cur.length; i < ii; i++) {
6273                 e = cur[i];
6274                 while (e.n) {
6275                     if (f) {
6276                         if (e.f) {
6277                             for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) {
6278                                 e.f.splice(i, 1);
6279                                 break;
6280                             }
6281                             !e.f.length && delete e.f;
6282                         }
6283                         for (key in e.n) if (e.n[has](key) && e.n[key].f) {
6284                             var funcs = e.n[key].f;
6285                             for (i = 0, ii = funcs.length; i < ii; i++) if (funcs[i] == f) {
6286                                 funcs.splice(i, 1);
6287                                 break;
6288                             }
6289                             !funcs.length && delete e.n[key].f;
6290                         }
6291                     } else {
6292                         delete e.f;
6293                         for (key in e.n) if (e.n[has](key) && e.n[key].f) {
6294                             delete e.n[key].f;
6295                         }
6296                     }
6297                     e = e.n;
6298                 }
6299             }
6300         };
6301         /*\
6302          * eve.version
6303          [ property (string) ]
6304          **
6305          * Current version of the library.
6306         \*/
6307         eve.version = version;
6308         eve.toString = function () {
6309             return "You are running Eve " + version;
6310         };
6311         return eve;
6312     })();
6313     
6314     // Eve finished
6315     
6316     eve.on("DOMload", function () {
6317         loaded = true;
6318     });
6319 })();