From a6f3f72fa66a05215cbf8f8f1b0b4992fb0e2201 Mon Sep 17 00:00:00 2001 From: jrtechs Date: Sun, 27 May 2018 21:19:43 -0400 Subject: [PATCH] Worked on client side rendering of the graph. --- Diagram.svg | 1 + pom.xml | 7 + .../java/net/jrtechs/www/client/basic.html | 241 ++++ .../java/net/jrtechs/www/client/images.html | 290 +++++ .../jrtechs/www/client/serverConnection.js | 56 + .../client/src/captors/sigma.captors.mouse.js | 349 +++++ .../client/src/captors/sigma.captors.touch.js | 410 ++++++ .../src/classes/sigma.classes.camera.js | 240 ++++ .../src/classes/sigma.classes.configurable.js | 116 ++ .../src/classes/sigma.classes.dispatcher.js | 204 +++ .../src/classes/sigma.classes.edgequad.js | 832 ++++++++++++ .../client/src/classes/sigma.classes.graph.js | 859 +++++++++++++ .../client/src/classes/sigma.classes.quad.js | 674 ++++++++++ .../java/net/jrtechs/www/client/src/conrad.js | 984 ++++++++++++++ .../www/client/src/jquery-2.1.1.min.js | 4 + .../src/middlewares/sigma.middlewares.copy.js | 35 + .../middlewares/sigma.middlewares.rescale.js | 189 +++ .../client/src/misc/sigma.misc.animation.js | 239 ++++ .../src/misc/sigma.misc.bindDOMEvents.js | 156 +++ .../client/src/misc/sigma.misc.bindEvents.js | 509 ++++++++ .../client/src/misc/sigma.misc.drawHovers.js | 222 ++++ .../src/plugins/sigma.exporters.svg/README.md | 41 + .../sigma.exporters.svg.js | 225 ++++ .../sigma.layout.forceAtlas2/Gruntfile.js | 28 + .../sigma.layout.forceAtlas2/README.md | 79 ++ .../sigma.layout.forceAtlas2/supervisor.js | 340 +++++ .../tasks/forceAtlas2.js | 127 ++ .../sigma.layout.forceAtlas2/worker.js | 1129 +++++++++++++++++ .../plugins/sigma.layout.noverlap/README.md | 87 ++ .../sigma.layout.noverlap.js | 408 ++++++ .../src/plugins/sigma.neo4j.cypher/LICENSE | 553 ++++++++ .../src/plugins/sigma.neo4j.cypher/README.md | 58 + .../sigma.neo4j.cypher/sigma.neo4j.cypher.js | 218 ++++ .../src/plugins/sigma.parsers.gexf/README.md | 29 + .../plugins/sigma.parsers.gexf/gexf-parser.js | 551 ++++++++ .../sigma.parsers.gexf/sigma.parsers.gexf.js | 112 ++ .../src/plugins/sigma.parsers.json/README.md | 29 + .../sigma.parsers.json/sigma.parsers.json.js | 88 ++ .../plugins/sigma.pathfinding.astar/LICENSE | 25 + .../plugins/sigma.pathfinding.astar/README.md | 27 + .../sigma.pathfinding.astar.js | 134 ++ .../plugins/sigma.plugins.animate/README.md | 71 ++ .../sigma.plugins.animate.js | 204 +++ .../plugins/sigma.plugins.dragNodes/README.md | 36 + .../sigma.plugins.dragNodes.js | 326 +++++ .../plugins/sigma.plugins.filter/README.md | 187 +++ .../sigma.plugins.filter.js | 504 ++++++++ .../sigma.plugins.neighborhoods/README.md | 24 + .../sigma.plugins.neighborhoods.js | 186 +++ .../sigma.plugins.relativeSize/README.md | 8 + .../sigma.plugins.relativeSize.js | 28 + .../README.md | 21 + .../sigma.canvas.edgehovers.dashed.js | 64 + .../sigma.canvas.edgehovers.dotted.js | 64 + .../sigma.canvas.edgehovers.parallel.js | 77 ++ .../sigma.canvas.edgehovers.tapered.js | 74 ++ .../sigma.canvas.edges.dashed.js | 64 + .../sigma.canvas.edges.dotted.js | 64 + .../sigma.canvas.edges.parallel.js | 77 ++ .../sigma.canvas.edges.tapered.js | 77 ++ .../sigma.renderers.customShapes/README.md | 61 + .../shape-library.js | 162 +++ .../sigma.renderers.customShapes.js | 236 ++++ .../sigma.renderers.edgeDots/README.md | 38 + .../sigma.canvas.edges.dotCurve.js | 114 ++ .../sigma.canvas.edges.dotCurvedArrow.js | 145 +++ .../sigma.renderers.edgeLabels/README.md | 76 ++ .../sigma.renderers.edgeLabels/settings.js | 41 + .../sigma.canvas.edges.labels.curve.js | 112 ++ .../sigma.canvas.edges.labels.curvedArrow.js | 25 + .../sigma.canvas.edges.labels.def.js | 96 ++ .../sigma.renderers.parallelEdges/README.md | 31 + .../sigma.canvas.edgehovers.curve.js | 65 + .../sigma.canvas.edgehovers.curvedArrow.js | 97 ++ .../sigma.canvas.edges.curve.js | 58 + .../sigma.canvas.edges.curvedArrow.js | 89 ++ .../sigma.canvas.edges.labels.curve.js | 112 ++ .../sigma.renderers.parallelEdges/utils.js | 50 + .../sigma.renderers.snapshot/README.md | 36 + .../sigma.renderers.snapshot.js | 122 ++ .../sigma.statistics.HITS.js | 154 +++ .../canvas/sigma.canvas.edgehovers.arrow.js | 76 ++ .../canvas/sigma.canvas.edgehovers.curve.js | 64 + .../sigma.canvas.edgehovers.curvedArrow.js | 96 ++ .../canvas/sigma.canvas.edgehovers.def.js | 57 + .../canvas/sigma.canvas.edges.arrow.js | 66 + .../canvas/sigma.canvas.edges.curve.js | 57 + .../canvas/sigma.canvas.edges.curvedArrow.js | 88 ++ .../canvas/sigma.canvas.edges.def.js | 49 + .../canvas/sigma.canvas.extremities.def.js | 38 + .../canvas/sigma.canvas.hovers.def.js | 106 ++ .../canvas/sigma.canvas.labels.def.js | 44 + .../canvas/sigma.canvas.nodes.def.js | 30 + .../src/renderers/sigma.renderers.canvas.js | 442 +++++++ .../src/renderers/sigma.renderers.def.js | 29 + .../src/renderers/sigma.renderers.svg.js | 479 +++++++ .../src/renderers/sigma.renderers.webgl.js | 717 +++++++++++ .../renderers/svg/sigma.svg.edges.curve.js | 84 ++ .../src/renderers/svg/sigma.svg.edges.def.js | 73 ++ .../src/renderers/svg/sigma.svg.hovers.def.js | 113 ++ .../src/renderers/svg/sigma.svg.labels.def.js | 80 ++ .../src/renderers/svg/sigma.svg.nodes.def.js | 58 + .../src/renderers/svg/sigma.svg.utils.js | 31 + .../webgl/sigma.webgl.edges.arrow.js | 391 ++++++ .../renderers/webgl/sigma.webgl.edges.def.js | 258 ++++ .../renderers/webgl/sigma.webgl.edges.fast.js | 147 +++ .../webgl/sigma.webgl.edges.thickLine.js | 255 ++++ .../webgl/sigma.webgl.edges.thickLineCPU.js | 220 ++++ .../webgl/sigma.webgl.edges.thickLineGPU.js | 255 ++++ .../renderers/webgl/sigma.webgl.nodes.def.js | 201 +++ .../renderers/webgl/sigma.webgl.nodes.fast.js | 176 +++ .../net/jrtechs/www/client/src/sigma.core.js | 739 +++++++++++ .../jrtechs/www/client/src/sigma.export.js | 20 + .../jrtechs/www/client/src/sigma.settings.js | 251 ++++ .../net/jrtechs/www/client/src/supervisor.js | 340 +++++ .../www/client/src/utils/sigma.polyfills.js | 77 ++ .../www/client/src/utils/sigma.utils.js | 1022 +++++++++++++++ .../java/net/jrtechs/www/client/src/worker.js | 1129 +++++++++++++++++ .../net/jrtechs/www/graphDB/SteamGraph.java | 22 +- .../java/net/jrtechs/www/server/Client.java | 58 +- 120 files changed, 23403 insertions(+), 16 deletions(-) create mode 100644 Diagram.svg create mode 100644 src/main/java/net/jrtechs/www/client/basic.html create mode 100644 src/main/java/net/jrtechs/www/client/images.html create mode 100644 src/main/java/net/jrtechs/www/client/serverConnection.js create mode 100644 src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.mouse.js create mode 100644 src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.touch.js create mode 100644 src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.camera.js create mode 100644 src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.configurable.js create mode 100644 src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.dispatcher.js create mode 100644 src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.edgequad.js create mode 100644 src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.graph.js create mode 100644 src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.quad.js create mode 100644 src/main/java/net/jrtechs/www/client/src/conrad.js create mode 100644 src/main/java/net/jrtechs/www/client/src/jquery-2.1.1.min.js create mode 100644 src/main/java/net/jrtechs/www/client/src/middlewares/sigma.middlewares.copy.js create mode 100644 src/main/java/net/jrtechs/www/client/src/middlewares/sigma.middlewares.rescale.js create mode 100644 src/main/java/net/jrtechs/www/client/src/misc/sigma.misc.animation.js create mode 100644 src/main/java/net/jrtechs/www/client/src/misc/sigma.misc.bindDOMEvents.js create mode 100644 src/main/java/net/jrtechs/www/client/src/misc/sigma.misc.bindEvents.js create mode 100644 src/main/java/net/jrtechs/www/client/src/misc/sigma.misc.drawHovers.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.exporters.svg/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.exporters.svg/sigma.exporters.svg.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.layout.forceAtlas2/Gruntfile.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.layout.forceAtlas2/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.layout.forceAtlas2/supervisor.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.layout.forceAtlas2/tasks/forceAtlas2.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.layout.forceAtlas2/worker.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.layout.noverlap/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.layout.noverlap/sigma.layout.noverlap.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.neo4j.cypher/LICENSE create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.neo4j.cypher/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.neo4j.cypher/sigma.neo4j.cypher.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.parsers.gexf/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.parsers.gexf/gexf-parser.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.parsers.gexf/sigma.parsers.gexf.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.parsers.json/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.parsers.json/sigma.parsers.json.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.pathfinding.astar/LICENSE create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.pathfinding.astar/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.pathfinding.astar/sigma.pathfinding.astar.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.animate/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.animate/sigma.plugins.animate.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.dragNodes/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.dragNodes/sigma.plugins.dragNodes.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.filter/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.filter/sigma.plugins.filter.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.neighborhoods/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.neighborhoods/sigma.plugins.neighborhoods.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.relativeSize/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.plugins.relativeSize/sigma.plugins.relativeSize.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edgehovers.dashed.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edgehovers.dotted.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edgehovers.parallel.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edgehovers.tapered.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edges.dashed.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edges.dotted.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edges.parallel.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customEdgeShapes/sigma.canvas.edges.tapered.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customShapes/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customShapes/shape-library.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.customShapes/sigma.renderers.customShapes.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeDots/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeDots/sigma.canvas.edges.dotCurve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeDots/sigma.canvas.edges.dotCurvedArrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeLabels/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeLabels/settings.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeLabels/sigma.canvas.edges.labels.curve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeLabels/sigma.canvas.edges.labels.curvedArrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.edgeLabels/sigma.canvas.edges.labels.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.parallelEdges/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.parallelEdges/sigma.canvas.edgehovers.curve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.parallelEdges/sigma.canvas.edgehovers.curvedArrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.parallelEdges/sigma.canvas.edges.curve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.parallelEdges/sigma.canvas.edges.curvedArrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.parallelEdges/sigma.canvas.edges.labels.curve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.parallelEdges/utils.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.snapshot/README.md create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.renderers.snapshot/sigma.renderers.snapshot.js create mode 100644 src/main/java/net/jrtechs/www/client/src/plugins/sigma.statistics.HITS/sigma.statistics.HITS.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edgehovers.arrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edgehovers.curve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edgehovers.curvedArrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edgehovers.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edges.arrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edges.curve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edges.curvedArrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.edges.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.extremities.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.hovers.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.labels.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/canvas/sigma.canvas.nodes.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/sigma.renderers.canvas.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/sigma.renderers.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/sigma.renderers.svg.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/sigma.renderers.webgl.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/svg/sigma.svg.edges.curve.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/svg/sigma.svg.edges.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/svg/sigma.svg.hovers.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/svg/sigma.svg.labels.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/svg/sigma.svg.nodes.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/svg/sigma.svg.utils.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.edges.arrow.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.edges.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.edges.fast.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.edges.thickLine.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.edges.thickLineCPU.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.edges.thickLineGPU.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.nodes.def.js create mode 100644 src/main/java/net/jrtechs/www/client/src/renderers/webgl/sigma.webgl.nodes.fast.js create mode 100644 src/main/java/net/jrtechs/www/client/src/sigma.core.js create mode 100644 src/main/java/net/jrtechs/www/client/src/sigma.export.js create mode 100644 src/main/java/net/jrtechs/www/client/src/sigma.settings.js create mode 100644 src/main/java/net/jrtechs/www/client/src/supervisor.js create mode 100644 src/main/java/net/jrtechs/www/client/src/utils/sigma.polyfills.js create mode 100644 src/main/java/net/jrtechs/www/client/src/utils/sigma.utils.js create mode 100644 src/main/java/net/jrtechs/www/client/src/worker.js diff --git a/Diagram.svg b/Diagram.svg new file mode 100644 index 0000000..ad8ce63 --- /dev/null +++ b/Diagram.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pom.xml b/pom.xml index f2d7d25..46821b8 100644 --- a/pom.xml +++ b/pom.xml @@ -53,6 +53,13 @@ json 20180130 + + + + org.java-websocket + Java-WebSocket + 1.3.0 + diff --git a/src/main/java/net/jrtechs/www/client/basic.html b/src/main/java/net/jrtechs/www/client/basic.html new file mode 100644 index 0000000..0df856b --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/basic.html @@ -0,0 +1,241 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ + + + + diff --git a/src/main/java/net/jrtechs/www/client/images.html b/src/main/java/net/jrtechs/www/client/images.html new file mode 100644 index 0000000..2da314e --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/images.html @@ -0,0 +1,290 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ + + + + diff --git a/src/main/java/net/jrtechs/www/client/serverConnection.js b/src/main/java/net/jrtechs/www/client/serverConnection.js new file mode 100644 index 0000000..5d5588e --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/serverConnection.js @@ -0,0 +1,56 @@ +var connection = new WebSocket('ws://127.0.0.1:4444'); + +connection.onopen = function () +{ + console.log('Connected!'); + connection.send('Ping'); // Send the message 'Ping' to the server +}; + +// Log errors +connection.onerror = function (error) +{ + console.log('WebSocket Error ' + error); +}; + +function addNodeToGraph(request) +{ + s.graph.addNode({ + id: request.id, + label: request.name, + x: Math.random(), + y: Math.random(), + size: Math.random(), + color: '#666' + }); + s.refresh(); +} + + +function addEdgeToGraph(request) +{ + s.graph.addEdge({ + id: request.id, + source: request.p1, + target: request.p2, + size: Math.random(), + color: '#000' + }); + s.refresh(); +} + + +// Log messages from the server +connection.onmessage = function (e) +{ + var request = JSON.parse(e.data); + + if(request.action == 1) + { + addNodeToGraph(request); + } + else if(request.action == 2) + { + addEdgeToGraph(request); + } + console.log('Server: ' + e.data); +}; \ No newline at end of file diff --git a/src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.mouse.js b/src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.mouse.js new file mode 100644 index 0000000..e3a40c5 --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.mouse.js @@ -0,0 +1,349 @@ +;(function(undefined) { + 'use strict'; + + if (typeof sigma === 'undefined') + throw 'sigma is not declared'; + + // Initialize packages: + sigma.utils.pkg('sigma.captors'); + + /** + * The user inputs default captor. It deals with mouse events, keyboards + * events and touch events. + * + * @param {DOMElement} target The DOM element where the listeners will be + * bound. + * @param {camera} camera The camera related to the target. + * @param {configurable} settings The settings function. + * @return {sigma.captor} The fresh new captor instance. + */ + sigma.captors.mouse = function(target, camera, settings) { + var _self = this, + _target = target, + _camera = camera, + _settings = settings, + + // CAMERA MANAGEMENT: + // ****************** + // The camera position when the user starts dragging: + _startCameraX, + _startCameraY, + _startCameraAngle, + + // The latest stage position: + _lastCameraX, + _lastCameraY, + _lastCameraAngle, + _lastCameraRatio, + + // MOUSE MANAGEMENT: + // ***************** + // The mouse position when the user starts dragging: + _startMouseX, + _startMouseY, + + _isMouseDown, + _isMoving, + _hasDragged, + _downStartTime, + _movingTimeoutId; + + sigma.classes.dispatcher.extend(this); + + sigma.utils.doubleClick(_target, 'click', _doubleClickHandler); + _target.addEventListener('DOMMouseScroll', _wheelHandler, false); + _target.addEventListener('mousewheel', _wheelHandler, false); + _target.addEventListener('mousemove', _moveHandler, false); + _target.addEventListener('mousedown', _downHandler, false); + _target.addEventListener('click', _clickHandler, false); + _target.addEventListener('mouseout', _outHandler, false); + document.addEventListener('mouseup', _upHandler, false); + + + + + /** + * This method unbinds every handlers that makes the captor work. + */ + this.kill = function() { + sigma.utils.unbindDoubleClick(_target, 'click'); + _target.removeEventListener('DOMMouseScroll', _wheelHandler); + _target.removeEventListener('mousewheel', _wheelHandler); + _target.removeEventListener('mousemove', _moveHandler); + _target.removeEventListener('mousedown', _downHandler); + _target.removeEventListener('click', _clickHandler); + _target.removeEventListener('mouseout', _outHandler); + document.removeEventListener('mouseup', _upHandler); + }; + + + + + // MOUSE EVENTS: + // ************* + + /** + * The handler listening to the 'move' mouse event. It will effectively + * drag the graph. + * + * @param {event} e A mouse event. + */ + function _moveHandler(e) { + var x, + y, + pos; + + // Dispatch event: + if (_settings('mouseEnabled')) { + _self.dispatchEvent('mousemove', + sigma.utils.mouseCoords(e)); + + if (_isMouseDown) { + _isMoving = true; + _hasDragged = true; + + if (_movingTimeoutId) + clearTimeout(_movingTimeoutId); + + _movingTimeoutId = setTimeout(function() { + _isMoving = false; + }, _settings('dragTimeout')); + + sigma.misc.animation.killAll(_camera); + + _camera.isMoving = true; + pos = _camera.cameraPosition( + sigma.utils.getX(e) - _startMouseX, + sigma.utils.getY(e) - _startMouseY, + true + ); + + x = _startCameraX - pos.x; + y = _startCameraY - pos.y; + + if (x !== _camera.x || y !== _camera.y) { + _lastCameraX = _camera.x; + _lastCameraY = _camera.y; + + _camera.goTo({ + x: x, + y: y + }); + } + + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue = false; + + e.stopPropagation(); + return false; + } + } + } + + /** + * The handler listening to the 'up' mouse event. It will stop dragging the + * graph. + * + * @param {event} e A mouse event. + */ + function _upHandler(e) { + if (_settings('mouseEnabled') && _isMouseDown) { + _isMouseDown = false; + if (_movingTimeoutId) + clearTimeout(_movingTimeoutId); + + _camera.isMoving = false; + + var x = sigma.utils.getX(e), + y = sigma.utils.getY(e); + + if (_isMoving) { + sigma.misc.animation.killAll(_camera); + sigma.misc.animation.camera( + _camera, + { + x: _camera.x + + _settings('mouseInertiaRatio') * (_camera.x - _lastCameraX), + y: _camera.y + + _settings('mouseInertiaRatio') * (_camera.y - _lastCameraY) + }, + { + easing: 'quadraticOut', + duration: _settings('mouseInertiaDuration') + } + ); + } else if ( + _startMouseX !== x || + _startMouseY !== y + ) + _camera.goTo({ + x: _camera.x, + y: _camera.y + }); + + _self.dispatchEvent('mouseup', + sigma.utils.mouseCoords(e)); + + // Update _isMoving flag: + _isMoving = false; + } + } + + /** + * The handler listening to the 'down' mouse event. It will start observing + * the mouse position for dragging the graph. + * + * @param {event} e A mouse event. + */ + function _downHandler(e) { + if (_settings('mouseEnabled')) { + _startCameraX = _camera.x; + _startCameraY = _camera.y; + + _lastCameraX = _camera.x; + _lastCameraY = _camera.y; + + _startMouseX = sigma.utils.getX(e); + _startMouseY = sigma.utils.getY(e); + + _hasDragged = false; + _downStartTime = (new Date()).getTime(); + + switch (e.which) { + case 2: + // Middle mouse button pressed + // Do nothing. + break; + case 3: + // Right mouse button pressed + _self.dispatchEvent('rightclick', + sigma.utils.mouseCoords(e, _startMouseX, _startMouseY)); + break; + // case 1: + default: + // Left mouse button pressed + _isMouseDown = true; + + _self.dispatchEvent('mousedown', + sigma.utils.mouseCoords(e, _startMouseX, _startMouseY)); + } + } + } + + /** + * The handler listening to the 'out' mouse event. It will just redispatch + * the event. + * + * @param {event} e A mouse event. + */ + function _outHandler(e) { + if (_settings('mouseEnabled')) + _self.dispatchEvent('mouseout'); + } + + /** + * The handler listening to the 'click' mouse event. It will redispatch the + * click event, but with normalized X and Y coordinates. + * + * @param {event} e A mouse event. + */ + function _clickHandler(e) { + if (_settings('mouseEnabled')) { + var event = sigma.utils.mouseCoords(e); + event.isDragging = + (((new Date()).getTime() - _downStartTime) > 100) && _hasDragged; + _self.dispatchEvent('click', event); + } + + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue = false; + + e.stopPropagation(); + return false; + } + + /** + * The handler listening to the double click custom event. It will + * basically zoom into the graph. + * + * @param {event} e A mouse event. + */ + function _doubleClickHandler(e) { + var pos, + ratio, + animation; + + if (_settings('mouseEnabled')) { + ratio = 1 / _settings('doubleClickZoomingRatio'); + + _self.dispatchEvent('doubleclick', + sigma.utils.mouseCoords(e, _startMouseX, _startMouseY)); + + if (_settings('doubleClickEnabled')) { + pos = _camera.cameraPosition( + sigma.utils.getX(e) - sigma.utils.getCenter(e).x, + sigma.utils.getY(e) - sigma.utils.getCenter(e).y, + true + ); + + animation = { + duration: _settings('doubleClickZoomDuration') + }; + + sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); + } + + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue = false; + + e.stopPropagation(); + return false; + } + } + + /** + * The handler listening to the 'wheel' mouse event. It will basically zoom + * in or not into the graph. + * + * @param {event} e A mouse event. + */ + function _wheelHandler(e) { + var pos, + ratio, + animation, + wheelDelta = sigma.utils.getDelta(e); + + if (_settings('mouseEnabled') && _settings('mouseWheelEnabled') && wheelDelta !== 0) { + ratio = wheelDelta > 0 ? + 1 / _settings('zoomingRatio') : + _settings('zoomingRatio'); + + pos = _camera.cameraPosition( + sigma.utils.getX(e) - sigma.utils.getCenter(e).x, + sigma.utils.getY(e) - sigma.utils.getCenter(e).y, + true + ); + + animation = { + duration: _settings('mouseZoomDuration') + }; + + sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); + + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue = false; + + e.stopPropagation(); + return false; + } + } + }; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.touch.js b/src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.touch.js new file mode 100644 index 0000000..0e4d987 --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/captors/sigma.captors.touch.js @@ -0,0 +1,410 @@ +;(function(undefined) { + 'use strict'; + + if (typeof sigma === 'undefined') + throw 'sigma is not declared'; + + // Initialize packages: + sigma.utils.pkg('sigma.captors'); + + /** + * The user inputs default captor. It deals with mouse events, keyboards + * events and touch events. + * + * @param {DOMElement} target The DOM element where the listeners will be + * bound. + * @param {camera} camera The camera related to the target. + * @param {configurable} settings The settings function. + * @return {sigma.captor} The fresh new captor instance. + */ + sigma.captors.touch = function(target, camera, settings) { + var _self = this, + _target = target, + _camera = camera, + _settings = settings, + + // CAMERA MANAGEMENT: + // ****************** + // The camera position when the user starts dragging: + _startCameraX, + _startCameraY, + _startCameraAngle, + _startCameraRatio, + + // The latest stage position: + _lastCameraX, + _lastCameraY, + _lastCameraAngle, + _lastCameraRatio, + + // TOUCH MANAGEMENT: + // ***************** + // Touches that are down: + _downTouches = [], + + _startTouchX0, + _startTouchY0, + _startTouchX1, + _startTouchY1, + _startTouchAngle, + _startTouchDistance, + + _touchMode, + + _isMoving, + _doubleTap, + _movingTimeoutId; + + sigma.classes.dispatcher.extend(this); + + sigma.utils.doubleClick(_target, 'touchstart', _doubleTapHandler); + _target.addEventListener('touchstart', _handleStart, false); + _target.addEventListener('touchend', _handleLeave, false); + _target.addEventListener('touchcancel', _handleLeave, false); + _target.addEventListener('touchleave', _handleLeave, false); + _target.addEventListener('touchmove', _handleMove, false); + + function position(e) { + var offset = sigma.utils.getOffset(_target); + + return { + x: e.pageX - offset.left, + y: e.pageY - offset.top + }; + } + + /** + * This method unbinds every handlers that makes the captor work. + */ + this.kill = function() { + sigma.utils.unbindDoubleClick(_target, 'touchstart'); + _target.addEventListener('touchstart', _handleStart); + _target.addEventListener('touchend', _handleLeave); + _target.addEventListener('touchcancel', _handleLeave); + _target.addEventListener('touchleave', _handleLeave); + _target.addEventListener('touchmove', _handleMove); + }; + + // TOUCH EVENTS: + // ************* + /** + * The handler listening to the 'touchstart' event. It will set the touch + * mode ("_touchMode") and start observing the user touch moves. + * + * @param {event} e A touch event. + */ + function _handleStart(e) { + if (_settings('touchEnabled')) { + var x0, + x1, + y0, + y1, + pos0, + pos1; + + _downTouches = e.touches; + + switch (_downTouches.length) { + case 1: + _camera.isMoving = true; + _touchMode = 1; + + _startCameraX = _camera.x; + _startCameraY = _camera.y; + + _lastCameraX = _camera.x; + _lastCameraY = _camera.y; + + pos0 = position(_downTouches[0]); + _startTouchX0 = pos0.x; + _startTouchY0 = pos0.y; + + break; + case 2: + _camera.isMoving = true; + _touchMode = 2; + + pos0 = position(_downTouches[0]); + pos1 = position(_downTouches[1]); + x0 = pos0.x; + y0 = pos0.y; + x1 = pos1.x; + y1 = pos1.y; + + _lastCameraX = _camera.x; + _lastCameraY = _camera.y; + + _startCameraAngle = _camera.angle; + _startCameraRatio = _camera.ratio; + + _startCameraX = _camera.x; + _startCameraY = _camera.y; + + _startTouchX0 = x0; + _startTouchY0 = y0; + _startTouchX1 = x1; + _startTouchY1 = y1; + + _startTouchAngle = Math.atan2( + _startTouchY1 - _startTouchY0, + _startTouchX1 - _startTouchX0 + ); + _startTouchDistance = Math.sqrt( + (_startTouchY1 - _startTouchY0) * + (_startTouchY1 - _startTouchY0) + + (_startTouchX1 - _startTouchX0) * + (_startTouchX1 - _startTouchX0) + ); + + e.preventDefault(); + return false; + } + } + } + + /** + * The handler listening to the 'touchend', 'touchcancel' and 'touchleave' + * event. It will update the touch mode if there are still at least one + * finger, and stop dragging else. + * + * @param {event} e A touch event. + */ + function _handleLeave(e) { + if (_settings('touchEnabled')) { + _downTouches = e.touches; + var inertiaRatio = _settings('touchInertiaRatio'); + + if (_movingTimeoutId) { + _isMoving = false; + clearTimeout(_movingTimeoutId); + } + + switch (_touchMode) { + case 2: + if (e.touches.length === 1) { + _handleStart(e); + + e.preventDefault(); + break; + } + /* falls through */ + case 1: + _camera.isMoving = false; + _self.dispatchEvent('stopDrag'); + + if (_isMoving) { + _doubleTap = false; + sigma.misc.animation.camera( + _camera, + { + x: _camera.x + + inertiaRatio * (_camera.x - _lastCameraX), + y: _camera.y + + inertiaRatio * (_camera.y - _lastCameraY) + }, + { + easing: 'quadraticOut', + duration: _settings('touchInertiaDuration') + } + ); + } + + _isMoving = false; + _touchMode = 0; + break; + } + } + } + + /** + * The handler listening to the 'touchmove' event. It will effectively drag + * the graph, and eventually zooms and turn it if the user is using two + * fingers. + * + * @param {event} e A touch event. + */ + function _handleMove(e) { + if (!_doubleTap && _settings('touchEnabled')) { + var x0, + x1, + y0, + y1, + cos, + sin, + end, + pos0, + pos1, + diff, + start, + dAngle, + dRatio, + newStageX, + newStageY, + newStageRatio, + newStageAngle; + + _downTouches = e.touches; + _isMoving = true; + + if (_movingTimeoutId) + clearTimeout(_movingTimeoutId); + + _movingTimeoutId = setTimeout(function() { + _isMoving = false; + }, _settings('dragTimeout')); + + switch (_touchMode) { + case 1: + pos0 = position(_downTouches[0]); + x0 = pos0.x; + y0 = pos0.y; + + diff = _camera.cameraPosition( + x0 - _startTouchX0, + y0 - _startTouchY0, + true + ); + + newStageX = _startCameraX - diff.x; + newStageY = _startCameraY - diff.y; + + if (newStageX !== _camera.x || newStageY !== _camera.y) { + _lastCameraX = _camera.x; + _lastCameraY = _camera.y; + + _camera.goTo({ + x: newStageX, + y: newStageY + }); + + _self.dispatchEvent('mousemove', + sigma.utils.mouseCoords(e, pos0.x, pos0.y)); + + _self.dispatchEvent('drag'); + } + break; + case 2: + pos0 = position(_downTouches[0]); + pos1 = position(_downTouches[1]); + x0 = pos0.x; + y0 = pos0.y; + x1 = pos1.x; + y1 = pos1.y; + + start = _camera.cameraPosition( + (_startTouchX0 + _startTouchX1) / 2 - + sigma.utils.getCenter(e).x, + (_startTouchY0 + _startTouchY1) / 2 - + sigma.utils.getCenter(e).y, + true + ); + end = _camera.cameraPosition( + (x0 + x1) / 2 - sigma.utils.getCenter(e).x, + (y0 + y1) / 2 - sigma.utils.getCenter(e).y, + true + ); + + dAngle = Math.atan2(y1 - y0, x1 - x0) - _startTouchAngle; + dRatio = Math.sqrt( + (y1 - y0) * (y1 - y0) + (x1 - x0) * (x1 - x0) + ) / _startTouchDistance; + + // Translation: + x0 = start.x; + y0 = start.y; + + // Homothetic transformation: + newStageRatio = _startCameraRatio / dRatio; + x0 = x0 * dRatio; + y0 = y0 * dRatio; + + // Rotation: + newStageAngle = _startCameraAngle - dAngle; + cos = Math.cos(-dAngle); + sin = Math.sin(-dAngle); + x1 = x0 * cos + y0 * sin; + y1 = y0 * cos - x0 * sin; + x0 = x1; + y0 = y1; + + // Finalize: + newStageX = x0 - end.x + _startCameraX; + newStageY = y0 - end.y + _startCameraY; + + if ( + newStageRatio !== _camera.ratio || + newStageAngle !== _camera.angle || + newStageX !== _camera.x || + newStageY !== _camera.y + ) { + _lastCameraX = _camera.x; + _lastCameraY = _camera.y; + _lastCameraAngle = _camera.angle; + _lastCameraRatio = _camera.ratio; + + _camera.goTo({ + x: newStageX, + y: newStageY, + angle: newStageAngle, + ratio: newStageRatio + }); + + _self.dispatchEvent('drag'); + } + + break; + } + + e.preventDefault(); + return false; + } + } + + /** + * The handler listening to the double tap custom event. It will + * basically zoom into the graph. + * + * @param {event} e A touch event. + */ + function _doubleTapHandler(e) { + var pos, + ratio, + animation; + + if (e.touches && e.touches.length === 1 && _settings('touchEnabled')) { + _doubleTap = true; + + ratio = 1 / _settings('doubleClickZoomingRatio'); + + pos = position(e.touches[0]); + _self.dispatchEvent('doubleclick', + sigma.utils.mouseCoords(e, pos.x, pos.y)); + + if (_settings('doubleClickEnabled')) { + pos = _camera.cameraPosition( + pos.x - sigma.utils.getCenter(e).x, + pos.y - sigma.utils.getCenter(e).y, + true + ); + + animation = { + duration: _settings('doubleClickZoomDuration'), + onComplete: function() { + _doubleTap = false; + } + }; + + sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); + } + + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue = false; + + e.stopPropagation(); + return false; + } + } + }; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.camera.js b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.camera.js new file mode 100644 index 0000000..dcc4c52 --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.camera.js @@ -0,0 +1,240 @@ +;(function(undefined) { + 'use strict'; + + if (typeof sigma === 'undefined') + throw 'sigma is not declared'; + + sigma.utils.pkg('sigma.classes'); + + /** + * The camera constructor. It just initializes its attributes and methods. + * + * @param {string} id The id. + * @param {sigma.classes.graph} graph The graph. + * @param {configurable} settings The settings function. + * @param {?object} options Eventually some overriding options. + * @return {camera} Returns the fresh new camera instance. + */ + sigma.classes.camera = function(id, graph, settings, options) { + sigma.classes.dispatcher.extend(this); + + Object.defineProperty(this, 'graph', { + value: graph + }); + Object.defineProperty(this, 'id', { + value: id + }); + Object.defineProperty(this, 'readPrefix', { + value: 'read_cam' + id + ':' + }); + Object.defineProperty(this, 'prefix', { + value: 'cam' + id + ':' + }); + + this.x = 0; + this.y = 0; + this.ratio = 1; + this.angle = 0; + this.isAnimated = false; + this.settings = (typeof options === 'object' && options) ? + settings.embedObject(options) : + settings; + }; + + /** + * Updates the camera position. + * + * @param {object} coordinates The new coordinates object. + * @return {camera} Returns the camera. + */ + sigma.classes.camera.prototype.goTo = function(coordinates) { + if (!this.settings('enableCamera')) + return this; + + var i, + l, + c = coordinates || {}, + keys = ['x', 'y', 'ratio', 'angle']; + + for (i = 0, l = keys.length; i < l; i++) + if (c[keys[i]] !== undefined) { + if (typeof c[keys[i]] === 'number' && !isNaN(c[keys[i]])) + this[keys[i]] = c[keys[i]]; + else + throw 'Value for "' + keys[i] + '" is not a number.'; + } + + this.dispatchEvent('coordinatesUpdated'); + return this; + }; + + /** + * This method takes a graph and computes for each node and edges its + * coordinates relatively to the center of the camera. Basically, it will + * compute the coordinates that will be used by the graphic renderers. + * + * Since it should be possible to use different cameras and different + * renderers, it is possible to specify a prefix to put before the new + * coordinates (to get something like "node.camera1_x") + * + * @param {?string} read The prefix of the coordinates to read. + * @param {?string} write The prefix of the coordinates to write. + * @param {?object} options Eventually an object of options. Those can be: + * - A restricted nodes array. + * - A restricted edges array. + * - A width. + * - A height. + * @return {camera} Returns the camera. + */ + sigma.classes.camera.prototype.applyView = function(read, write, options) { + options = options || {}; + write = write !== undefined ? write : this.prefix; + read = read !== undefined ? read : this.readPrefix; + + var nodes = options.nodes || this.graph.nodes(), + edges = options.edges || this.graph.edges(); + + var i, + l, + node, + relCos = Math.cos(this.angle) / this.ratio, + relSin = Math.sin(this.angle) / this.ratio, + nodeRatio = Math.pow(this.ratio, this.settings('nodesPowRatio')), + edgeRatio = Math.pow(this.ratio, this.settings('edgesPowRatio')), + xOffset = (options.width || 0) / 2 - this.x * relCos - this.y * relSin, + yOffset = (options.height || 0) / 2 - this.y * relCos + this.x * relSin; + + for (i = 0, l = nodes.length; i < l; i++) { + node = nodes[i]; + node[write + 'x'] = + (node[read + 'x'] || 0) * relCos + + (node[read + 'y'] || 0) * relSin + + xOffset; + node[write + 'y'] = + (node[read + 'y'] || 0) * relCos - + (node[read + 'x'] || 0) * relSin + + yOffset; + node[write + 'size'] = + (node[read + 'size'] || 0) / + nodeRatio; + } + + for (i = 0, l = edges.length; i < l; i++) { + edges[i][write + 'size'] = + (edges[i][read + 'size'] || 0) / + edgeRatio; + } + + return this; + }; + + /** + * This function converts the coordinates of a point from the frame of the + * camera to the frame of the graph. + * + * @param {number} x The X coordinate of the point in the frame of the + * camera. + * @param {number} y The Y coordinate of the point in the frame of the + * camera. + * @return {object} The point coordinates in the frame of the graph. + */ + sigma.classes.camera.prototype.graphPosition = function(x, y, vector) { + var X = 0, + Y = 0, + cos = Math.cos(this.angle), + sin = Math.sin(this.angle); + + // Revert the origin differential vector: + if (!vector) { + X = - (this.x * cos + this.y * sin) / this.ratio; + Y = - (this.y * cos - this.x * sin) / this.ratio; + } + + return { + x: (x * cos + y * sin) / this.ratio + X, + y: (y * cos - x * sin) / this.ratio + Y + }; + }; + + /** + * This function converts the coordinates of a point from the frame of the + * graph to the frame of the camera. + * + * @param {number} x The X coordinate of the point in the frame of the + * graph. + * @param {number} y The Y coordinate of the point in the frame of the + * graph. + * @return {object} The point coordinates in the frame of the camera. + */ + sigma.classes.camera.prototype.cameraPosition = function(x, y, vector) { + var X = 0, + Y = 0, + cos = Math.cos(this.angle), + sin = Math.sin(this.angle); + + // Revert the origin differential vector: + if (!vector) { + X = - (this.x * cos + this.y * sin) / this.ratio; + Y = - (this.y * cos - this.x * sin) / this.ratio; + } + + return { + x: ((x - X) * cos - (y - Y) * sin) * this.ratio, + y: ((y - Y) * cos + (x - X) * sin) * this.ratio + }; + }; + + /** + * This method returns the transformation matrix of the camera. This is + * especially useful to apply the camera view directly in shaders, in case of + * WebGL rendering. + * + * @return {array} The transformation matrix. + */ + sigma.classes.camera.prototype.getMatrix = function() { + var scale = sigma.utils.matrices.scale(1 / this.ratio), + rotation = sigma.utils.matrices.rotation(this.angle), + translation = sigma.utils.matrices.translation(-this.x, -this.y), + matrix = sigma.utils.matrices.multiply( + translation, + sigma.utils.matrices.multiply( + rotation, + scale + ) + ); + + return matrix; + }; + + /** + * Taking a width and a height as parameters, this method returns the + * coordinates of the rectangle representing the camera on screen, in the + * graph's referentiel. + * + * To keep displaying labels of nodes going out of the screen, the method + * keeps a margin around the screen in the returned rectangle. + * + * @param {number} width The width of the screen. + * @param {number} height The height of the screen. + * @return {object} The rectangle as x1, y1, x2 and y2, representing + * two opposite points. + */ + sigma.classes.camera.prototype.getRectangle = function(width, height) { + var widthVect = this.cameraPosition(width, 0, true), + heightVect = this.cameraPosition(0, height, true), + centerVect = this.cameraPosition(width / 2, height / 2, true), + marginX = this.cameraPosition(width / 4, 0, true).x, + marginY = this.cameraPosition(0, height / 4, true).y; + + return { + x1: this.x - centerVect.x - marginX, + y1: this.y - centerVect.y - marginY, + x2: this.x - centerVect.x + marginX + widthVect.x, + y2: this.y - centerVect.y - marginY + widthVect.y, + height: Math.sqrt( + Math.pow(heightVect.x, 2) + + Math.pow(heightVect.y + 2 * marginY, 2) + ) + }; + }; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.configurable.js b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.configurable.js new file mode 100644 index 0000000..09ce1f7 --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.configurable.js @@ -0,0 +1,116 @@ +;(function() { + 'use strict'; + + /** + * This utils aims to facilitate the manipulation of each instance setting. + * Using a function instead of an object brings two main advantages: First, + * it will be easier in the future to catch settings updates through a + * function than an object. Second, giving it a full object will "merge" it + * to the settings object properly, keeping us to have to always add a loop. + * + * @return {configurable} The "settings" function. + */ + var configurable = function() { + var i, + l, + data = {}, + datas = Array.prototype.slice.call(arguments, 0); + + /** + * The method to use to set or get any property of this instance. + * + * @param {string|object} a1 If it is a string and if a2 is undefined, + * then it will return the corresponding + * property. If it is a string and if a2 is + * set, then it will set a2 as the property + * corresponding to a1, and return this. If + * it is an object, then each pair string + + * object(or any other type) will be set as a + * property. + * @param {*?} a2 The new property corresponding to a1 if a1 + * is a string. + * @return {*|configurable} Returns itself or the corresponding + * property. + * + * Polymorphism: + * ************* + * Here are some basic use examples: + * + * > settings = new configurable(); + * > settings('mySetting', 42); + * > settings('mySetting'); // Logs: 42 + * > settings('mySetting', 123); + * > settings('mySetting'); // Logs: 123 + * > settings({mySetting: 456}); + * > settings('mySetting'); // Logs: 456 + * + * Also, it is possible to use the function as a fallback: + * > settings({mySetting: 'abc'}, 'mySetting'); // Logs: 'abc' + * > settings({hisSetting: 'abc'}, 'mySetting'); // Logs: 456 + */ + var settings = function(a1, a2) { + var o, + i, + l, + k; + + if (arguments.length === 1 && typeof a1 === 'string') { + if (data[a1] !== undefined) + return data[a1]; + for (i = 0, l = datas.length; i < l; i++) + if (datas[i][a1] !== undefined) + return datas[i][a1]; + return undefined; + } else if (typeof a1 === 'object' && typeof a2 === 'string') { + return (a1 || {})[a2] !== undefined ? a1[a2] : settings(a2); + } else { + o = (typeof a1 === 'object' && a2 === undefined) ? a1 : {}; + + if (typeof a1 === 'string') + o[a1] = a2; + + for (i = 0, k = Object.keys(o), l = k.length; i < l; i++) + data[k[i]] = o[k[i]]; + + return this; + } + }; + + /** + * This method returns a new configurable function, with new objects + * + * @param {object*} Any number of objects to search in. + * @return {function} Returns the function. Check its documentation to know + * more about how it works. + */ + settings.embedObjects = function() { + var args = datas.concat( + data + ).concat( + Array.prototype.splice.call(arguments, 0) + ); + + return configurable.apply({}, args); + }; + + // Initialize + for (i = 0, l = arguments.length; i < l; i++) + settings(arguments[i]); + + return settings; + }; + + /** + * EXPORT: + * ******* + */ + if (typeof this.sigma !== 'undefined') { + this.sigma.classes = this.sigma.classes || {}; + this.sigma.classes.configurable = configurable; + } else if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) + exports = module.exports = configurable; + exports.configurable = configurable; + } else + this.configurable = configurable; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.dispatcher.js b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.dispatcher.js new file mode 100644 index 0000000..0ce7dca --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.dispatcher.js @@ -0,0 +1,204 @@ +;(function() { + 'use strict'; + + /** + * Dispatcher constructor. + * + * @return {dispatcher} The new dispatcher instance. + */ + var dispatcher = function() { + Object.defineProperty(this, '_handlers', { + value: {} + }); + }; + + + + + /** + * Will execute the handler everytime that the indicated event (or the + * indicated events) will be triggered. + * + * @param {string} events The name of the event (or the events + * separated by spaces). + * @param {function(Object)} handler The handler to bind. + * @return {dispatcher} Returns the instance itself. + */ + dispatcher.prototype.bind = function(events, handler) { + var i, + l, + event, + eArray; + + if ( + arguments.length === 1 && + typeof arguments[0] === 'object' + ) + for (events in arguments[0]) + this.bind(events, arguments[0][events]); + else if ( + arguments.length === 2 && + typeof arguments[1] === 'function' + ) { + eArray = typeof events === 'string' ? events.split(' ') : events; + + for (i = 0, l = eArray.length; i !== l; i += 1) { + event = eArray[i]; + + // Check that event is not '': + if (!event) + continue; + + if (!this._handlers[event]) + this._handlers[event] = []; + + // Using an object instead of directly the handler will make possible + // later to add flags + this._handlers[event].push({ + handler: handler + }); + } + } else + throw 'bind: Wrong arguments.'; + + return this; + }; + + /** + * Removes the handler from a specified event (or specified events). + * + * @param {?string} events The name of the event (or the events + * separated by spaces). If undefined, + * then all handlers are removed. + * @param {?function(object)} handler The handler to unbind. If undefined, + * each handler bound to the event or the + * events will be removed. + * @return {dispatcher} Returns the instance itself. + */ + dispatcher.prototype.unbind = function(events, handler) { + var i, + n, + j, + m, + k, + a, + event, + eArray = typeof events === 'string' ? events.split(' ') : events; + + if (!arguments.length) { + for (k in this._handlers) + delete this._handlers[k]; + return this; + } + + if (handler) { + for (i = 0, n = eArray.length; i !== n; i += 1) { + event = eArray[i]; + if (this._handlers[event]) { + a = []; + for (j = 0, m = this._handlers[event].length; j !== m; j += 1) + if (this._handlers[event][j].handler !== handler) + a.push(this._handlers[event][j]); + + this._handlers[event] = a; + } + + if (this._handlers[event] && this._handlers[event].length === 0) + delete this._handlers[event]; + } + } else + for (i = 0, n = eArray.length; i !== n; i += 1) + delete this._handlers[eArray[i]]; + + return this; + }; + + /** + * Executes each handler bound to the event + * + * @param {string} events The name of the event (or the events separated + * by spaces). + * @param {?object} data The content of the event (optional). + * @return {dispatcher} Returns the instance itself. + */ + dispatcher.prototype.dispatchEvent = function(events, data) { + var i, + n, + j, + m, + a, + event, + eventName, + self = this, + eArray = typeof events === 'string' ? events.split(' ') : events; + + data = data === undefined ? {} : data; + + for (i = 0, n = eArray.length; i !== n; i += 1) { + eventName = eArray[i]; + + if (this._handlers[eventName]) { + event = self.getEvent(eventName, data); + a = []; + + for (j = 0, m = this._handlers[eventName].length; j !== m; j += 1) { + this._handlers[eventName][j].handler(event); + if (!this._handlers[eventName][j].one) + a.push(this._handlers[eventName][j]); + } + + this._handlers[eventName] = a; + } + } + + return this; + }; + + /** + * Return an event object. + * + * @param {string} events The name of the event. + * @param {?object} data The content of the event (optional). + * @return {object} Returns the instance itself. + */ + dispatcher.prototype.getEvent = function(event, data) { + return { + type: event, + data: data || {}, + target: this + }; + }; + + /** + * A useful function to deal with inheritance. It will make the target + * inherit the prototype of the class dispatcher as well as its constructor. + * + * @param {object} target The target. + */ + dispatcher.extend = function(target, args) { + var k; + + for (k in dispatcher.prototype) + if (dispatcher.prototype.hasOwnProperty(k)) + target[k] = dispatcher.prototype[k]; + + dispatcher.apply(target, args); + }; + + + + + /** + * EXPORT: + * ******* + */ + if (typeof this.sigma !== 'undefined') { + this.sigma.classes = this.sigma.classes || {}; + this.sigma.classes.dispatcher = dispatcher; + } else if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) + exports = module.exports = dispatcher; + exports.dispatcher = dispatcher; + } else + this.dispatcher = dispatcher; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.edgequad.js b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.edgequad.js new file mode 100644 index 0000000..fbc5b7f --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.edgequad.js @@ -0,0 +1,832 @@ +;(function(undefined) { + 'use strict'; + + /** + * Sigma Quadtree Module for edges + * =============================== + * + * Author: Sébastien Heymann, + * from the quad of Guillaume Plique (Yomguithereal) + * Version: 0.2 + */ + + + + /** + * Quad Geometric Operations + * ------------------------- + * + * A useful batch of geometric operations used by the quadtree. + */ + + var _geom = { + + /** + * Transforms a graph node with x, y and size into an + * axis-aligned square. + * + * @param {object} A graph node with at least a point (x, y) and a size. + * @return {object} A square: two points (x1, y1), (x2, y2) and height. + */ + pointToSquare: function(n) { + return { + x1: n.x - n.size, + y1: n.y - n.size, + x2: n.x + n.size, + y2: n.y - n.size, + height: n.size * 2 + }; + }, + + /** + * Transforms a graph edge with x1, y1, x2, y2 and size into an + * axis-aligned square. + * + * @param {object} A graph edge with at least two points + * (x1, y1), (x2, y2) and a size. + * @return {object} A square: two points (x1, y1), (x2, y2) and height. + */ + lineToSquare: function(e) { + if (e.y1 < e.y2) { + // (e.x1, e.y1) on top + if (e.x1 < e.x2) { + // (e.x1, e.y1) on left + return { + x1: e.x1 - e.size, + y1: e.y1 - e.size, + x2: e.x2 + e.size, + y2: e.y1 - e.size, + height: e.y2 - e.y1 + e.size * 2 + }; + } + // (e.x1, e.y1) on right + return { + x1: e.x2 - e.size, + y1: e.y1 - e.size, + x2: e.x1 + e.size, + y2: e.y1 - e.size, + height: e.y2 - e.y1 + e.size * 2 + }; + } + + // (e.x2, e.y2) on top + if (e.x1 < e.x2) { + // (e.x1, e.y1) on left + return { + x1: e.x1 - e.size, + y1: e.y2 - e.size, + x2: e.x2 + e.size, + y2: e.y2 - e.size, + height: e.y1 - e.y2 + e.size * 2 + }; + } + // (e.x2, e.y2) on right + return { + x1: e.x2 - e.size, + y1: e.y2 - e.size, + x2: e.x1 + e.size, + y2: e.y2 - e.size, + height: e.y1 - e.y2 + e.size * 2 + }; + }, + + /** + * Transforms a graph edge of type 'curve' with x1, y1, x2, y2, + * control point and size into an axis-aligned square. + * + * @param {object} e A graph edge with at least two points + * (x1, y1), (x2, y2) and a size. + * @param {object} cp A control point (x,y). + * @return {object} A square: two points (x1, y1), (x2, y2) and height. + */ + quadraticCurveToSquare: function(e, cp) { + var pt = sigma.utils.getPointOnQuadraticCurve( + 0.5, + e.x1, + e.y1, + e.x2, + e.y2, + cp.x, + cp.y + ); + + // Bounding box of the two points and the point at the middle of the + // curve: + var minX = Math.min(e.x1, e.x2, pt.x), + maxX = Math.max(e.x1, e.x2, pt.x), + minY = Math.min(e.y1, e.y2, pt.y), + maxY = Math.max(e.y1, e.y2, pt.y); + + return { + x1: minX - e.size, + y1: minY - e.size, + x2: maxX + e.size, + y2: minY - e.size, + height: maxY - minY + e.size * 2 + }; + }, + + /** + * Transforms a graph self loop into an axis-aligned square. + * + * @param {object} n A graph node with a point (x, y) and a size. + * @return {object} A square: two points (x1, y1), (x2, y2) and height. + */ + selfLoopToSquare: function(n) { + // Fitting to the curve is too costly, we compute a larger bounding box + // using the control points: + var cp = sigma.utils.getSelfLoopControlPoints(n.x, n.y, n.size); + + // Bounding box of the point and the two control points: + var minX = Math.min(n.x, cp.x1, cp.x2), + maxX = Math.max(n.x, cp.x1, cp.x2), + minY = Math.min(n.y, cp.y1, cp.y2), + maxY = Math.max(n.y, cp.y1, cp.y2); + + return { + x1: minX - n.size, + y1: minY - n.size, + x2: maxX + n.size, + y2: minY - n.size, + height: maxY - minY + n.size * 2 + }; + }, + + /** + * Checks whether a rectangle is axis-aligned. + * + * @param {object} A rectangle defined by two points + * (x1, y1) and (x2, y2). + * @return {boolean} True if the rectangle is axis-aligned. + */ + isAxisAligned: function(r) { + return r.x1 === r.x2 || r.y1 === r.y2; + }, + + /** + * Compute top points of an axis-aligned rectangle. This is useful in + * cases when the rectangle has been rotated (left, right or bottom up) and + * later operations need to know the top points. + * + * @param {object} An axis-aligned rectangle defined by two points + * (x1, y1), (x2, y2) and height. + * @return {object} A rectangle: two points (x1, y1), (x2, y2) and height. + */ + axisAlignedTopPoints: function(r) { + + // Basic + if (r.y1 === r.y2 && r.x1 < r.x2) + return r; + + // Rotated to right + if (r.x1 === r.x2 && r.y2 > r.y1) + return { + x1: r.x1 - r.height, y1: r.y1, + x2: r.x1, y2: r.y1, + height: r.height + }; + + // Rotated to left + if (r.x1 === r.x2 && r.y2 < r.y1) + return { + x1: r.x1, y1: r.y2, + x2: r.x2 + r.height, y2: r.y2, + height: r.height + }; + + // Bottom's up + return { + x1: r.x2, y1: r.y1 - r.height, + x2: r.x1, y2: r.y1 - r.height, + height: r.height + }; + }, + + /** + * Get coordinates of a rectangle's lower left corner from its top points. + * + * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). + * @return {object} Coordinates of the corner (x, y). + */ + lowerLeftCoor: function(r) { + var width = ( + Math.sqrt( + Math.pow(r.x2 - r.x1, 2) + + Math.pow(r.y2 - r.y1, 2) + ) + ); + + return { + x: r.x1 - (r.y2 - r.y1) * r.height / width, + y: r.y1 + (r.x2 - r.x1) * r.height / width + }; + }, + + /** + * Get coordinates of a rectangle's lower right corner from its top points + * and its lower left corner. + * + * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). + * @param {object} A corner's coordinates (x, y). + * @return {object} Coordinates of the corner (x, y). + */ + lowerRightCoor: function(r, llc) { + return { + x: llc.x - r.x1 + r.x2, + y: llc.y - r.y1 + r.y2 + }; + }, + + /** + * Get the coordinates of all the corners of a rectangle from its top point. + * + * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). + * @return {array} An array of the four corners' coordinates (x, y). + */ + rectangleCorners: function(r) { + var llc = this.lowerLeftCoor(r), + lrc = this.lowerRightCoor(r, llc); + + return [ + {x: r.x1, y: r.y1}, + {x: r.x2, y: r.y2}, + {x: llc.x, y: llc.y}, + {x: lrc.x, y: lrc.y} + ]; + }, + + /** + * Split a square defined by its boundaries into four. + * + * @param {object} Boundaries of the square (x, y, width, height). + * @return {array} An array containing the four new squares, themselves + * defined by an array of their four corners (x, y). + */ + splitSquare: function(b) { + return [ + [ + {x: b.x, y: b.y}, + {x: b.x + b.width / 2, y: b.y}, + {x: b.x, y: b.y + b.height / 2}, + {x: b.x + b.width / 2, y: b.y + b.height / 2} + ], + [ + {x: b.x + b.width / 2, y: b.y}, + {x: b.x + b.width, y: b.y}, + {x: b.x + b.width / 2, y: b.y + b.height / 2}, + {x: b.x + b.width, y: b.y + b.height / 2} + ], + [ + {x: b.x, y: b.y + b.height / 2}, + {x: b.x + b.width / 2, y: b.y + b.height / 2}, + {x: b.x, y: b.y + b.height}, + {x: b.x + b.width / 2, y: b.y + b.height} + ], + [ + {x: b.x + b.width / 2, y: b.y + b.height / 2}, + {x: b.x + b.width, y: b.y + b.height / 2}, + {x: b.x + b.width / 2, y: b.y + b.height}, + {x: b.x + b.width, y: b.y + b.height} + ] + ]; + }, + + /** + * Compute the four axis between corners of rectangle A and corners of + * rectangle B. This is needed later to check an eventual collision. + * + * @param {array} An array of rectangle A's four corners (x, y). + * @param {array} An array of rectangle B's four corners (x, y). + * @return {array} An array of four axis defined by their coordinates (x,y). + */ + axis: function(c1, c2) { + return [ + {x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y}, + {x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y}, + {x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y}, + {x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y} + ]; + }, + + /** + * Project a rectangle's corner on an axis. + * + * @param {object} Coordinates of a corner (x, y). + * @param {object} Coordinates of an axis (x, y). + * @return {object} The projection defined by coordinates (x, y). + */ + projection: function(c, a) { + var l = ( + (c.x * a.x + c.y * a.y) / + (Math.pow(a.x, 2) + Math.pow(a.y, 2)) + ); + + return { + x: l * a.x, + y: l * a.y + }; + }, + + /** + * Check whether two rectangles collide on one particular axis. + * + * @param {object} An axis' coordinates (x, y). + * @param {array} Rectangle A's corners. + * @param {array} Rectangle B's corners. + * @return {boolean} True if the rectangles collide on the axis. + */ + axisCollision: function(a, c1, c2) { + var sc1 = [], + sc2 = []; + + for (var ci = 0; ci < 4; ci++) { + var p1 = this.projection(c1[ci], a), + p2 = this.projection(c2[ci], a); + + sc1.push(p1.x * a.x + p1.y * a.y); + sc2.push(p2.x * a.x + p2.y * a.y); + } + + var maxc1 = Math.max.apply(Math, sc1), + maxc2 = Math.max.apply(Math, sc2), + minc1 = Math.min.apply(Math, sc1), + minc2 = Math.min.apply(Math, sc2); + + return (minc2 <= maxc1 && maxc2 >= minc1); + }, + + /** + * Check whether two rectangles collide on each one of their four axis. If + * all axis collide, then the two rectangles do collide on the plane. + * + * @param {array} Rectangle A's corners. + * @param {array} Rectangle B's corners. + * @return {boolean} True if the rectangles collide. + */ + collision: function(c1, c2) { + var axis = this.axis(c1, c2), + col = true; + + for (var i = 0; i < 4; i++) + col = col && this.axisCollision(axis[i], c1, c2); + + return col; + } + }; + + + /** + * Quad Functions + * ------------ + * + * The Quadtree functions themselves. + * For each of those functions, we consider that in a splitted quad, the + * index of each node is the following: + * 0: top left + * 1: top right + * 2: bottom left + * 3: bottom right + * + * Moreover, the hereafter quad's philosophy is to consider that if an element + * collides with more than one nodes, this element belongs to each of the + * nodes it collides with where other would let it lie on a higher node. + */ + + /** + * Get the index of the node containing the point in the quad + * + * @param {object} point A point defined by coordinates (x, y). + * @param {object} quadBounds Boundaries of the quad (x, y, width, heigth). + * @return {integer} The index of the node containing the point. + */ + function _quadIndex(point, quadBounds) { + var xmp = quadBounds.x + quadBounds.width / 2, + ymp = quadBounds.y + quadBounds.height / 2, + top = (point.y < ymp), + left = (point.x < xmp); + + if (top) { + if (left) + return 0; + else + return 1; + } + else { + if (left) + return 2; + else + return 3; + } + } + + /** + * Get a list of indexes of nodes containing an axis-aligned rectangle + * + * @param {object} rectangle A rectangle defined by two points (x1, y1), + * (x2, y2) and height. + * @param {array} quadCorners An array of the quad nodes' corners. + * @return {array} An array of indexes containing one to + * four integers. + */ + function _quadIndexes(rectangle, quadCorners) { + var indexes = []; + + // Iterating through quads + for (var i = 0; i < 4; i++) + if ((rectangle.x2 >= quadCorners[i][0].x) && + (rectangle.x1 <= quadCorners[i][1].x) && + (rectangle.y1 + rectangle.height >= quadCorners[i][0].y) && + (rectangle.y1 <= quadCorners[i][2].y)) + indexes.push(i); + + return indexes; + } + + /** + * Get a list of indexes of nodes containing a non-axis-aligned rectangle + * + * @param {array} corners An array containing each corner of the + * rectangle defined by its coordinates (x, y). + * @param {array} quadCorners An array of the quad nodes' corners. + * @return {array} An array of indexes containing one to + * four integers. + */ + function _quadCollision(corners, quadCorners) { + var indexes = []; + + // Iterating through quads + for (var i = 0; i < 4; i++) + if (_geom.collision(corners, quadCorners[i])) + indexes.push(i); + + return indexes; + } + + /** + * Subdivide a quad by creating a node at a precise index. The function does + * not generate all four nodes not to potentially create unused nodes. + * + * @param {integer} index The index of the node to create. + * @param {object} quad The quad object to subdivide. + * @return {object} A new quad representing the node created. + */ + function _quadSubdivide(index, quad) { + var next = quad.level + 1, + subw = Math.round(quad.bounds.width / 2), + subh = Math.round(quad.bounds.height / 2), + qx = Math.round(quad.bounds.x), + qy = Math.round(quad.bounds.y), + x, + y; + + switch (index) { + case 0: + x = qx; + y = qy; + break; + case 1: + x = qx + subw; + y = qy; + break; + case 2: + x = qx; + y = qy + subh; + break; + case 3: + x = qx + subw; + y = qy + subh; + break; + } + + return _quadTree( + {x: x, y: y, width: subw, height: subh}, + next, + quad.maxElements, + quad.maxLevel + ); + } + + /** + * Recursively insert an element into the quadtree. Only points + * with size, i.e. axis-aligned squares, may be inserted with this + * method. + * + * @param {object} el The element to insert in the quadtree. + * @param {object} sizedPoint A sized point defined by two top points + * (x1, y1), (x2, y2) and height. + * @param {object} quad The quad in which to insert the element. + * @return {undefined} The function does not return anything. + */ + function _quadInsert(el, sizedPoint, quad) { + if (quad.level < quad.maxLevel) { + + // Searching appropriate quads + var indexes = _quadIndexes(sizedPoint, quad.corners); + + // Iterating + for (var i = 0, l = indexes.length; i < l; i++) { + + // Subdividing if necessary + if (quad.nodes[indexes[i]] === undefined) + quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad); + + // Recursion + _quadInsert(el, sizedPoint, quad.nodes[indexes[i]]); + } + } + else { + + // Pushing the element in a leaf node + quad.elements.push(el); + } + } + + /** + * Recursively retrieve every elements held by the node containing the + * searched point. + * + * @param {object} point The searched point (x, y). + * @param {object} quad The searched quad. + * @return {array} An array of elements contained in the relevant + * node. + */ + function _quadRetrievePoint(point, quad) { + if (quad.level < quad.maxLevel) { + var index = _quadIndex(point, quad.bounds); + + // If node does not exist we return an empty list + if (quad.nodes[index] !== undefined) { + return _quadRetrievePoint(point, quad.nodes[index]); + } + else { + return []; + } + } + else { + return quad.elements; + } + } + + /** + * Recursively retrieve every elements contained within an rectangular area + * that may or may not be axis-aligned. + * + * @param {object|array} rectData The searched area defined either by + * an array of four corners (x, y) in + * the case of a non-axis-aligned + * rectangle or an object with two top + * points (x1, y1), (x2, y2) and height. + * @param {object} quad The searched quad. + * @param {function} collisionFunc The collision function used to search + * for node indexes. + * @param {array?} els The retrieved elements. + * @return {array} An array of elements contained in the + * area. + */ + function _quadRetrieveArea(rectData, quad, collisionFunc, els) { + els = els || {}; + + if (quad.level < quad.maxLevel) { + var indexes = collisionFunc(rectData, quad.corners); + + for (var i = 0, l = indexes.length; i < l; i++) + if (quad.nodes[indexes[i]] !== undefined) + _quadRetrieveArea( + rectData, + quad.nodes[indexes[i]], + collisionFunc, + els + ); + } else + for (var j = 0, m = quad.elements.length; j < m; j++) + if (els[quad.elements[j].id] === undefined) + els[quad.elements[j].id] = quad.elements[j]; + + return els; + } + + /** + * Creates the quadtree object itself. + * + * @param {object} bounds The boundaries of the quad defined by an + * origin (x, y), width and heigth. + * @param {integer} level The level of the quad in the tree. + * @param {integer} maxElements The max number of element in a leaf node. + * @param {integer} maxLevel The max recursion level of the tree. + * @return {object} The quadtree object. + */ + function _quadTree(bounds, level, maxElements, maxLevel) { + return { + level: level || 0, + bounds: bounds, + corners: _geom.splitSquare(bounds), + maxElements: maxElements || 40, + maxLevel: maxLevel || 8, + elements: [], + nodes: [] + }; + } + + + /** + * Sigma Quad Constructor + * ---------------------- + * + * The edgequad API as exposed to sigma. + */ + + /** + * The edgequad core that will become the sigma interface with the quadtree. + * + * property {object} _tree Property holding the quadtree object. + * property {object} _geom Exposition of the _geom namespace for testing. + * property {object} _cache Cache for the area method. + * property {boolean} _enabled Can index and retreive elements. + */ + var edgequad = function() { + this._geom = _geom; + this._tree = null; + this._cache = { + query: false, + result: false + }; + this._enabled = true; + }; + + /** + * Index a graph by inserting its edges into the quadtree. + * + * @param {object} graph A graph instance. + * @param {object} params An object of parameters with at least the quad + * bounds. + * @return {object} The quadtree object. + * + * Parameters: + * ---------- + * bounds: {object} boundaries of the quad defined by its origin (x, y) + * width and heigth. + * prefix: {string?} a prefix for edge geometric attributes. + * maxElements: {integer?} the max number of elements in a leaf node. + * maxLevel: {integer?} the max recursion level of the tree. + */ + edgequad.prototype.index = function(graph, params) { + if (!this._enabled) + return this._tree; + + // Enforcing presence of boundaries + if (!params.bounds) + throw 'sigma.classes.edgequad.index: bounds information not given.'; + + // Prefix + var prefix = params.prefix || '', + cp, + source, + target, + n, + e; + + // Building the tree + this._tree = _quadTree( + params.bounds, + 0, + params.maxElements, + params.maxLevel + ); + + var edges = graph.edges(); + + // Inserting graph edges into the tree + for (var i = 0, l = edges.length; i < l; i++) { + source = graph.nodes(edges[i].source); + target = graph.nodes(edges[i].target); + e = { + x1: source[prefix + 'x'], + y1: source[prefix + 'y'], + x2: target[prefix + 'x'], + y2: target[prefix + 'y'], + size: edges[i][prefix + 'size'] || 0 + }; + + // Inserting edge + if (edges[i].type === 'curve' || edges[i].type === 'curvedArrow') { + if (source.id === target.id) { + n = { + x: source[prefix + 'x'], + y: source[prefix + 'y'], + size: source[prefix + 'size'] || 0 + }; + _quadInsert( + edges[i], + _geom.selfLoopToSquare(n), + this._tree); + } + else { + cp = sigma.utils.getQuadraticControlPoint(e.x1, e.y1, e.x2, e.y2); + _quadInsert( + edges[i], + _geom.quadraticCurveToSquare(e, cp), + this._tree); + } + } + else { + _quadInsert( + edges[i], + _geom.lineToSquare(e), + this._tree); + } + } + + // Reset cache: + this._cache = { + query: false, + result: false + }; + + // remove? + return this._tree; + }; + + /** + * Retrieve every graph edges held by the quadtree node containing the + * searched point. + * + * @param {number} x of the point. + * @param {number} y of the point. + * @return {array} An array of edges retrieved. + */ + edgequad.prototype.point = function(x, y) { + if (!this._enabled) + return []; + + return this._tree ? + _quadRetrievePoint({x: x, y: y}, this._tree) || [] : + []; + }; + + /** + * Retrieve every graph edges within a rectangular area. The methods keep the + * last area queried in cache for optimization reason and will act differently + * for the same reason if the area is axis-aligned or not. + * + * @param {object} A rectangle defined by two top points (x1, y1), (x2, y2) + * and height. + * @return {array} An array of edges retrieved. + */ + edgequad.prototype.area = function(rect) { + if (!this._enabled) + return []; + + var serialized = JSON.stringify(rect), + collisionFunc, + rectData; + + // Returning cache? + if (this._cache.query === serialized) + return this._cache.result; + + // Axis aligned ? + if (_geom.isAxisAligned(rect)) { + collisionFunc = _quadIndexes; + rectData = _geom.axisAlignedTopPoints(rect); + } + else { + collisionFunc = _quadCollision; + rectData = _geom.rectangleCorners(rect); + } + + // Retrieving edges + var edges = this._tree ? + _quadRetrieveArea( + rectData, + this._tree, + collisionFunc + ) : + []; + + // Object to array + var edgesArray = []; + for (var i in edges) + edgesArray.push(edges[i]); + + // Caching + this._cache.query = serialized; + this._cache.result = edgesArray; + + return edgesArray; + }; + + + /** + * EXPORT: + * ******* + */ + if (typeof this.sigma !== 'undefined') { + this.sigma.classes = this.sigma.classes || {}; + this.sigma.classes.edgequad = edgequad; + } else if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) + exports = module.exports = edgequad; + exports.edgequad = edgequad; + } else + this.edgequad = edgequad; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.graph.js b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.graph.js new file mode 100644 index 0000000..c7ebe9d --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.graph.js @@ -0,0 +1,859 @@ +;(function(undefined) { + 'use strict'; + + var _methods = Object.create(null), + _indexes = Object.create(null), + _initBindings = Object.create(null), + _methodBindings = Object.create(null), + _methodBeforeBindings = Object.create(null), + _defaultSettings = { + immutable: true, + clone: true + }, + _defaultSettingsFunction = function(key) { + return _defaultSettings[key]; + }; + + /** + * The graph constructor. It initializes the data and the indexes, and binds + * the custom indexes and methods to its own scope. + * + * Recognized parameters: + * ********************** + * Here is the exhaustive list of every accepted parameters in the settings + * object: + * + * {boolean} clone Indicates if the data have to be cloned in methods + * to add nodes or edges. + * {boolean} immutable Indicates if nodes "id" values and edges "id", + * "source" and "target" values must be set as + * immutable. + * + * @param {?configurable} settings Eventually a settings function. + * @return {graph} The new graph instance. + */ + var graph = function(settings) { + var k, + fn, + data; + + /** + * DATA: + * ***** + * Every data that is callable from graph methods are stored in this "data" + * object. This object will be served as context for all these methods, + * and it is possible to add other type of data in it. + */ + data = { + /** + * SETTINGS FUNCTION: + * ****************** + */ + settings: settings || _defaultSettingsFunction, + + /** + * MAIN DATA: + * ********** + */ + nodesArray: [], + edgesArray: [], + + /** + * GLOBAL INDEXES: + * *************** + * These indexes just index data by ids. + */ + nodesIndex: Object.create(null), + edgesIndex: Object.create(null), + + /** + * LOCAL INDEXES: + * ************** + * These indexes refer from node to nodes. Each key is an id, and each + * value is the array of the ids of related nodes. + */ + inNeighborsIndex: Object.create(null), + outNeighborsIndex: Object.create(null), + allNeighborsIndex: Object.create(null), + + inNeighborsCount: Object.create(null), + outNeighborsCount: Object.create(null), + allNeighborsCount: Object.create(null) + }; + + // Execute bindings: + for (k in _initBindings) + _initBindings[k].call(data); + + // Add methods to both the scope and the data objects: + for (k in _methods) { + fn = __bindGraphMethod(k, data, _methods[k]); + this[k] = fn; + data[k] = fn; + } + }; + + + + + /** + * A custom tool to bind methods such that function that are bound to it will + * be executed anytime the method is called. + * + * @param {string} methodName The name of the method to bind. + * @param {object} scope The scope where the method must be executed. + * @param {function} fn The method itself. + * @return {function} The new method. + */ + function __bindGraphMethod(methodName, scope, fn) { + var result = function() { + var k, + res; + + // Execute "before" bound functions: + for (k in _methodBeforeBindings[methodName]) + _methodBeforeBindings[methodName][k].apply(scope, arguments); + + // Apply the method: + res = fn.apply(scope, arguments); + + // Execute bound functions: + for (k in _methodBindings[methodName]) + _methodBindings[methodName][k].apply(scope, arguments); + + // Return res: + return res; + }; + + return result; + } + + /** + * This custom tool function removes every pair key/value from an hash. The + * goal is to avoid creating a new object while some other references are + * still hanging in some scopes... + * + * @param {object} obj The object to empty. + * @return {object} The empty object. + */ + function __emptyObject(obj) { + var k; + + for (k in obj) + if (!('hasOwnProperty' in obj) || obj.hasOwnProperty(k)) + delete obj[k]; + + return obj; + } + + + + + /** + * This global method adds a method that will be bound to the futurly created + * graph instances. + * + * Since these methods will be bound to their scope when the instances are + * created, it does not use the prototype. Because of that, methods have to + * be added before instances are created to make them available. + * + * Here is an example: + * + * > graph.addMethod('getNodesCount', function() { + * > return this.nodesArray.length; + * > }); + * > + * > var myGraph = new graph(); + * > console.log(myGraph.getNodesCount()); // outputs 0 + * + * @param {string} methodName The name of the method. + * @param {function} fn The method itself. + * @return {object} The global graph constructor. + */ + graph.addMethod = function(methodName, fn) { + if ( + typeof methodName !== 'string' || + typeof fn !== 'function' || + arguments.length !== 2 + ) + throw 'addMethod: Wrong arguments.'; + + if (_methods[methodName] || graph[methodName]) + throw 'The method "' + methodName + '" already exists.'; + + _methods[methodName] = fn; + _methodBindings[methodName] = Object.create(null); + _methodBeforeBindings[methodName] = Object.create(null); + + return this; + }; + + /** + * This global method returns true if the method has already been added, and + * false else. + * + * Here are some examples: + * + * > graph.hasMethod('addNode'); // returns true + * > graph.hasMethod('hasMethod'); // returns true + * > graph.hasMethod('unexistingMethod'); // returns false + * + * @param {string} methodName The name of the method. + * @return {boolean} The result. + */ + graph.hasMethod = function(methodName) { + return !!(_methods[methodName] || graph[methodName]); + }; + + /** + * This global methods attaches a function to a method. Anytime the specified + * method is called, the attached function is called right after, with the + * same arguments and in the same scope. The attached function is called + * right before if the last argument is true, unless the method is the graph + * constructor. + * + * To attach a function to the graph constructor, use 'constructor' as the + * method name (first argument). + * + * The main idea is to have a clean way to keep custom indexes up to date, + * for instance: + * + * > var timesAddNodeCalled = 0; + * > graph.attach('addNode', 'timesAddNodeCalledInc', function() { + * > timesAddNodeCalled++; + * > }); + * > + * > var myGraph = new graph(); + * > console.log(timesAddNodeCalled); // outputs 0 + * > + * > myGraph.addNode({ id: '1' }).addNode({ id: '2' }); + * > console.log(timesAddNodeCalled); // outputs 2 + * + * The idea for calling a function before is to provide pre-processors, for + * instance: + * + * > var colorPalette = { Person: '#C3CBE1', Place: '#9BDEBD' }; + * > graph.attach('addNode', 'applyNodeColorPalette', function(n) { + * > n.color = colorPalette[n.category]; + * > }, true); + * > + * > var myGraph = new graph(); + * > myGraph.addNode({ id: 'n0', category: 'Person' }); + * > console.log(myGraph.nodes('n0').color); // outputs '#C3CBE1' + * + * @param {string} methodName The name of the related method or + * "constructor". + * @param {string} key The key to identify the function to attach. + * @param {function} fn The function to bind. + * @param {boolean} before If true the function is called right before. + * @return {object} The global graph constructor. + */ + graph.attach = function(methodName, key, fn, before) { + if ( + typeof methodName !== 'string' || + typeof key !== 'string' || + typeof fn !== 'function' || + arguments.length < 3 || + arguments.length > 4 + ) + throw 'attach: Wrong arguments.'; + + var bindings; + + if (methodName === 'constructor') + bindings = _initBindings; + else { + if (before) { + if (!_methodBeforeBindings[methodName]) + throw 'The method "' + methodName + '" does not exist.'; + + bindings = _methodBeforeBindings[methodName]; + } + else { + if (!_methodBindings[methodName]) + throw 'The method "' + methodName + '" does not exist.'; + + bindings = _methodBindings[methodName]; + } + } + + if (bindings[key]) + throw 'A function "' + key + '" is already attached ' + + 'to the method "' + methodName + '".'; + + bindings[key] = fn; + + return this; + }; + + /** + * Alias of attach(methodName, key, fn, true). + */ + graph.attachBefore = function(methodName, key, fn) { + return this.attach(methodName, key, fn, true); + }; + + /** + * This methods is just an helper to deal with custom indexes. It takes as + * arguments the name of the index and an object containing all the different + * functions to bind to the methods. + * + * Here is a basic example, that creates an index to keep the number of nodes + * in the current graph. It also adds a method to provide a getter on that + * new index: + * + * > sigma.classes.graph.addIndex('nodesCount', { + * > constructor: function() { + * > this.nodesCount = 0; + * > }, + * > addNode: function() { + * > this.nodesCount++; + * > }, + * > dropNode: function() { + * > this.nodesCount--; + * > } + * > }); + * > + * > sigma.classes.graph.addMethod('getNodesCount', function() { + * > return this.nodesCount; + * > }); + * > + * > var myGraph = new sigma.classes.graph(); + * > console.log(myGraph.getNodesCount()); // outputs 0 + * > + * > myGraph.addNode({ id: '1' }).addNode({ id: '2' }); + * > console.log(myGraph.getNodesCount()); // outputs 2 + * + * @param {string} name The name of the index. + * @param {object} bindings The object containing the functions to bind. + * @return {object} The global graph constructor. + */ + graph.addIndex = function(name, bindings) { + if ( + typeof name !== 'string' || + Object(bindings) !== bindings || + arguments.length !== 2 + ) + throw 'addIndex: Wrong arguments.'; + + if (_indexes[name]) + throw 'The index "' + name + '" already exists.'; + + var k; + + // Store the bindings: + _indexes[name] = bindings; + + // Attach the bindings: + for (k in bindings) + if (typeof bindings[k] !== 'function') + throw 'The bindings must be functions.'; + else + graph.attach(k, name, bindings[k]); + + return this; + }; + + + + + /** + * This method adds a node to the graph. The node must be an object, with a + * string under the key "id". Except for this, it is possible to add any + * other attribute, that will be preserved all along the manipulations. + * + * If the graph option "clone" has a truthy value, the node will be cloned + * when added to the graph. Also, if the graph option "immutable" has a + * truthy value, its id will be defined as immutable. + * + * @param {object} node The node to add. + * @return {object} The graph instance. + */ + graph.addMethod('addNode', function(node) { + // Check that the node is an object and has an id: + if (Object(node) !== node || arguments.length !== 1) + throw 'addNode: Wrong arguments.'; + + if (typeof node.id !== 'string' && typeof node.id !== 'number') + throw 'The node must have a string or number id.'; + + if (this.nodesIndex[node.id]) + throw 'The node "' + node.id + '" already exists.'; + + var k, + id = node.id, + validNode = Object.create(null); + + // Check the "clone" option: + if (this.settings('clone')) { + for (k in node) + if (k !== 'id') + validNode[k] = node[k]; + } else + validNode = node; + + // Check the "immutable" option: + if (this.settings('immutable')) + Object.defineProperty(validNode, 'id', { + value: id, + enumerable: true + }); + else + validNode.id = id; + + // Add empty containers for edges indexes: + this.inNeighborsIndex[id] = Object.create(null); + this.outNeighborsIndex[id] = Object.create(null); + this.allNeighborsIndex[id] = Object.create(null); + + this.inNeighborsCount[id] = 0; + this.outNeighborsCount[id] = 0; + this.allNeighborsCount[id] = 0; + + // Add the node to indexes: + this.nodesArray.push(validNode); + this.nodesIndex[validNode.id] = validNode; + + // Return the current instance: + return this; + }); + + /** + * This method adds an edge to the graph. The edge must be an object, with a + * string under the key "id", and strings under the keys "source" and + * "target" that design existing nodes. Except for this, it is possible to + * add any other attribute, that will be preserved all along the + * manipulations. + * + * If the graph option "clone" has a truthy value, the edge will be cloned + * when added to the graph. Also, if the graph option "immutable" has a + * truthy value, its id, source and target will be defined as immutable. + * + * @param {object} edge The edge to add. + * @return {object} The graph instance. + */ + graph.addMethod('addEdge', function(edge) { + // Check that the edge is an object and has an id: + if (Object(edge) !== edge || arguments.length !== 1) + throw 'addEdge: Wrong arguments.'; + + if (typeof edge.id !== 'string' && typeof edge.id !== 'number') + throw 'The edge must have a string or number id.'; + + if ((typeof edge.source !== 'string' && typeof edge.source !== 'number') || + !this.nodesIndex[edge.source]) + throw 'The edge source must have an existing node id.'; + + if ((typeof edge.target !== 'string' && typeof edge.target !== 'number') || + !this.nodesIndex[edge.target]) + throw 'The edge target must have an existing node id.'; + + if (this.edgesIndex[edge.id]) + throw 'The edge "' + edge.id + '" already exists.'; + + var k, + validEdge = Object.create(null); + + // Check the "clone" option: + if (this.settings('clone')) { + for (k in edge) + if (k !== 'id' && k !== 'source' && k !== 'target') + validEdge[k] = edge[k]; + } else + validEdge = edge; + + // Check the "immutable" option: + if (this.settings('immutable')) { + Object.defineProperty(validEdge, 'id', { + value: edge.id, + enumerable: true + }); + + Object.defineProperty(validEdge, 'source', { + value: edge.source, + enumerable: true + }); + + Object.defineProperty(validEdge, 'target', { + value: edge.target, + enumerable: true + }); + } else { + validEdge.id = edge.id; + validEdge.source = edge.source; + validEdge.target = edge.target; + } + + // Add the edge to indexes: + this.edgesArray.push(validEdge); + this.edgesIndex[validEdge.id] = validEdge; + + if (!this.inNeighborsIndex[validEdge.target][validEdge.source]) + this.inNeighborsIndex[validEdge.target][validEdge.source] = + Object.create(null); + this.inNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] = + validEdge; + + if (!this.outNeighborsIndex[validEdge.source][validEdge.target]) + this.outNeighborsIndex[validEdge.source][validEdge.target] = + Object.create(null); + this.outNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] = + validEdge; + + if (!this.allNeighborsIndex[validEdge.source][validEdge.target]) + this.allNeighborsIndex[validEdge.source][validEdge.target] = + Object.create(null); + this.allNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] = + validEdge; + + if (validEdge.target !== validEdge.source) { + if (!this.allNeighborsIndex[validEdge.target][validEdge.source]) + this.allNeighborsIndex[validEdge.target][validEdge.source] = + Object.create(null); + this.allNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] = + validEdge; + } + + // Keep counts up to date: + this.inNeighborsCount[validEdge.target]++; + this.outNeighborsCount[validEdge.source]++; + this.allNeighborsCount[validEdge.target]++; + this.allNeighborsCount[validEdge.source]++; + + return this; + }); + + /** + * This method drops a node from the graph. It also removes each edge that is + * bound to it, through the dropEdge method. An error is thrown if the node + * does not exist. + * + * @param {string} id The node id. + * @return {object} The graph instance. + */ + graph.addMethod('dropNode', function(id) { + // Check that the arguments are valid: + if ((typeof id !== 'string' && typeof id !== 'number') || + arguments.length !== 1) + throw 'dropNode: Wrong arguments.'; + + if (!this.nodesIndex[id]) + throw 'The node "' + id + '" does not exist.'; + + var i, k, l; + + // Remove the node from indexes: + delete this.nodesIndex[id]; + for (i = 0, l = this.nodesArray.length; i < l; i++) + if (this.nodesArray[i].id === id) { + this.nodesArray.splice(i, 1); + break; + } + + // Remove related edges: + for (i = this.edgesArray.length - 1; i >= 0; i--) + if (this.edgesArray[i].source === id || this.edgesArray[i].target === id) + this.dropEdge(this.edgesArray[i].id); + + // Remove related edge indexes: + delete this.inNeighborsIndex[id]; + delete this.outNeighborsIndex[id]; + delete this.allNeighborsIndex[id]; + + delete this.inNeighborsCount[id]; + delete this.outNeighborsCount[id]; + delete this.allNeighborsCount[id]; + + for (k in this.nodesIndex) { + delete this.inNeighborsIndex[k][id]; + delete this.outNeighborsIndex[k][id]; + delete this.allNeighborsIndex[k][id]; + } + + return this; + }); + + /** + * This method drops an edge from the graph. An error is thrown if the edge + * does not exist. + * + * @param {string} id The edge id. + * @return {object} The graph instance. + */ + graph.addMethod('dropEdge', function(id) { + // Check that the arguments are valid: + if ((typeof id !== 'string' && typeof id !== 'number') || + arguments.length !== 1) + throw 'dropEdge: Wrong arguments.'; + + if (!this.edgesIndex[id]) + throw 'The edge "' + id + '" does not exist.'; + + var i, l, edge; + + // Remove the edge from indexes: + edge = this.edgesIndex[id]; + delete this.edgesIndex[id]; + for (i = 0, l = this.edgesArray.length; i < l; i++) + if (this.edgesArray[i].id === id) { + this.edgesArray.splice(i, 1); + break; + } + + delete this.inNeighborsIndex[edge.target][edge.source][edge.id]; + if (!Object.keys(this.inNeighborsIndex[edge.target][edge.source]).length) + delete this.inNeighborsIndex[edge.target][edge.source]; + + delete this.outNeighborsIndex[edge.source][edge.target][edge.id]; + if (!Object.keys(this.outNeighborsIndex[edge.source][edge.target]).length) + delete this.outNeighborsIndex[edge.source][edge.target]; + + delete this.allNeighborsIndex[edge.source][edge.target][edge.id]; + if (!Object.keys(this.allNeighborsIndex[edge.source][edge.target]).length) + delete this.allNeighborsIndex[edge.source][edge.target]; + + if (edge.target !== edge.source) { + delete this.allNeighborsIndex[edge.target][edge.source][edge.id]; + if (!Object.keys(this.allNeighborsIndex[edge.target][edge.source]).length) + delete this.allNeighborsIndex[edge.target][edge.source]; + } + + this.inNeighborsCount[edge.target]--; + this.outNeighborsCount[edge.source]--; + this.allNeighborsCount[edge.source]--; + this.allNeighborsCount[edge.target]--; + + return this; + }); + + /** + * This method destroys the current instance. It basically empties each index + * and methods attached to the graph. + */ + graph.addMethod('kill', function() { + // Delete arrays: + this.nodesArray.length = 0; + this.edgesArray.length = 0; + delete this.nodesArray; + delete this.edgesArray; + + // Delete indexes: + delete this.nodesIndex; + delete this.edgesIndex; + delete this.inNeighborsIndex; + delete this.outNeighborsIndex; + delete this.allNeighborsIndex; + delete this.inNeighborsCount; + delete this.outNeighborsCount; + delete this.allNeighborsCount; + }); + + /** + * This method empties the nodes and edges arrays, as well as the different + * indexes. + * + * @return {object} The graph instance. + */ + graph.addMethod('clear', function() { + this.nodesArray.length = 0; + this.edgesArray.length = 0; + + // Due to GC issues, I prefer not to create new object. These objects are + // only available from the methods and attached functions, but still, it is + // better to prevent ghost references to unrelevant data... + __emptyObject(this.nodesIndex); + __emptyObject(this.edgesIndex); + __emptyObject(this.nodesIndex); + __emptyObject(this.inNeighborsIndex); + __emptyObject(this.outNeighborsIndex); + __emptyObject(this.allNeighborsIndex); + __emptyObject(this.inNeighborsCount); + __emptyObject(this.outNeighborsCount); + __emptyObject(this.allNeighborsCount); + + return this; + }); + + /** + * This method reads an object and adds the nodes and edges, through the + * proper methods "addNode" and "addEdge". + * + * Here is an example: + * + * > var myGraph = new graph(); + * > myGraph.read({ + * > nodes: [ + * > { id: 'n0' }, + * > { id: 'n1' } + * > ], + * > edges: [ + * > { + * > id: 'e0', + * > source: 'n0', + * > target: 'n1' + * > } + * > ] + * > }); + * > + * > console.log( + * > myGraph.nodes().length, + * > myGraph.edges().length + * > ); // outputs 2 1 + * + * @param {object} g The graph object. + * @return {object} The graph instance. + */ + graph.addMethod('read', function(g) { + var i, + a, + l; + + a = g.nodes || []; + for (i = 0, l = a.length; i < l; i++) + this.addNode(a[i]); + + a = g.edges || []; + for (i = 0, l = a.length; i < l; i++) + this.addEdge(a[i]); + + return this; + }); + + /** + * This methods returns one or several nodes, depending on how it is called. + * + * To get the array of nodes, call "nodes" without argument. To get a + * specific node, call it with the id of the node. The get multiple node, + * call it with an array of ids, and it will return the array of nodes, in + * the same order. + * + * @param {?(string|array)} v Eventually one id, an array of ids. + * @return {object|array} The related node or array of nodes. + */ + graph.addMethod('nodes', function(v) { + // Clone the array of nodes and return it: + if (!arguments.length) + return this.nodesArray.slice(0); + + // Return the related node: + if (arguments.length === 1 && + (typeof v === 'string' || typeof v === 'number')) + return this.nodesIndex[v]; + + // Return an array of the related node: + if ( + arguments.length === 1 && + Object.prototype.toString.call(v) === '[object Array]' + ) { + var i, + l, + a = []; + + for (i = 0, l = v.length; i < l; i++) + if (typeof v[i] === 'string' || typeof v[i] === 'number') + a.push(this.nodesIndex[v[i]]); + else + throw 'nodes: Wrong arguments.'; + + return a; + } + + throw 'nodes: Wrong arguments.'; + }); + + /** + * This methods returns the degree of one or several nodes, depending on how + * it is called. It is also possible to get incoming or outcoming degrees + * instead by specifying 'in' or 'out' as a second argument. + * + * @param {string|array} v One id, an array of ids. + * @param {?string} which Which degree is required. Values are 'in', + * 'out', and by default the normal degree. + * @return {number|array} The related degree or array of degrees. + */ + graph.addMethod('degree', function(v, which) { + // Check which degree is required: + which = { + 'in': this.inNeighborsCount, + 'out': this.outNeighborsCount + }[which || ''] || this.allNeighborsCount; + + // Return the related node: + if (typeof v === 'string' || typeof v === 'number') + return which[v]; + + // Return an array of the related node: + if (Object.prototype.toString.call(v) === '[object Array]') { + var i, + l, + a = []; + + for (i = 0, l = v.length; i < l; i++) + if (typeof v[i] === 'string' || typeof v[i] === 'number') + a.push(which[v[i]]); + else + throw 'degree: Wrong arguments.'; + + return a; + } + + throw 'degree: Wrong arguments.'; + }); + + /** + * This methods returns one or several edges, depending on how it is called. + * + * To get the array of edges, call "edges" without argument. To get a + * specific edge, call it with the id of the edge. The get multiple edge, + * call it with an array of ids, and it will return the array of edges, in + * the same order. + * + * @param {?(string|array)} v Eventually one id, an array of ids. + * @return {object|array} The related edge or array of edges. + */ + graph.addMethod('edges', function(v) { + // Clone the array of edges and return it: + if (!arguments.length) + return this.edgesArray.slice(0); + + // Return the related edge: + if (arguments.length === 1 && + (typeof v === 'string' || typeof v === 'number')) + return this.edgesIndex[v]; + + // Return an array of the related edge: + if ( + arguments.length === 1 && + Object.prototype.toString.call(v) === '[object Array]' + ) { + var i, + l, + a = []; + + for (i = 0, l = v.length; i < l; i++) + if (typeof v[i] === 'string' || typeof v[i] === 'number') + a.push(this.edgesIndex[v[i]]); + else + throw 'edges: Wrong arguments.'; + + return a; + } + + throw 'edges: Wrong arguments.'; + }); + + + /** + * EXPORT: + * ******* + */ + if (typeof sigma !== 'undefined') { + sigma.classes = sigma.classes || Object.create(null); + sigma.classes.graph = graph; + } else if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) + exports = module.exports = graph; + exports.graph = graph; + } else + this.graph = graph; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.quad.js b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.quad.js new file mode 100644 index 0000000..fb11386 --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/classes/sigma.classes.quad.js @@ -0,0 +1,674 @@ +;(function(undefined) { + 'use strict'; + + /** + * Sigma Quadtree Module + * ===================== + * + * Author: Guillaume Plique (Yomguithereal) + * Version: 0.2 + */ + + + + /** + * Quad Geometric Operations + * ------------------------- + * + * A useful batch of geometric operations used by the quadtree. + */ + + var _geom = { + + /** + * Transforms a graph node with x, y and size into an + * axis-aligned square. + * + * @param {object} A graph node with at least a point (x, y) and a size. + * @return {object} A square: two points (x1, y1), (x2, y2) and height. + */ + pointToSquare: function(n) { + return { + x1: n.x - n.size, + y1: n.y - n.size, + x2: n.x + n.size, + y2: n.y - n.size, + height: n.size * 2 + }; + }, + + /** + * Checks whether a rectangle is axis-aligned. + * + * @param {object} A rectangle defined by two points + * (x1, y1) and (x2, y2). + * @return {boolean} True if the rectangle is axis-aligned. + */ + isAxisAligned: function(r) { + return r.x1 === r.x2 || r.y1 === r.y2; + }, + + /** + * Compute top points of an axis-aligned rectangle. This is useful in + * cases when the rectangle has been rotated (left, right or bottom up) and + * later operations need to know the top points. + * + * @param {object} An axis-aligned rectangle defined by two points + * (x1, y1), (x2, y2) and height. + * @return {object} A rectangle: two points (x1, y1), (x2, y2) and height. + */ + axisAlignedTopPoints: function(r) { + + // Basic + if (r.y1 === r.y2 && r.x1 < r.x2) + return r; + + // Rotated to right + if (r.x1 === r.x2 && r.y2 > r.y1) + return { + x1: r.x1 - r.height, y1: r.y1, + x2: r.x1, y2: r.y1, + height: r.height + }; + + // Rotated to left + if (r.x1 === r.x2 && r.y2 < r.y1) + return { + x1: r.x1, y1: r.y2, + x2: r.x2 + r.height, y2: r.y2, + height: r.height + }; + + // Bottom's up + return { + x1: r.x2, y1: r.y1 - r.height, + x2: r.x1, y2: r.y1 - r.height, + height: r.height + }; + }, + + /** + * Get coordinates of a rectangle's lower left corner from its top points. + * + * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). + * @return {object} Coordinates of the corner (x, y). + */ + lowerLeftCoor: function(r) { + var width = ( + Math.sqrt( + Math.pow(r.x2 - r.x1, 2) + + Math.pow(r.y2 - r.y1, 2) + ) + ); + + return { + x: r.x1 - (r.y2 - r.y1) * r.height / width, + y: r.y1 + (r.x2 - r.x1) * r.height / width + }; + }, + + /** + * Get coordinates of a rectangle's lower right corner from its top points + * and its lower left corner. + * + * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). + * @param {object} A corner's coordinates (x, y). + * @return {object} Coordinates of the corner (x, y). + */ + lowerRightCoor: function(r, llc) { + return { + x: llc.x - r.x1 + r.x2, + y: llc.y - r.y1 + r.y2 + }; + }, + + /** + * Get the coordinates of all the corners of a rectangle from its top point. + * + * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). + * @return {array} An array of the four corners' coordinates (x, y). + */ + rectangleCorners: function(r) { + var llc = this.lowerLeftCoor(r), + lrc = this.lowerRightCoor(r, llc); + + return [ + {x: r.x1, y: r.y1}, + {x: r.x2, y: r.y2}, + {x: llc.x, y: llc.y}, + {x: lrc.x, y: lrc.y} + ]; + }, + + /** + * Split a square defined by its boundaries into four. + * + * @param {object} Boundaries of the square (x, y, width, height). + * @return {array} An array containing the four new squares, themselves + * defined by an array of their four corners (x, y). + */ + splitSquare: function(b) { + return [ + [ + {x: b.x, y: b.y}, + {x: b.x + b.width / 2, y: b.y}, + {x: b.x, y: b.y + b.height / 2}, + {x: b.x + b.width / 2, y: b.y + b.height / 2} + ], + [ + {x: b.x + b.width / 2, y: b.y}, + {x: b.x + b.width, y: b.y}, + {x: b.x + b.width / 2, y: b.y + b.height / 2}, + {x: b.x + b.width, y: b.y + b.height / 2} + ], + [ + {x: b.x, y: b.y + b.height / 2}, + {x: b.x + b.width / 2, y: b.y + b.height / 2}, + {x: b.x, y: b.y + b.height}, + {x: b.x + b.width / 2, y: b.y + b.height} + ], + [ + {x: b.x + b.width / 2, y: b.y + b.height / 2}, + {x: b.x + b.width, y: b.y + b.height / 2}, + {x: b.x + b.width / 2, y: b.y + b.height}, + {x: b.x + b.width, y: b.y + b.height} + ] + ]; + }, + + /** + * Compute the four axis between corners of rectangle A and corners of + * rectangle B. This is needed later to check an eventual collision. + * + * @param {array} An array of rectangle A's four corners (x, y). + * @param {array} An array of rectangle B's four corners (x, y). + * @return {array} An array of four axis defined by their coordinates (x,y). + */ + axis: function(c1, c2) { + return [ + {x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y}, + {x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y}, + {x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y}, + {x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y} + ]; + }, + + /** + * Project a rectangle's corner on an axis. + * + * @param {object} Coordinates of a corner (x, y). + * @param {object} Coordinates of an axis (x, y). + * @return {object} The projection defined by coordinates (x, y). + */ + projection: function(c, a) { + var l = ( + (c.x * a.x + c.y * a.y) / + (Math.pow(a.x, 2) + Math.pow(a.y, 2)) + ); + + return { + x: l * a.x, + y: l * a.y + }; + }, + + /** + * Check whether two rectangles collide on one particular axis. + * + * @param {object} An axis' coordinates (x, y). + * @param {array} Rectangle A's corners. + * @param {array} Rectangle B's corners. + * @return {boolean} True if the rectangles collide on the axis. + */ + axisCollision: function(a, c1, c2) { + var sc1 = [], + sc2 = []; + + for (var ci = 0; ci < 4; ci++) { + var p1 = this.projection(c1[ci], a), + p2 = this.projection(c2[ci], a); + + sc1.push(p1.x * a.x + p1.y * a.y); + sc2.push(p2.x * a.x + p2.y * a.y); + } + + var maxc1 = Math.max.apply(Math, sc1), + maxc2 = Math.max.apply(Math, sc2), + minc1 = Math.min.apply(Math, sc1), + minc2 = Math.min.apply(Math, sc2); + + return (minc2 <= maxc1 && maxc2 >= minc1); + }, + + /** + * Check whether two rectangles collide on each one of their four axis. If + * all axis collide, then the two rectangles do collide on the plane. + * + * @param {array} Rectangle A's corners. + * @param {array} Rectangle B's corners. + * @return {boolean} True if the rectangles collide. + */ + collision: function(c1, c2) { + var axis = this.axis(c1, c2), + col = true; + + for (var i = 0; i < 4; i++) + col = col && this.axisCollision(axis[i], c1, c2); + + return col; + } + }; + + + /** + * Quad Functions + * ------------ + * + * The Quadtree functions themselves. + * For each of those functions, we consider that in a splitted quad, the + * index of each node is the following: + * 0: top left + * 1: top right + * 2: bottom left + * 3: bottom right + * + * Moreover, the hereafter quad's philosophy is to consider that if an element + * collides with more than one nodes, this element belongs to each of the + * nodes it collides with where other would let it lie on a higher node. + */ + + /** + * Get the index of the node containing the point in the quad + * + * @param {object} point A point defined by coordinates (x, y). + * @param {object} quadBounds Boundaries of the quad (x, y, width, heigth). + * @return {integer} The index of the node containing the point. + */ + function _quadIndex(point, quadBounds) { + var xmp = quadBounds.x + quadBounds.width / 2, + ymp = quadBounds.y + quadBounds.height / 2, + top = (point.y < ymp), + left = (point.x < xmp); + + if (top) { + if (left) + return 0; + else + return 1; + } + else { + if (left) + return 2; + else + return 3; + } + } + + /** + * Get a list of indexes of nodes containing an axis-aligned rectangle + * + * @param {object} rectangle A rectangle defined by two points (x1, y1), + * (x2, y2) and height. + * @param {array} quadCorners An array of the quad nodes' corners. + * @return {array} An array of indexes containing one to + * four integers. + */ + function _quadIndexes(rectangle, quadCorners) { + var indexes = []; + + // Iterating through quads + for (var i = 0; i < 4; i++) + if ((rectangle.x2 >= quadCorners[i][0].x) && + (rectangle.x1 <= quadCorners[i][1].x) && + (rectangle.y1 + rectangle.height >= quadCorners[i][0].y) && + (rectangle.y1 <= quadCorners[i][2].y)) + indexes.push(i); + + return indexes; + } + + /** + * Get a list of indexes of nodes containing a non-axis-aligned rectangle + * + * @param {array} corners An array containing each corner of the + * rectangle defined by its coordinates (x, y). + * @param {array} quadCorners An array of the quad nodes' corners. + * @return {array} An array of indexes containing one to + * four integers. + */ + function _quadCollision(corners, quadCorners) { + var indexes = []; + + // Iterating through quads + for (var i = 0; i < 4; i++) + if (_geom.collision(corners, quadCorners[i])) + indexes.push(i); + + return indexes; + } + + /** + * Subdivide a quad by creating a node at a precise index. The function does + * not generate all four nodes not to potentially create unused nodes. + * + * @param {integer} index The index of the node to create. + * @param {object} quad The quad object to subdivide. + * @return {object} A new quad representing the node created. + */ + function _quadSubdivide(index, quad) { + var next = quad.level + 1, + subw = Math.round(quad.bounds.width / 2), + subh = Math.round(quad.bounds.height / 2), + qx = Math.round(quad.bounds.x), + qy = Math.round(quad.bounds.y), + x, + y; + + switch (index) { + case 0: + x = qx; + y = qy; + break; + case 1: + x = qx + subw; + y = qy; + break; + case 2: + x = qx; + y = qy + subh; + break; + case 3: + x = qx + subw; + y = qy + subh; + break; + } + + return _quadTree( + {x: x, y: y, width: subw, height: subh}, + next, + quad.maxElements, + quad.maxLevel + ); + } + + /** + * Recursively insert an element into the quadtree. Only points + * with size, i.e. axis-aligned squares, may be inserted with this + * method. + * + * @param {object} el The element to insert in the quadtree. + * @param {object} sizedPoint A sized point defined by two top points + * (x1, y1), (x2, y2) and height. + * @param {object} quad The quad in which to insert the element. + * @return {undefined} The function does not return anything. + */ + function _quadInsert(el, sizedPoint, quad) { + if (quad.level < quad.maxLevel) { + + // Searching appropriate quads + var indexes = _quadIndexes(sizedPoint, quad.corners); + + // Iterating + for (var i = 0, l = indexes.length; i < l; i++) { + + // Subdividing if necessary + if (quad.nodes[indexes[i]] === undefined) + quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad); + + // Recursion + _quadInsert(el, sizedPoint, quad.nodes[indexes[i]]); + } + } + else { + + // Pushing the element in a leaf node + quad.elements.push(el); + } + } + + /** + * Recursively retrieve every elements held by the node containing the + * searched point. + * + * @param {object} point The searched point (x, y). + * @param {object} quad The searched quad. + * @return {array} An array of elements contained in the relevant + * node. + */ + function _quadRetrievePoint(point, quad) { + if (quad.level < quad.maxLevel) { + var index = _quadIndex(point, quad.bounds); + + // If node does not exist we return an empty list + if (quad.nodes[index] !== undefined) { + return _quadRetrievePoint(point, quad.nodes[index]); + } + else { + return []; + } + } + else { + return quad.elements; + } + } + + /** + * Recursively retrieve every elements contained within an rectangular area + * that may or may not be axis-aligned. + * + * @param {object|array} rectData The searched area defined either by + * an array of four corners (x, y) in + * the case of a non-axis-aligned + * rectangle or an object with two top + * points (x1, y1), (x2, y2) and height. + * @param {object} quad The searched quad. + * @param {function} collisionFunc The collision function used to search + * for node indexes. + * @param {array?} els The retrieved elements. + * @return {array} An array of elements contained in the + * area. + */ + function _quadRetrieveArea(rectData, quad, collisionFunc, els) { + els = els || {}; + + if (quad.level < quad.maxLevel) { + var indexes = collisionFunc(rectData, quad.corners); + + for (var i = 0, l = indexes.length; i < l; i++) + if (quad.nodes[indexes[i]] !== undefined) + _quadRetrieveArea( + rectData, + quad.nodes[indexes[i]], + collisionFunc, + els + ); + } else + for (var j = 0, m = quad.elements.length; j < m; j++) + if (els[quad.elements[j].id] === undefined) + els[quad.elements[j].id] = quad.elements[j]; + + return els; + } + + /** + * Creates the quadtree object itself. + * + * @param {object} bounds The boundaries of the quad defined by an + * origin (x, y), width and heigth. + * @param {integer} level The level of the quad in the tree. + * @param {integer} maxElements The max number of element in a leaf node. + * @param {integer} maxLevel The max recursion level of the tree. + * @return {object} The quadtree object. + */ + function _quadTree(bounds, level, maxElements, maxLevel) { + return { + level: level || 0, + bounds: bounds, + corners: _geom.splitSquare(bounds), + maxElements: maxElements || 20, + maxLevel: maxLevel || 4, + elements: [], + nodes: [] + }; + } + + + /** + * Sigma Quad Constructor + * ---------------------- + * + * The quad API as exposed to sigma. + */ + + /** + * The quad core that will become the sigma interface with the quadtree. + * + * property {object} _tree Property holding the quadtree object. + * property {object} _geom Exposition of the _geom namespace for testing. + * property {object} _cache Cache for the area method. + */ + var quad = function() { + this._geom = _geom; + this._tree = null; + this._cache = { + query: false, + result: false + }; + }; + + /** + * Index a graph by inserting its nodes into the quadtree. + * + * @param {array} nodes An array of nodes to index. + * @param {object} params An object of parameters with at least the quad + * bounds. + * @return {object} The quadtree object. + * + * Parameters: + * ---------- + * bounds: {object} boundaries of the quad defined by its origin (x, y) + * width and heigth. + * prefix: {string?} a prefix for node geometric attributes. + * maxElements: {integer?} the max number of elements in a leaf node. + * maxLevel: {integer?} the max recursion level of the tree. + */ + quad.prototype.index = function(nodes, params) { + + // Enforcing presence of boundaries + if (!params.bounds) + throw 'sigma.classes.quad.index: bounds information not given.'; + + // Prefix + var prefix = params.prefix || ''; + + // Building the tree + this._tree = _quadTree( + params.bounds, + 0, + params.maxElements, + params.maxLevel + ); + + // Inserting graph nodes into the tree + for (var i = 0, l = nodes.length; i < l; i++) { + + // Inserting node + _quadInsert( + nodes[i], + _geom.pointToSquare({ + x: nodes[i][prefix + 'x'], + y: nodes[i][prefix + 'y'], + size: nodes[i][prefix + 'size'] + }), + this._tree + ); + } + + // Reset cache: + this._cache = { + query: false, + result: false + }; + + // remove? + return this._tree; + }; + + /** + * Retrieve every graph nodes held by the quadtree node containing the + * searched point. + * + * @param {number} x of the point. + * @param {number} y of the point. + * @return {array} An array of nodes retrieved. + */ + quad.prototype.point = function(x, y) { + return this._tree ? + _quadRetrievePoint({x: x, y: y}, this._tree) || [] : + []; + }; + + /** + * Retrieve every graph nodes within a rectangular area. The methods keep the + * last area queried in cache for optimization reason and will act differently + * for the same reason if the area is axis-aligned or not. + * + * @param {object} A rectangle defined by two top points (x1, y1), (x2, y2) + * and height. + * @return {array} An array of nodes retrieved. + */ + quad.prototype.area = function(rect) { + var serialized = JSON.stringify(rect), + collisionFunc, + rectData; + + // Returning cache? + if (this._cache.query === serialized) + return this._cache.result; + + // Axis aligned ? + if (_geom.isAxisAligned(rect)) { + collisionFunc = _quadIndexes; + rectData = _geom.axisAlignedTopPoints(rect); + } + else { + collisionFunc = _quadCollision; + rectData = _geom.rectangleCorners(rect); + } + + // Retrieving nodes + var nodes = this._tree ? + _quadRetrieveArea( + rectData, + this._tree, + collisionFunc + ) : + []; + + // Object to array + var nodesArray = []; + for (var i in nodes) + nodesArray.push(nodes[i]); + + // Caching + this._cache.query = serialized; + this._cache.result = nodesArray; + + return nodesArray; + }; + + + /** + * EXPORT: + * ******* + */ + if (typeof this.sigma !== 'undefined') { + this.sigma.classes = this.sigma.classes || {}; + this.sigma.classes.quad = quad; + } else if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) + exports = module.exports = quad; + exports.quad = quad; + } else + this.quad = quad; +}).call(this); diff --git a/src/main/java/net/jrtechs/www/client/src/conrad.js b/src/main/java/net/jrtechs/www/client/src/conrad.js new file mode 100644 index 0000000..bdb6610 --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/conrad.js @@ -0,0 +1,984 @@ +/** + * conrad.js is a tiny JavaScript jobs scheduler, + * + * Version: 0.1.0 + * Sources: http://github.com/jacomyal/conrad.js + * Doc: http://github.com/jacomyal/conrad.js#readme + * + * License: + * -------- + * Copyright © 2013 Alexis Jacomy, Sciences-Po médialab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising + * from, out of or in connection with the software or the use or other dealings + * in the Software. + */ +(function(global) { + 'use strict'; + + // Check that conrad.js has not been loaded yet: + if (global.conrad) + throw new Error('conrad already exists'); + + + /** + * PRIVATE VARIABLES: + * ****************** + */ + + /** + * A flag indicating whether conrad is running or not. + * + * @type {Number} + */ + var _lastFrameTime; + + /** + * A flag indicating whether conrad is running or not. + * + * @type {Boolean} + */ + var _isRunning = false; + + /** + * The hash of registered jobs. Each job must at least have a unique ID + * under the key "id" and a function under the key "job". This hash + * contains each running job and each waiting job. + * + * @type {Object} + */ + var _jobs = {}; + + /** + * The hash of currently running jobs. + * + * @type {Object} + */ + var _runningJobs = {}; + + /** + * The array of currently running jobs, sorted by priority. + * + * @type {Array} + */ + var _sortedByPriorityJobs = []; + + /** + * The array of currently waiting jobs. + * + * @type {Object} + */ + var _waitingJobs = {}; + + /** + * The array of finished jobs. They are stored in an array, since two jobs + * with the same "id" can happen at two different times. + * + * @type {Array} + */ + var _doneJobs = []; + + /** + * A dirty flag to keep conrad from starting: Indeed, when addJob() is called + * with several jobs, conrad must be started only at the end. This flag keeps + * me from duplicating the code that effectively adds a job. + * + * @type {Boolean} + */ + var _noStart = false; + + /** + * An hash containing some global settings about how conrad.js should + * behave. + * + * @type {Object} + */ + var _parameters = { + frameDuration: 20, + history: true + }; + + /** + * This object contains every handlers bound to conrad events. It does not + * requirea any DOM implementation, since the events are all JavaScript. + * + * @type {Object} + */ + var _handlers = Object.create(null); + + + /** + * PRIVATE FUNCTIONS: + * ****************** + */ + + /** + * Will execute the handler everytime that the indicated event (or the + * indicated events) will be triggered. + * + * @param {string|array|object} events The name of the event (or the events + * separated by spaces). + * @param {function(Object)} handler The handler to bind. + * @return {Object} Returns conrad. + */ + function _bind(events, handler) { + var i, + i_end, + event, + eArray; + + if (!arguments.length) + return; + else if ( + arguments.length === 1 && + Object(arguments[0]) === arguments[0] + ) + for (events in arguments[0]) + _bind(events, arguments[0][events]); + else if (arguments.length > 1) { + eArray = + Array.isArray(events) ? + events : + events.split(/ /); + + for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { + event = eArray[i]; + + if (!_handlers[event]) + _handlers[event] = []; + + // Using an object instead of directly the handler will make possible + // later to add flags + _handlers[event].push({ + handler: handler + }); + } + } + } + + /** + * Removes the handler from a specified event (or specified events). + * + * @param {?string} events The name of the event (or the events + * separated by spaces). If undefined, + * then all handlers are removed. + * @param {?function(Object)} handler The handler to unbind. If undefined, + * each handler bound to the event or the + * events will be removed. + * @return {Object} Returns conrad. + */ + function _unbind(events, handler) { + var i, + i_end, + j, + j_end, + a, + event, + eArray = Array.isArray(events) ? + events : + events.split(/ /); + + if (!arguments.length) + _handlers = Object.create(null); + else if (handler) { + for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { + event = eArray[i]; + if (_handlers[event]) { + a = []; + for (j = 0, j_end = _handlers[event].length; j !== j_end; j += 1) + if (_handlers[event][j].handler !== handler) + a.push(_handlers[event][j]); + + _handlers[event] = a; + } + + if (_handlers[event] && _handlers[event].length === 0) + delete _handlers[event]; + } + } else + for (i = 0, i_end = eArray.length; i !== i_end; i += 1) + delete _handlers[eArray[i]]; + } + + /** + * Executes each handler bound to the event. + * + * @param {string} events The name of the event (or the events separated + * by spaces). + * @param {?Object} data The content of the event (optional). + * @return {Object} Returns conrad. + */ + function _dispatch(events, data) { + var i, + j, + i_end, + j_end, + event, + eventName, + eArray = Array.isArray(events) ? + events : + events.split(/ /); + + data = data === undefined ? {} : data; + + for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { + eventName = eArray[i]; + + if (_handlers[eventName]) { + event = { + type: eventName, + data: data || {} + }; + + for (j = 0, j_end = _handlers[eventName].length; j !== j_end; j += 1) + try { + _handlers[eventName][j].handler(event); + } catch (e) {} + } + } + } + + /** + * Executes the most prioritary job once, and deals with filling the stats + * (done, time, averageTime, currentTime, etc...). + * + * @return {?Object} Returns the job object if it has to be killed, null else. + */ + function _executeFirstJob() { + var i, + l, + test, + kill, + pushed = false, + time = __dateNow(), + job = _sortedByPriorityJobs.shift(); + + // Execute the job and look at the result: + test = job.job(); + + // Deal with stats: + time = __dateNow() - time; + job.done++; + job.time += time; + job.currentTime += time; + job.weightTime = job.currentTime / (job.weight || 1); + job.averageTime = job.time / job.done; + + // Check if the job has to be killed: + kill = job.count ? (job.count <= job.done) : !test; + + // Reset priorities: + if (!kill) { + for (i = 0, l = _sortedByPriorityJobs.length; i < l; i++) + if (_sortedByPriorityJobs[i].weightTime > job.weightTime) { + _sortedByPriorityJobs.splice(i, 0, job); + pushed = true; + break; + } + + if (!pushed) + _sortedByPriorityJobs.push(job); + } + + return kill ? job : null; + } + + /** + * Activates a job, by adding it to the _runningJobs object and the + * _sortedByPriorityJobs array. It also initializes its currentTime value. + * + * @param {Object} job The job to activate. + */ + function _activateJob(job) { + var l = _sortedByPriorityJobs.length; + + // Add the job to the running jobs: + _runningJobs[job.id] = job; + job.status = 'running'; + + // Add the job to the priorities: + if (l) { + job.weightTime = _sortedByPriorityJobs[l - 1].weightTime; + job.currentTime = job.weightTime * (job.weight || 1); + } + + // Initialize the job and dispatch: + job.startTime = __dateNow(); + _dispatch('jobStarted', __clone(job)); + + _sortedByPriorityJobs.push(job); + } + + /** + * The main loop of conrad.js: + * . It executes job such that they all occupate the same processing time. + * . It stops jobs that do not need to be executed anymore. + * . It triggers callbacks when it is relevant. + * . It starts waiting jobs when they need to be started. + * . It injects frames to keep a constant frapes per second ratio. + * . It stops itself when there are no more jobs to execute. + */ + function _loop() { + var k, + o, + l, + job, + time, + deadJob; + + // Deal with the newly added jobs (the _jobs object): + for (k in _jobs) { + job = _jobs[k]; + + if (job.after) + _waitingJobs[k] = job; + else + _activateJob(job); + + delete _jobs[k]; + } + + // Set the _isRunning flag to false if there are no running job: + _isRunning = !!_sortedByPriorityJobs.length; + + // Deal with the running jobs (the _runningJobs object): + while ( + _sortedByPriorityJobs.length && + __dateNow() - _lastFrameTime < _parameters.frameDuration + ) { + deadJob = _executeFirstJob(); + + // Deal with the case where the job has ended: + if (deadJob) { + _killJob(deadJob.id); + + // Check for waiting jobs: + for (k in _waitingJobs) + if (_waitingJobs[k].after === deadJob.id) { + _activateJob(_waitingJobs[k]); + delete _waitingJobs[k]; + } + } + } + + // Check if conrad still has jobs to deal with, and kill it if not: + if (_isRunning) { + // Update the _lastFrameTime: + _lastFrameTime = __dateNow(); + + _dispatch('enterFrame'); + setTimeout(_loop, 0); + } else + _dispatch('stop'); + } + + /** + * Adds one or more jobs, and starts the loop if no job was running before. A + * job is at least a unique string "id" and a function, and there are some + * parameters that you can specify for each job to modify the way conrad will + * execute it. If a job is added with the "id" of another job that is waiting + * or still running, an error will be thrown. + * + * When a job is added, it is referenced in the _jobs object, by its id. + * Then, if it has to be executed right now, it will be also referenced in + * the _runningJobs object. If it has to wait, then it will be added into the + * _waitingJobs object, until it can start. + * + * Keep reading this documentation to see how to call this method. + * + * @return {Object} Returns conrad. + * + * Adding one job: + * *************** + * Basically, a job is defined by its string id and a function (the job). It + * is also possible to add some parameters: + * + * > conrad.addJob('myJobId', myJobFunction); + * > conrad.addJob('myJobId', { + * > job: myJobFunction, + * > someParameter: someValue + * > }); + * > conrad.addJob({ + * > id: 'myJobId', + * > job: myJobFunction, + * > someParameter: someValue + * > }); + * + * Adding several jobs: + * ******************** + * When adding several jobs at the same time, it is possible to specify + * parameters for each one individually or for all: + * + * > conrad.addJob([ + * > { + * > id: 'myJobId1', + * > job: myJobFunction1, + * > someParameter1: someValue1 + * > }, + * > { + * > id: 'myJobId2', + * > job: myJobFunction2, + * > someParameter2: someValue2 + * > } + * > ], { + * > someCommonParameter: someCommonValue + * > }); + * > conrad.addJob({ + * > myJobId1: {, + * > job: myJobFunction1, + * > someParameter1: someValue1 + * > }, + * > myJobId2: {, + * > job: myJobFunction2, + * > someParameter2: someValue2 + * > } + * > }, { + * > someCommonParameter: someCommonValue + * > }); + * > conrad.addJob({ + * > myJobId1: myJobFunction1, + * > myJobId2: myJobFunction2 + * > }, { + * > someCommonParameter: someCommonValue + * > }); + * + * Recognized parameters: + * ********************** + * Here is the exhaustive list of every accepted parameters: + * + * {?Function} end A callback to execute when the job is ended. It is + * not executed if the job is killed instead of ended + * "naturally". + * {?Integer} count The number of time the job has to be executed. + * {?Number} weight If specified, the job will be executed as it was + * added "weight" times. + * {?String} after The id of another job (eventually not added yet). + * If specified, this job will start only when the + * specified "after" job is ended. + */ + function _addJob(v1, v2) { + var i, + l, + o; + + // Array of jobs: + if (Array.isArray(v1)) { + // Keep conrad to start until the last job is added: + _noStart = true; + + for (i = 0, l = v1.length; i < l; i++) + _addJob(v1[i].id, __extend(v1[i], v2)); + + _noStart = false; + if (!_isRunning) { + // Update the _lastFrameTime: + _lastFrameTime = __dateNow(); + + _dispatch('start'); + _loop(); + } + } else if (typeof v1 === 'object') { + // One job (object): + if (typeof v1.id === 'string') + _addJob(v1.id, v1); + + // Hash of jobs: + else { + // Keep conrad to start until the last job is added: + _noStart = true; + + for (i in v1) + if (typeof v1[i] === 'function') + _addJob(i, __extend({ + job: v1[i] + }, v2)); + else + _addJob(i, __extend(v1[i], v2)); + + _noStart = false; + if (!_isRunning) { + // Update the _lastFrameTime: + _lastFrameTime = __dateNow(); + + _dispatch('start'); + _loop(); + } + } + + // One job (string, *): + } else if (typeof v1 === 'string') { + if (_hasJob(v1)) + throw new Error( + '[conrad.addJob] Job with id "' + v1 + '" already exists.' + ); + + // One job (string, function): + if (typeof v2 === 'function') { + o = { + id: v1, + done: 0, + time: 0, + status: 'waiting', + currentTime: 0, + averageTime: 0, + weightTime: 0, + job: v2 + }; + + // One job (string, object): + } else if (typeof v2 === 'object') { + o = __extend( + { + id: v1, + done: 0, + time: 0, + status: 'waiting', + currentTime: 0, + averageTime: 0, + weightTime: 0 + }, + v2 + ); + + // If none of those cases, throw an error: + } else + throw new Error('[conrad.addJob] Wrong arguments.'); + + // Effectively add the job: + _jobs[v1] = o; + _dispatch('jobAdded', __clone(o)); + + // Check if the loop has to be started: + if (!_isRunning && !_noStart) { + // Update the _lastFrameTime: + _lastFrameTime = __dateNow(); + + _dispatch('start'); + _loop(); + } + + // If none of those cases, throw an error: + } else + throw new Error('[conrad.addJob] Wrong arguments.'); + + return this; + } + + /** + * Kills one or more jobs, indicated by their ids. It is only possible to + * kill running jobs or waiting jobs. If you try to kill a job that does not + * exist or that is already killed, a warning will be thrown. + * + * @param {Array|String} v1 A string job id or an array of job ids. + * @return {Object} Returns conrad. + */ + function _killJob(v1) { + var i, + l, + k, + a, + job, + found = false; + + // Array of job ids: + if (Array.isArray(v1)) + for (i = 0, l = v1.length; i < l; i++) + _killJob(v1[i]); + + // One job's id: + else if (typeof v1 === 'string') { + a = [_runningJobs, _waitingJobs, _jobs]; + + // Remove the job from the hashes: + for (i = 0, l = a.length; i < l; i++) + if (v1 in a[i]) { + job = a[i][v1]; + + if (_parameters.history) { + job.status = 'done'; + _doneJobs.push(job); + } + + _dispatch('jobEnded', __clone(job)); + delete a[i][v1]; + + if (typeof job.end === 'function') + job.end(); + + found = true; + } + + // Remove the priorities array: + a = _sortedByPriorityJobs; + for (i = 0, l = a.length; i < l; i++) + if (a[i].id === v1) { + a.splice(i, 1); + break; + } + + if (!found) + throw new Error('[conrad.killJob] Job "' + v1 + '" not found.'); + + // If none of those cases, throw an error: + } else + throw new Error('[conrad.killJob] Wrong arguments.'); + + return this; + } + + /** + * Kills every running, waiting, and just added jobs. + * + * @return {Object} Returns conrad. + */ + function _killAll() { + var k, + jobs = __extend(_jobs, _runningJobs, _waitingJobs); + + // Take every jobs and push them into the _doneJobs object: + if (_parameters.history) + for (k in jobs) { + jobs[k].status = 'done'; + _doneJobs.push(jobs[k]); + + if (typeof jobs[k].end === 'function') + jobs[k].end(); + } + + // Reinitialize the different jobs lists: + _jobs = {}; + _waitingJobs = {}; + _runningJobs = {}; + _sortedByPriorityJobs = []; + + // In case some jobs are added right after the kill: + _isRunning = false; + + return this; + } + + /** + * Returns true if a job with the specified id is currently running or + * waiting, and false else. + * + * @param {String} id The id of the job. + * @return {?Object} Returns the job object if it exists. + */ + function _hasJob(id) { + var job = _jobs[id] || _runningJobs[id] || _waitingJobs[id]; + return job ? __extend(job) : null; + } + + /** + * This method will set the setting specified by "v1" to the value specified + * by "v2" if both are given, and else return the current value of the + * settings "v1". + * + * @param {String} v1 The name of the property. + * @param {?*} v2 Eventually, a value to set to the specified + * property. + * @return {Object|*} Returns the specified settings value if "v2" is not + * given, and conrad else. + */ + function _settings(v1, v2) { + var o; + + if (typeof a1 === 'string' && arguments.length === 1) + return _parameters[a1]; + else { + o = (typeof a1 === 'object' && arguments.length === 1) ? + a1 || {} : + {}; + if (typeof a1 === 'string') + o[a1] = a2; + + for (var k in o) + if (o[k] !== undefined) + _parameters[k] = o[k]; + else + delete _parameters[k]; + + return this; + } + } + + /** + * Returns true if conrad is currently running, and false else. + * + * @return {Boolean} Returns _isRunning. + */ + function _getIsRunning() { + return _isRunning; + } + + /** + * Unreference every job that is stored in the _doneJobs object. It will + * not be possible anymore to get stats about these jobs, but it will release + * the memory. + * + * @return {Object} Returns conrad. + */ + function _clearHistory() { + _doneJobs = []; + return this; + } + + /** + * Returns a snapshot of every data about jobs that wait to be started, are + * currently running or are done. + * + * It is possible to get only running, waiting or done jobs by giving + * "running", "waiting" or "done" as fist argument. + * + * It is also possible to get every job with a specified id by giving it as + * first argument. Also, using a RegExp instead of an id will return every + * jobs whose ids match the RegExp. And these two last use cases work as well + * by giving before "running", "waiting" or "done". + * + * @return {Array} The array of the matching jobs. + * + * Some call examples: + * ******************* + * > conrad.getStats('running') + * > conrad.getStats('waiting') + * > conrad.getStats('done') + * > conrad.getStats('myJob') + * > conrad.getStats(/test/) + * > conrad.getStats('running', 'myRunningJob') + * > conrad.getStats('running', /test/) + */ + function _getStats(v1, v2) { + var a, + k, + i, + l, + stats, + pattern, + isPatternString; + + if (!arguments.length) { + stats = []; + + for (k in _jobs) + stats.push(_jobs[k]); + + for (k in _waitingJobs) + stats.push(_waitingJobs[k]); + + for (k in _runningJobs) + stats.push(_runningJobs[k]); + + stats = stats.concat(_doneJobs); + } + + if (typeof v1 === 'string') + switch (v1) { + case 'waiting': + stats = __objectValues(_waitingJobs); + break; + case 'running': + stats = __objectValues(_runningJobs); + break; + case 'done': + stats = _doneJobs; + break; + default: + pattern = v1; + } + + if (v1 instanceof RegExp) + pattern = v1; + + if (!pattern && (typeof v2 === 'string' || v2 instanceof RegExp)) + pattern = v2; + + // Filter jobs if a pattern is given: + if (pattern) { + isPatternString = typeof pattern === 'string'; + + if (stats instanceof Array) { + a = stats; + } else if (typeof stats === 'object') { + a = []; + + for (k in stats) + a = a.concat(stats[k]); + } else { + a = []; + + for (k in _jobs) + a.push(_jobs[k]); + + for (k in _waitingJobs) + a.push(_waitingJobs[k]); + + for (k in _runningJobs) + a.push(_runningJobs[k]); + + a = a.concat(_doneJobs); + } + + stats = []; + for (i = 0, l = a.length; i < l; i++) + if (isPatternString ? a[i].id === pattern : a[i].id.match(pattern)) + stats.push(a[i]); + } + + return __clone(stats); + } + + + /** + * TOOLS FUNCTIONS: + * **************** + */ + + /** + * This function takes any number of objects as arguments, copies from each + * of these objects each pair key/value into a new object, and finally + * returns this object. + * + * The arguments are parsed from the last one to the first one, such that + * when two objects have keys in common, the "earliest" object wins. + * + * Example: + * ******** + * > var o1 = { + * > a: 1, + * > b: 2, + * > c: '3' + * > }, + * > o2 = { + * > c: '4', + * > d: [ 5 ] + * > }; + * > __extend(o1, o2); + * > // Returns: { + * > // a: 1, + * > // b: 2, + * > // c: '3', + * > // d: [ 5 ] + * > // }; + * + * @param {Object+} Any number of objects. + * @return {Object} The merged object. + */ + function __extend() { + var i, + k, + res = {}, + l = arguments.length; + + for (i = l - 1; i >= 0; i--) + for (k in arguments[i]) + res[k] = arguments[i][k]; + + return res; + } + + /** + * This function simply clones an object. This object must contain only + * objects, arrays and immutable values. Since it is not public, it does not + * deal with cyclic references, DOM elements and instantiated objects - so + * use it carefully. + * + * @param {Object} The object to clone. + * @return {Object} The clone. + */ + function __clone(item) { + var result, i, k, l; + + if (!item) + return item; + + if (Array.isArray(item)) { + result = []; + for (i = 0, l = item.length; i < l; i++) + result.push(__clone(item[i])); + } else if (typeof item === 'object') { + result = {}; + for (i in item) + result[i] = __clone(item[i]); + } else + result = item; + + return result; + } + + /** + * Returns an array containing the values of an object. + * + * @param {Object} The object. + * @return {Array} The array of values. + */ + function __objectValues(o) { + var k, + a = []; + + for (k in o) + a.push(o[k]); + + return a; + } + + /** + * A short "Date.now()" polyfill. + * + * @return {Number} The current time (in ms). + */ + function __dateNow() { + return Date.now ? Date.now() : new Date().getTime(); + } + + /** + * Polyfill for the Array.isArray function: + */ + if (!Array.isArray) + Array.isArray = function(v) { + return Object.prototype.toString.call(v) === '[object Array]'; + }; + + + /** + * EXPORT PUBLIC API: + * ****************** + */ + var conrad = { + hasJob: _hasJob, + addJob: _addJob, + killJob: _killJob, + killAll: _killAll, + settings: _settings, + getStats: _getStats, + isRunning: _getIsRunning, + clearHistory: _clearHistory, + + // Events management: + bind: _bind, + unbind: _unbind, + + // Version: + version: '0.1.0' + }; + + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) + exports = module.exports = conrad; + exports.conrad = conrad; + } + global.conrad = conrad; +})(this); diff --git a/src/main/java/net/jrtechs/www/client/src/jquery-2.1.1.min.js b/src/main/java/net/jrtechs/www/client/src/jquery-2.1.1.min.js new file mode 100644 index 0000000..e5ace11 --- /dev/null +++ b/src/main/java/net/jrtechs/www/client/src/jquery-2.1.1.min.js @@ -0,0 +1,4 @@ +/*! jQuery v2.1.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.1",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+Math.random()}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b) +},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(ob(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(ob(c,"script"),kb),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(hb,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("