User:Lucia Dossin/Protyping/Modules/SVG

From XPUB & Lens-Based wiki

Deep Blue

SVG in the browser, controlled by javascript. We used svgpan, a JS library by Andrea Leofreddi, as basis for this module.
As you scroll, the SVG rectangle changes its color, going to pure blue to dark blue as you go deeper into it. It then goes to black and finally to white.

Demo: http://headroom.pzwart.wdka.hro.nl/~ldossin/deep-blue/drawing.svg

Below, the graphical version of the color transformation path:
Deep-blue-path.png

A few functions were added to the original code: setColor and setOpacity. I ended up not using setOpacity, but left it there. Functions are called in handleMouseWheel function, using the delta as component in the amount parameter.

Code

Initial Version

Below the array containing the hexa color values, used in setColor(). In this version, the array was built manually, adding or subtracting 5 to R, G and B values using an image editing software.

/**
 * Changes the color of an element
 */
 
var blues = ["#050505","#0a0a0a","#0f0f0f", "#141414", "#191919", "#1e1e1e", "#232323", "#282828", "#2d2d2d", "#323232", "#373737", 
"#3c3c3c", "#414141", "#464646", "#4b4b4b", "#505050", "#555555", "#5a5a5a", "#5f5f5f", "#646464", "#696969", "#6e6e6e", "#737373", 
"#787878", "#7d7d7d", "#828282", "#878787", "#8c8c8c", "#919191", "#969696", "#9b9b9b", "#a0a0a0", "#a5a5a5", "#aaaaaa", "#afafaf", 
"#b4b4b4", "#b9b9b9", "#bebebe", "#c3c3c3", "#c8c8c8", "#cdcdcd", "#d2d2d2", "#d7d7d7", "#e1e1e1", "#e6e6e6", "#ebebeb", "#f0f0f0", 
"#f5f5f5", "#fafafa", "#ffffff", "#fafaff", "#f5f5ff", "#f0f0ff", "#ebebff", "#e6e6ff", "#e1e1ff", "#dcdcff", "#d7d7ff", "#d2d2ff", 
"#cdcdff", "#c8c8ff", "#c3c3ff", "#bebeff", "#b9b9ff", "#b4b4ff", "#afafff", "#aaaaff", "#a5a5ff", "#a0a0ff", "#9b9bff", "#9696ff", 
"#9191ff", "#8c8cff", "#8787ff", "#8282ff", "#7d7dff", "#7878ff", "#7373ff", "#6e6eff", "#6969ff", "#6464ff", "#5f5fff", "#5a5aff", 
"#5555ff", "#5050ff", "#4b4bff", "#4646ff", "#4141ff", "#3c3cff", "#3737ff", "#3232ff", "#2d2dff", "#2828ff", "#2323ff", "#1e1eff", 
"#1919ff", "#1414ff", "#0f0fff", "#0a0aff", "#0505ff", "#0000ff", "#0000fa", "#0000f5", "#0000f0", "#0000eb", "#0000e6", "#0000e1", 
"#0000dc", "#0000d7", "#0000d2", "#0000cd", "#0000c8", "#0000c3", "#0000be", "#0000b9", "#0000b4", "#0000af", "#0000aa", "#0000a5", 
"#0000a0", "#00009b", "#000096", "#000091", "#00008c", "#000087", "#000082", "#00007d", "#000078", "#000073", "#00006e", "#000069", 
"#000064", "#00005f", "#00005a", "#000055", "#000050", "#00004b", "#000046", "#000041", "#00003c", "#000037", "#000032", "#00002d", 
"#000028", "#000023", "#00001e", "#000019", "#000014", "#00000f", "#00000a", "#000005", "#000000"];

var it = Math.floor(blues.length/2);
 
//initial color setting
var init_svg = document.getElementById("svg2");
var init_color = blues[it];
init_svg.setAttribute("fill", init_color);
 
function setColor(element, move){
	if (move > 1) {
		it++;
	}else{
		it--;
	}
	if (it < 0){ 
		it = blues.length-1;
	}
	if (it > blues.length) {
		it = 0;
	}
	element.setAttribute("fill", blues[it]);
}
/**
 * Changes the opacity of an element
 */
var opac = .5;
 
function setOpacity(element, amount){
	opac = opac * amount;
	element.setAttribute("fill-opacity", opac);
}

And then the call to these functions can be found in the last lines of handleMouseWheel function.

//setOpacity(g, z);
	
setColor(g, z);

The original svg code, generated by Inkscape, was also slightly modified - the color fill property was removed from the xml and was set through javascript (see below).

//initial color setting
var init_svg = document.getElementById("svg2");
var init_color = blues[it];
init_svg.setAttribute("fill", init_color);

SVG code

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   id="svg2"
   version="1.1"
   inkscape:version="0.48.4 r9939"
   sodipodi:docname="New document 1">
   <script xlink:href="SVGPan.js"/>
  <defs
     id="defs4">
    <inkscape:perspective
       sodipodi:type="inkscape:persp3d"
       inkscape:vp_x="0 : 526.18109 : 1"
       inkscape:vp_y="0 : 1000 : 0"
       inkscape:vp_z="744.09448 : 526.18109 : 1"
       inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
       id="perspective2985" />
  </defs>
  <sodipodi:namedview
     id="base"
     pagecolor="#ffffff"
     bordercolor="#666666"
     borderopacity="1.0"
     inkscape:pageopacity="0.0"
     inkscape:pageshadow="2"
     inkscape:zoom="0.35"
     inkscape:cx="366.42857"
     inkscape:cy="640"
     inkscape:document-units="px"
     inkscape:current-layer="layer1"
     showgrid="false"
     inkscape:window-width="1280"
     inkscape:window-height="781"
     inkscape:window-x="0"
     inkscape:window-y="0"
     inkscape:window-maximized="1" />
  <metadata
     id="metadata7">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g
     inkscape:label="Layer 1"
     inkscape:groupmode="layer"
     id="viewport">
    <rect
       style="fill-rule:evenodd;stroke:#000000;stroke-width:0px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
       id="rect3003"
       width="240"
       height="180"
       x="640"
       y="390" />
  </g>
</svg>

JS code (original by Andrea Leofreddi, http://code.google.com/p/svgpan/)

/** 
 *  SVGPan library 1.2.2
 * ======================
 *
 * Given an unique existing element with id "viewport" (or when missing, the 
 * first g-element), including the the library into any SVG adds the following 
 * capabilities:
 *
 *  - Mouse panning
 *  - Mouse zooming (using the wheel)
 *  - Object dragging
 *
 * You can configure the behaviour of the pan/zoom/drag with the variables
 * listed in the CONFIGURATION section of this file.
 *
 * Known issues:
 *
 *  - Zooming (while panning) on Safari has still some issues
 *
 * Releases:
 *
 * 1.2.2, Tue Aug 30 17:21:56 CEST 2011, Andrea Leofreddi
 *	- Fixed viewBox on root tag (#7)
 *	- Improved zoom speed (#2)
 *
 * 1.2.1, Mon Jul  4 00:33:18 CEST 2011, Andrea Leofreddi
 *	- Fixed a regression with mouse wheel (now working on Firefox 5)
 *	- Working with viewBox attribute (#4)
 *	- Added "use strict;" and fixed resulting warnings (#5)
 *	- Added configuration variables, dragging is disabled by default (#3)
 *
 * 1.2, Sat Mar 20 08:42:50 GMT 2010, Zeng Xiaohui
 *	Fixed a bug with browser mouse handler interaction
 *
 * 1.1, Wed Feb  3 17:39:33 GMT 2010, Zeng Xiaohui
 *	Updated the zoom code to support the mouse wheel on Safari/Chrome
 *
 * 1.0, Andrea Leofreddi
 *	First release
 *
 * This code is licensed under the following BSD license:
 *
 * Copyright 2009-2010 Andrea Leofreddi <a.leofreddi@itcharm.com>. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY Andrea Leofreddi ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Andrea Leofreddi OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Andrea Leofreddi.
 */

"use strict";

/// CONFIGURATION 
/// ====>

var enablePan = 1; // 1 or 0: enable or disable panning (default enabled)
var enableZoom = 1; // 1 or 0: enable or disable zooming (default enabled)
var enableDrag = 0; // 1 or 0: enable or disable dragging (default disabled)
var zoomScale = 0.2; // Zoom sensitivity

/// <====
/// END OF CONFIGURATION 

var root = document.documentElement;

var state = 'none', svgRoot = null, stateTarget, stateOrigin, stateTf;

setupHandlers(root);

/**
 * Register handlers
 */
function setupHandlers(root){
	setAttributes(root, {
		"onmouseup" : "handleMouseUp(evt)",
		"onmousedown" : "handleMouseDown(evt)",
		"onmousemove" : "handleMouseMove(evt)",
		//"onmouseout" : "handleMouseUp(evt)", // Decomment this to stop the pan functionality when dragging out of the SVG element
	});

	if(navigator.userAgent.toLowerCase().indexOf('webkit') >= 0)
		window.addEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
	else
		window.addEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
}

/**
 * Retrieves the root element for SVG manipulation. The element is then cached into the svgRoot global variable.
 */
function getRoot(root) {
	if(svgRoot == null) {
		var r = root.getElementById("viewport") ? root.getElementById("viewport") : root.documentElement, t = r;

		while(t != root) {
			if(t.getAttribute("viewBox")) {
				setCTM(r, t.getCTM());

				t.removeAttribute("viewBox");
			}

			t = t.parentNode;
		}

		svgRoot = r;
	}

	return svgRoot;
}

/**
 * Instance an SVGPoint object with given event coordinates.
 */
function getEventPoint(evt) {
	var p = root.createSVGPoint();

	p.x = evt.clientX;
	p.y = evt.clientY;

	return p;
}

/**
 * Changes the color of an element
 */
var blues = ["#050505","#0a0a0a","#0f0f0f", "#141414", "#191919", "#1e1e1e", "#232323", "#282828", "#2d2d2d", "#323232", "#373737", 
"#3c3c3c", "#414141", "#464646", "#4b4b4b", "#505050", "#555555", "#5a5a5a", "#5f5f5f", "#646464", "#696969", "#6e6e6e", "#737373", 
"#787878", "#7d7d7d", "#828282", "#878787", "#8c8c8c", "#919191", "#969696", "#9b9b9b", "#a0a0a0", "#a5a5a5", "#aaaaaa", "#afafaf", 
"#b4b4b4", "#b9b9b9", "#bebebe", "#c3c3c3", "#c8c8c8", "#cdcdcd", "#d2d2d2", "#d7d7d7", "#e1e1e1", "#e6e6e6", "#ebebeb", "#f0f0f0", 
"#f5f5f5", "#fafafa", "#ffffff", "#fafaff", "#f5f5ff", "#f0f0ff", "#ebebff", "#e6e6ff", "#e1e1ff", "#dcdcff", "#d7d7ff", "#d2d2ff", 
"#cdcdff", "#c8c8ff", "#c3c3ff", "#bebeff", "#b9b9ff", "#b4b4ff", "#afafff", "#aaaaff", "#a5a5ff", "#a0a0ff", "#9b9bff", "#9696ff", 
"#9191ff", "#8c8cff", "#8787ff", "#8282ff", "#7d7dff", "#7878ff", "#7373ff", "#6e6eff", "#6969ff", "#6464ff", "#5f5fff", "#5a5aff", 
"#5555ff", "#5050ff", "#4b4bff", "#4646ff", "#4141ff", "#3c3cff", "#3737ff", "#3232ff", "#2d2dff", "#2828ff", "#2323ff", "#1e1eff", 
"#1919ff", "#1414ff", "#0f0fff", "#0a0aff", "#0505ff", "#0000ff", "#0000fa", "#0000f5", "#0000f0", "#0000eb", "#0000e6", "#0000e1", 
"#0000dc", "#0000d7", "#0000d2", "#0000cd", "#0000c8", "#0000c3", "#0000be", "#0000b9", "#0000b4", "#0000af", "#0000aa", "#0000a5", 
"#0000a0", "#00009b", "#000096", "#000091", "#00008c", "#000087", "#000082", "#00007d", "#000078", "#000073", "#00006e", "#000069", 
"#000064", "#00005f", "#00005a", "#000055", "#000050", "#00004b", "#000046", "#000041", "#00003c", "#000037", "#000032", "#00002d", 
"#000028", "#000023", "#00001e", "#000019", "#000014", "#00000f", "#00000a", "#000005", "#000000"];

var it = Math.floor(blues.length/2);

//initial color setting
var init_svg = document.getElementById("svg2");
var init_color = blues[it];
init_svg.setAttribute("fill", init_color);

function setColor(element, move){
	if (move > 1) {
		it++;
	}else{
		it--;
	}
	if (it < 0){ 
		it = blues.length-1;
	}
	if (it > blues.length) {
		it = 0;
	}
	element.setAttribute("fill", blues[it]);
}
/**
 * Changes the opacity of an element
 */
var opac = .5;

function setOpacity(element, amount){
	opac = opac * amount;
	element.setAttribute("fill-opacity", opac);
}

/**
 * Sets the current transform matrix of an element.
 */
function setCTM(element, matrix) {
	var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";

	element.setAttribute("transform", s);
}

/**
 * Dumps a matrix to a string (useful for debug).
 */
function dumpMatrix(matrix) {
	var s = "[ " + matrix.a + ", " + matrix.c + ", " + matrix.e + "\n  " + matrix.b + ", " + matrix.d + ", " + matrix.f + "\n  0, 0, 1 ]";

	return s;
}

/**
 * Sets attributes of an element.
 */
function setAttributes(element, attributes){
	for (var i in attributes)
		element.setAttributeNS(null, i, attributes[i]);
}

/**
 * Handle mouse wheel event.
 */
function handleMouseWheel(evt) {
	if(!enableZoom)
		return;

	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	var delta;

	if(evt.wheelDelta)
		delta = evt.wheelDelta / 360; // Chrome/Safari
	else
		delta = evt.detail / -9; // Mozilla

	var z = Math.pow(1 + zoomScale, delta);

	var g = getRoot(svgDoc);
	
	var p = getEventPoint(evt);

	p = p.matrixTransform(g.getCTM().inverse());

	// Compute new scale matrix in current mouse position
	var k = root.createSVGMatrix().translate(p.x, p.y).scale(z).translate(-p.x, -p.y);

        setCTM(g, g.getCTM().multiply(k));


	if(typeof(stateTf) == "undefined")
		stateTf = g.getCTM().inverse();

	stateTf = stateTf.multiply(k.inverse());
	
	//setOpacity(g, z);
	
	setColor(g, z);
	
}

/**
 * Handle mouse move event.
 */
function handleMouseMove(evt) {
	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	var g = getRoot(svgDoc);

	if(state == 'pan' && enablePan) {
		// Pan mode
		var p = getEventPoint(evt).matrixTransform(stateTf);

		setCTM(g, stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y));
	} else if(state == 'drag' && enableDrag) {
		// Drag mode
		var p = getEventPoint(evt).matrixTransform(g.getCTM().inverse());

		setCTM(stateTarget, root.createSVGMatrix().translate(p.x - stateOrigin.x, p.y - stateOrigin.y).multiply(g.getCTM().inverse()).multiply(stateTarget.getCTM()));

		stateOrigin = p;
	}
}

/**
 * Handle click event.
 */
function handleMouseDown(evt) {
	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	var g = getRoot(svgDoc);

	if(
		evt.target.tagName == "svg" 
		|| !enableDrag // Pan anyway when drag is disabled and the user clicked on an element 
	) {
		// Pan mode
		state = 'pan';

		stateTf = g.getCTM().inverse();

		stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
	} else {
		// Drag mode
		state = 'drag';

		stateTarget = evt.target;

		stateTf = g.getCTM().inverse();

		stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
	}
	
}

/**
 * Handle mouse button release event.
 */
function handleMouseUp(evt) {
	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	if(state == 'pan' || state == 'drag') {
		// Quit pan mode
		state = '';
	}
}

Improved(?) Version

While I was manually building the array of hexa values, I realized I could automate this process.

First I did some research on adding hexadecimals: it's like adding decimals, just in base 16. That means that every digit represents a range of 16 values (as opposed to 10 values in decimal).
I found a very helpful explanation at http://mathforum.org/library/drmath/view/55725.html

To be able to perform this operation using JS, I needed parseInt so that I could define base 16 for the variables (and the result). If I simply added two numbers, without specifying they are hexadecimals, I would get a decimal as result.

var int_val = parseInt(value [, base]);

After performing some tests, I realized that the initial zeros are omitted (just like we don't usually write 0001 but simply 1 when we refer to number 1). But because I was dealing with color values, I need a six digit result (000001, for example). That is achieved by the while loop in the code snippet below.

I started defining my initial value, black (var start). I also created an empty array (deepBlue) and a variable to hold the value of the color being added to the array (var adding).

Next, I built the loop. In the example below, I'm looping from black through blue. I'm adding 5 to each hexa value (but only tho the blue component of the color, 000005). I have the feeling that I'm being redundant here (I could probably just use hexadecimal values in the for loop and add the index/iterator to the array), but I'll leave that investigation for another time.

for(var b = 0; b < 255; b=b+5){
	adding = (parseInt(start, 16) + parseInt('000005', 16)).toString(16);
	while (adding.length < 6) { adding = '0' + adding; } // complete with Zeros
	start = adding;
	deepBlue.unshift('#'+adding); //unshift will place the value in the beginning of the array, the opposite of what push does
	//last adding value is blue 0000ff
}

In the loop below, going from blue (0000ff) to white (ffffff). So, leaving the blue component as it is and adding 5 to red and green components (050500).

for(var g = 0; g < 255; g=g+5){
	adding = (parseInt(start, 16) + parseInt('050500', 16)).toString(16);
	while (adding.length < 6) { adding = '0' + adding; } // complete with Zeros
	start = adding;
	deepBlue.unshift('#'+adding);
	//last adding value is white ffffff
}

Next loop, going from white (ffffff) to (nearly) black (050505). This time, I'm subtracting 05 from every RGB component (050505).

for(var r = 0; r < 255; r=r+5){
	adding = (parseInt(start, 16) - parseInt('050505', 16)).toString(16);
	while (adding.length < 6) { adding = '0' + adding; } // complete with Zeros
	start = adding;
	deepBlue.unshift('#'+adding);
	//last adding value is nearly black again 050505
}

Next, I retrieve the full blue as initial color for the SVG fill.

var theBlue = Math.floor(deepBlue.length*2/3);

//initial color setting
var init_svg = document.getElementById("svg2");
var init_color = deepBlue[theBlue]; //'theBlue' is the BLUE color value in 2/3 of the array (#0000ff)
init_svg.setAttribute("fill", init_color);

Below, the setColor function, with update var names.

function setColor(element, move){
	if (move > 1) {
		theBlue++;
	}else{
		theBlue--;
	}
	if (theBlue < 0){ 
		theBlue = deepBlue.length-1;
	}
	if (theBlue >= deepBlue.length) {
		theBlue = 0;
	}
	element.setAttribute("fill", deepBlue[theBlue]);
}

Full JS code below:

/** 
 *  SVGPan library 1.2.2
 * ======================
 *
 * Given an unique existing element with id "viewport" (or when missing, the 
 * first g-element), including the the library into any SVG adds the following 
 * capabilities:
 *
 *  - Mouse panning
 *  - Mouse zooming (using the wheel)
 *  - Object dragging
 *
 * You can configure the behaviour of the pan/zoom/drag with the variables
 * listed in the CONFIGURATION section of this file.
 *
 * Known issues:
 *
 *  - Zooming (while panning) on Safari has still some issues
 *
 * Releases:
 *
 * 1.2.2, Tue Aug 30 17:21:56 CEST 2011, Andrea Leofreddi
 *	- Fixed viewBox on root tag (#7)
 *	- Improved zoom speed (#2)
 *
 * 1.2.1, Mon Jul  4 00:33:18 CEST 2011, Andrea Leofreddi
 *	- Fixed a regression with mouse wheel (now working on Firefox 5)
 *	- Working with viewBox attribute (#4)
 *	- Added "use strict;" and fixed resulting warnings (#5)
 *	- Added configuration variables, dragging is disabled by default (#3)
 *
 * 1.2, Sat Mar 20 08:42:50 GMT 2010, Zeng Xiaohui
 *	Fixed a bug with browser mouse handler interaction
 *
 * 1.1, Wed Feb  3 17:39:33 GMT 2010, Zeng Xiaohui
 *	Updated the zoom code to support the mouse wheel on Safari/Chrome
 *
 * 1.0, Andrea Leofreddi
 *	First release
 *
 * This code is licensed under the following BSD license:
 *
 * Copyright 2009-2010 Andrea Leofreddi <a.leofreddi@itcharm.com>. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY Andrea Leofreddi ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Andrea Leofreddi OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Andrea Leofreddi.
 */

"use strict";

/// CONFIGURATION 
/// ====>

var enablePan = 1; // 1 or 0: enable or disable panning (default enabled)
var enableZoom = 1; // 1 or 0: enable or disable zooming (default enabled)
var enableDrag = 0; // 1 or 0: enable or disable dragging (default disabled)
var zoomScale = 0.05; // Zoom sensitivity

/// <====
/// END OF CONFIGURATION 

var root = document.documentElement;

var state = 'none', svgRoot = null, stateTarget, stateOrigin, stateTf;

setupHandlers(root);

/**
 * Register handlers
 */
function setupHandlers(root){
	setAttributes(root, {
		"onmouseup" : "handleMouseUp(evt)",
		"onmousedown" : "handleMouseDown(evt)",
		"onmousemove" : "handleMouseMove(evt)",
		//"onmouseout" : "handleMouseUp(evt)", // Decomment this to stop the pan functionality when dragging out of the SVG element
	});

	if(navigator.userAgent.toLowerCase().indexOf('webkit') >= 0)
		window.addEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
	else
		window.addEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
}

/**
 * Retrieves the root element for SVG manipulation. The element is then cached into the svgRoot global variable.
 */
function getRoot(root) {
	if(svgRoot == null) {
		var r = root.getElementById("viewport") ? root.getElementById("viewport") : root.documentElement, t = r;

		while(t != root) {
			if(t.getAttribute("viewBox")) {
				setCTM(r, t.getCTM());

				t.removeAttribute("viewBox");
			}

			t = t.parentNode;
		}

		svgRoot = r;
	}

	return svgRoot;
}

/**
 * Instance an SVGPoint object with given event coordinates.
 */
function getEventPoint(evt) {
	var p = root.createSVGPoint();

	p.x = evt.clientX;
	p.y = evt.clientY;

	return p;
}

/**
 * Creates an array of hexa color values and changes the color of the SVG element according to them, on scroll
 */

var deepBlue = [];
var start = '000000'; //black
var adding;

for(var b = 0; b < 255; b=b+5){
	adding = (parseInt(start, 16) + parseInt('000005', 16)).toString(16);
	while (adding.length < 6) { adding = '0' + adding; } // complete with Zeros
	start = adding;
	deepBlue.unshift('#'+adding); //unshift will place the value in the beginning of the array, the opposite of what push does
	//last adding value is blue 0000ff
}

for(var g = 0; g < 255; g=g+5){
	adding = (parseInt(start, 16) + parseInt('050500', 16)).toString(16);
	while (adding.length < 6) { adding = '0' + adding; } // complete with Zeros
	start = adding;
	deepBlue.unshift('#'+adding);
	//last adding value is white ffffff
}

for(var r = 0; r < 255; r=r+5){
	adding = (parseInt(start, 16) - parseInt('050505', 16)).toString(16);
	while (adding.length < 6) { adding = '0' + adding; } // complete with Zeros
	start = adding;
	deepBlue.unshift('#'+adding);
	//last adding value is nearly black again 050505
}

var theBlue = Math.floor(deepBlue.length*2/3);

//initial color setting
var init_svg = document.getElementById("svg2");
var init_color = deepBlue[theBlue]; //'theBlue' is the BLUE color value in 2/3 of the array (#0000ff)
init_svg.setAttribute("fill", init_color);

/**
 * End of Color stuff
 */

function setColor(element, move){
	if (move > 1) {
		theBlue++;
	}else{
		theBlue--;
	}
	if (theBlue < 0){ 
		theBlue = deepBlue.length-1;
	}
	if (theBlue >= deepBlue.length) {
		theBlue = 0;
	}
	element.setAttribute("fill", deepBlue[theBlue]);
}
/**
 * Changes the opacity of an element
 */
var opac = .5;

function setOpacity(element, amount){
	opac = opac * amount;
	element.setAttribute("fill-opacity", opac);
}

/**
 * Sets the current transform matrix of an element.
 */
function setCTM(element, matrix) {
	var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";

	element.setAttribute("transform", s);
}

/**
 * Dumps a matrix to a string (useful for debug).
 */
function dumpMatrix(matrix) {
	var s = "[ " + matrix.a + ", " + matrix.c + ", " + matrix.e + "\n  " + matrix.b + ", " + matrix.d + ", " + matrix.f + "\n  0, 0, 1 ]";

	return s;
}

/**
 * Sets attributes of an element.
 */
function setAttributes(element, attributes){
	for (var i in attributes)
		element.setAttributeNS(null, i, attributes[i]);
}

/**
 * Handle mouse wheel event.
 */
function handleMouseWheel(evt) {
	if(!enableZoom)
		return;

	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	var delta;

	if(evt.wheelDelta)
		delta = evt.wheelDelta / 360; // Chrome/Safari
	else
		delta = evt.detail / -9; // Mozilla

	var z = Math.pow(1 + zoomScale, delta);

	var g = getRoot(svgDoc);
	
	var p = getEventPoint(evt);

	p = p.matrixTransform(g.getCTM().inverse());

	// Compute new scale matrix in current mouse position
	var k = root.createSVGMatrix().translate(p.x, p.y).scale(z).translate(-p.x, -p.y);

        setCTM(g, g.getCTM().multiply(k));


	if(typeof(stateTf) == "undefined")
		stateTf = g.getCTM().inverse();

	stateTf = stateTf.multiply(k.inverse());
	
	//setOpacity(g, z);
	
	setColor(g, z);
	
}

/**
 * Handle mouse move event.
 */
function handleMouseMove(evt) {
	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	var g = getRoot(svgDoc);

	if(state == 'pan' && enablePan) {
		// Pan mode
		var p = getEventPoint(evt).matrixTransform(stateTf);

		setCTM(g, stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y));
	} else if(state == 'drag' && enableDrag) {
		// Drag mode
		var p = getEventPoint(evt).matrixTransform(g.getCTM().inverse());

		setCTM(stateTarget, root.createSVGMatrix().translate(p.x - stateOrigin.x, p.y - stateOrigin.y).multiply(g.getCTM().inverse()).multiply(stateTarget.getCTM()));

		stateOrigin = p;
	}
}

/**
 * Handle click event.
 */
function handleMouseDown(evt) {
	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	var g = getRoot(svgDoc);

	if(
		evt.target.tagName == "svg" 
		|| !enableDrag // Pan anyway when drag is disabled and the user clicked on an element 
	) {
		// Pan mode
		state = 'pan';

		stateTf = g.getCTM().inverse();

		stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
	} else {
		// Drag mode
		state = 'drag';

		stateTarget = evt.target;

		stateTf = g.getCTM().inverse();

		stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
	}
	
}

/**
 * Handle mouse button release event.
 */
function handleMouseUp(evt) {
	if(evt.preventDefault)
		evt.preventDefault();

	evt.returnValue = false;

	var svgDoc = evt.target.ownerDocument;

	if(state == 'pan' || state == 'drag') {
		// Quit pan mode
		state = '';
	}
}