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