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