cource code from http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element
192775
function parseSVG(s) {
	  var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
	  div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
	  var frag= document.createDocumentFragment();
	  while (div.firstChild.firstChild)
	    frag.appendChild(div.firstChild.firstChild);
	  return frag;
	}
276680
function append() {
  var i, l = this.length, el, args = this.slice.call(arguments);
  function it(node, index) {
    // content elements to insert
    el.each(function(ins) {
      ins = (index < (l - 1)) ? ins.cloneNode(true) : ins;
      node.appendChild(ins);
    });
  }
  for(i = 0;i < args.length;i++) {
    // wrap content
    el = this.air(args[i]);
    // matched parent elements (targets)
    this.each(it);
  }
  return this;
}
1370637
function (tipElement, svg) {
    _element = tipElement;
    _bubble = _element.find('.bubble');
    _svg = svg;
    _svgPoint = svg[0].createSVGPoint();
  }
1221003
def prep_defs(svg)

      # <defs> should be moved to the beginning of the SVG file for braod browser support. Ahem, Firefox ಠ_ಠ
      # When symbols are reassembled, @defs will be added back

      if @defs = svg.scan(/<defs>(.+)<\/defs>/m).flatten[0]
        svg.sub!("<defs>#{@defs}</defs>", '')
        @defs.gsub!(/(\n|\s{2,})/,'')

        @defs.scan(/id="(.+?)"/).flatten.uniq.each_with_index do |id, index|

          # If there are urls matching def ids
          if svg.match(/url\(##{id}\)/)

            new_id = "def-#{@id}-#{index}"                 # Generate a unique id
            @defs.gsub!(/id="#{id}"/, %Q{id="#{new_id}"})  # Replace the def ids
            svg.gsub!(/url\(##{id}\)/, "url(##{new_id})")  # Replace url references to these old def ids
          end
        end
      end

      svg
    end
847999
function() {
        var svgFeature = "http://www.w3.org/TR/SVG11/feature#";
        return (document.implementation && 
           (document.implementation.hasFeature("org.w3c.svg", "1.0") || 
            document.implementation.hasFeature(svgFeature + "SVG", "1.1") || 
            document.implementation.hasFeature(svgFeature + "BasicStructure", "1.1") ));
    }
806482
function(span, baseClass, icon) {
				var $span = $(span);

				if (typeof icon === "string") {
					$span.attr("class", baseClass + " " + icon);
				} else {
					// support object syntax: { text: ligature, addClasse: classname }
					if (icon.text) {
						$span.text("" + icon.text);
					} else if (icon.html) {
						span.innerHTML = icon.html;
					}
					$span.attr(
						"class",
						baseClass + " " + (icon.addClass || "")
					);
				}
			}
1236905
function svgToPng(rootFolder, currentFile, $) {
    var currentDirectory = path.dirname(currentFile);

    return editHTMLElement($, 'img', function($img) {
        var src = $img.attr('src');
        if (path.extname(src) !== '.svg') {
            return;
        }

        // Calcul absolute path for this
        src = LocationUtils.toAbsolute(src, currentDirectory, '.');

        // We avoid generating twice the same PNG
        var hash = crc.crc32(src).toString(16);
        var fileName = hash + '.png';

        // Input file path
        var inputPath = path.join(rootFolder, src);

        // Result file path
        var filePath = path.join(rootFolder, fileName);

        return fs.assertFile(filePath, function() {
            return imagesUtil.convertSVGToPNG(inputPath, filePath);
        })
        .then(function() {
            // Convert filename to a relative filename
            fileName = LocationUtils.relative(currentDirectory, fileName);

            // Replace src
            $img.attr('src', fileName);
        });
    });
}
395520
function _appendNode(parent, child) {
  var parentName = _getHTMLNodeName(parent);

  var childName = _getHTMLNodeName(child);

  if (doc.createStyleSheet) {
    if (parentName === 'script') {
      parent.text = child.nodeValue;
      return;
    }

    if (parentName === 'style') {
      parent.cssText = child.nodeValue; // This will not apply it--just make it available within the DOM cotents

      return;
    }
  }

  if (parentName === 'template') {
    parent.content.appendChild(child);
    return;
  }

  try {
    parent.appendChild(child); // IE9 is now ok with this
  } catch (e) {
    if (parentName === 'select' && childName === 'option') {
      try {
        // Since this is now DOM Level 4 standard behavior (and what IE7+ can handle), we try it first
        parent.add(child);
      } catch (err) {
        // DOM Level 2 did require a second argument, so we try it too just in case the user is using an older version of Firefox, etc.
        parent.add(child, null); // IE7 has a problem with this, but IE8+ is ok
      }

      return;
    }

    throw e;
  }
}
895391
function () {
      $("#addtrack").css("visibility","hidden");
      var element = document.getElementsByTagName('path')[0];
      element.setAttribute("stroke" , "black"); 
      element.setAttribute("fill" , "none");
      element = document.getElementsByTagName('line');
      for( var i=0 ; i<element.length ; i++)
      {
        element[i].setAttribute("stroke" , "black");
        element[i].setAttribute("fill" , "none");
          
      }
      var svg = document.querySelector(spec.timelineDiv+" svg");
      var serializer = new XMLSerializer();
      var source = serializer.serializeToString(svg);
      var link = document.createElement("a");

      //name spaces
      if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
          source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
      }
      if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
          source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
      }
      //xml declaration
      source = '<?xml version="1.0" standalone="no"?>\r\n' + source;

      //converting SVG source to URI data scheme.
      var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);
      link.download = "clinical-timeline.svg";
      link.href = url;
      link.click();
      $("#addtrack").css("visibility","visible");
    }
817933
function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);
			
			
			function submit() {
				// This submits the form, which returns the file data using svgEditor.processFile()
				form.submit();
				
				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}
			
			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.processFile()
					submit();
				});
			}
		}
1303371
function appendHTML() {
		if (!$box && document.body) {
			init = false;
			$window = $(window);
			$box = $tag(div).attr({
				id: colorbox,
				'class': $.support.opacity === false ? prefix + 'IE' : '', // class for optional IE8 & lower targeted CSS.
				role: 'dialog',
				tabindex: '-1'
			}).hide();
			$overlay = $tag(div, "Overlay").hide();
			$loadingOverlay = $([$tag(div, "LoadingOverlay")[0],$tag(div, "LoadingGraphic")[0]]);
			$wrap = $tag(div, "Wrapper");
			$content = $tag(div, "Content").append(
				$title = $tag(div, "Title"),
				$current = $tag(div, "Current"),
				$prev = $('<button type="button"/>').attr({id:prefix+'Previous'}),
				$next = $('<button type="button"/>').attr({id:prefix+'Next'}),
				$slideshow = $tag('button', "Slideshow"),
				$loadingOverlay
			);

			$close = $('<button type="button"/>').attr({id:prefix+'Close'});
			
			$wrap.append( // The 3x3 Grid that makes up Colorbox
				$tag(div).append(
					$tag(div, "TopLeft"),
					$topBorder = $tag(div, "TopCenter"),
					$tag(div, "TopRight")
				),
				$tag(div, false, 'clear:left').append(
					$leftBorder = $tag(div, "MiddleLeft"),
					$content,
					$rightBorder = $tag(div, "MiddleRight")
				),
				$tag(div, false, 'clear:left').append(
					$tag(div, "BottomLeft"),
					$bottomBorder = $tag(div, "BottomCenter"),
					$tag(div, "BottomRight")
				)
			).find('div div').css({'float': 'left'});
			
			$loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none');
			
			$groupControls = $next.add($prev).add($current).add($slideshow);

			$(document.body).append($overlay, $box.append($wrap, $loadingBay));
		}
	}
580819
function SVGLoader(loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.Types.SVG);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "data";

		if (preferXHR) {
			this.setTag(createjs.Elements.svg());
		} else {
			this.setTag(createjs.Elements.object());
			this.getTag().type = "image/svg+xml";
		}
	}
592123
function append() {
      var items = this.items;
      var _Components$Html = Components.Html,
          wrapper = _Components$Html.wrapper,
          slides = _Components$Html.slides;


      var half = Math.floor(items.length / 2);
      var prepend = items.slice(0, half).reverse();
      var append = items.slice(half, items.length);
      var width = Components.Sizes.slideWidth + 'px';

      for (var i = 0; i < append.length; i++) {
        wrapper.appendChild(append[i]);
      }

      for (var _i2 = 0; _i2 < prepend.length; _i2++) {
        wrapper.insertBefore(prepend[_i2], slides[0]);
      }

      for (var _i3 = 0; _i3 < items.length; _i3++) {
        items[_i3].style.width = width;
      }
    }
1300267
function ( type, css, obj, dom, id ) {

        type = type || 'div';

        if( Tools.SVG_TYPE_D.indexOf(type) !== -1 || Tools.SVG_TYPE_G.indexOf(type) !== -1 ){ // is svg element

            // create new svg if not def
            if( dom === undefined ) dom = Tools.doc.createElementNS( Tools.svgns, 'svg' );

            Tools.addAttributes( dom, type, obj, id );
            
        } else { // is html element

            if( dom === undefined ) dom = Tools.doc.createElementNS( Tools.htmls, type );
            else dom = dom.appendChild( Tools.doc.createElementNS( Tools.htmls, type ) );

        }

        if( css ) dom.style.cssText = css; 

        if( id === undefined ) return dom;
        else return dom.childNodes[ id || 0 ];

    }
732279
public Element render(SVGPlot svgp) {
    Element tag = svgp.svgElement(SVGConstants.SVG_G_TAG);
    Element button = svgp.svgRect(x, y, w, h);
    if(!Double.isNaN(r)) {
      SVGUtil.setAtt(button, SVGConstants.SVG_RX_ATTRIBUTE, r);
      SVGUtil.setAtt(button, SVGConstants.SVG_RY_ATTRIBUTE, r);
    }
    SVGUtil.setAtt(button, SVGConstants.SVG_STYLE_ATTRIBUTE, butcss.inlineCSS());
    tag.appendChild(button);
    // Add light effect:
    if (svgp.getIdElement(SVGEffects.LIGHT_GRADIENT_ID) != null) {
      Element light = svgp.svgRect(x, y, w, h);      
      if(!Double.isNaN(r)) {
        SVGUtil.setAtt(light, SVGConstants.SVG_RX_ATTRIBUTE, r);
        SVGUtil.setAtt(light, SVGConstants.SVG_RY_ATTRIBUTE, r);
      }
      SVGUtil.setAtt(light, SVGConstants.SVG_STYLE_ATTRIBUTE, "fill:url(#"+SVGEffects.LIGHT_GRADIENT_ID+");fill-opacity:.5");
      tag.appendChild(light);
    }

    // Add shadow effect:
    if(svgp.getIdElement(SVGEffects.SHADOW_ID) != null) {
      //Element shadow = svgp.svgRect(x + (w * .05), y + (h * .05), w, h);
      //SVGUtil.setAtt(button, SVGConstants.SVG_STYLE_ATTRIBUTE, SVGConstants.CSS_FILL_PROPERTY + ":" + SVGConstants.CSS_BLACK_VALUE);
      button.setAttribute(SVGConstants.SVG_FILTER_ATTRIBUTE, "url(#" + SVGEffects.SHADOW_ID + ")");
      //tag.appendChild(shadow);
    }

    if(title != null) {
      Element label = svgp.svgText(x + w * .5, y + h * .7, title);
      label.setAttribute(SVGConstants.SVG_STYLE_ATTRIBUTE, titlecss.inlineCSS());
      tag.appendChild(label);
    }
    return tag;
  }
54719
function (str, x, y) {
		var defaultChartStyle = defaultOptions.chart.style,
			wrapper = this.createElement('span'),
			attrSetters = wrapper.attrSetters,
			element = wrapper.element,
			renderer = wrapper.renderer;

		// Text setter
		attrSetters.text = function (value) {
			if (value !== element.innerHTML) {
				delete this.bBox;
			}
			element.innerHTML = value;
			return false;
		};

		// Various setters which rely on update transform
		attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) {
			if (key === 'align') {
				key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
			}
			wrapper[key] = value;
			wrapper.htmlUpdateTransform();
			return false;
		};

		// Set the default attributes
		wrapper.attr({
				text: str,
				x: mathRound(x),
				y: mathRound(y)
			})
			.css({
				position: ABSOLUTE,
				whiteSpace: 'nowrap',
				fontFamily: defaultChartStyle.fontFamily,
				fontSize: defaultChartStyle.fontSize
			});

		// Use the HTML specific .css method
		wrapper.css = wrapper.htmlCss;

		// This is specific for HTML within SVG
		if (renderer.isSVG) {
			wrapper.add = function (svgGroupWrapper) {

				var htmlGroup,
					container = renderer.box.parentNode,
					parentGroup,
					parents = [];

				// Create a mock group to hold the HTML elements
				if (svgGroupWrapper) {
					htmlGroup = svgGroupWrapper.div;
					if (!htmlGroup) {

						// Read the parent chain into an array and read from top down
						parentGroup = svgGroupWrapper;
						while (parentGroup) {

							parents.push(parentGroup);

							// Move up to the next parent group
							parentGroup = parentGroup.parentGroup;
						}

						// Ensure dynamically updating position when any parent is translated
						each(parents.reverse(), function (parentGroup) {
							var htmlGroupStyle;

							// Create a HTML div and append it to the parent div to emulate
							// the SVG group structure
							htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
								className: attr(parentGroup.element, 'class')
							}, {
								position: ABSOLUTE,
								left: (parentGroup.translateX || 0) + PX,
								top: (parentGroup.translateY || 0) + PX
							}, htmlGroup || container); // the top group is appended to container

							// Shortcut
							htmlGroupStyle = htmlGroup.style;

							// Set listeners to update the HTML div's position whenever the SVG group
							// position is changed
							extend(parentGroup.attrSetters, {
								translateX: function (value) {
									htmlGroupStyle.left = value + PX;
								},
								translateY: function (value) {
									htmlGroupStyle.top = value + PX;
								},
								visibility: function (value, key) {
									htmlGroupStyle[key] = value;
								}
							});
						});

					}
				} else {
					htmlGroup = container;
				}

				htmlGroup.appendChild(element);

				// Shared with VML:
				wrapper.added = true;
				if (wrapper.alignOnAdd) {
					wrapper.htmlUpdateTransform();
				}

				return wrapper;
			};
		}
		return wrapper;
	}
1365026
function savePNG(svg, scaleFactor) {
    svg.selectAll(classes.join(', ')).each(function inlineProps() {
        const element = this;
        const computedStyle = getComputedStyle(element, null);

        // loop through and compute inline svg styles
        for (let i = 0; i < computedStyle.length; i += 1) {
            const property = computedStyle.item(i);
            const value = computedStyle.getPropertyValue(property);
            element.style[property] = value;
        }
    });

    saveSvgAsPng(
        svg.node(),
        `${svg
            .select('title')
            .text()
            .replace(/\s/g, '-')
            .toLowerCase()}.png`,
        { scale: scaleFactor },
    );
}