This is my first project both in Autodesk Forge and Javascript, so I'm quite lost.
This is my code:
async function loadHeatmaps(model){
const dataVizExtn = await viewer.loadExtension("Autodesk.DataVisualization");
// Given a model loaded from Forge
const structureInfo = new Autodesk.DataVisualization.Core.ModelStructureInfo(model);
const devices = [
{
id: "Oficina 6",
name:"Oficina-",
position: { x: 22.475382737884104, y: 7.4884431474006163, z: 3.0 },
sensorTypes: ["temperature", "humidity"]
}
];
var offset = Autodesk.viewer.model.getGlobalOffset();
removeOffset(devices[0],offset)
// Generates `SurfaceShadingData` after assigning each device to a room.
const shadingData = await Autodesk.structureInfo.generateSurfaceShadingData(devices);
// Use the resulting shading data to generate heatmap from.
await dataVizExtn.setupSurfaceShading(model, shadingData);
// Register color stops for the heatmap. Along with the normalized sensor value
// in the range of [0.0, 1.0], `renderSurfaceShading` will interpolate the final
// heatmap color based on these specified colors.
const sensorColors = [0x0000ff, 0x00ff00, 0xffff00, 0xff0000];
// Set heatmap colors for temperature
const sensorType = "temperature";
dataVizExtn.registerSurfaceShadingColors(sensorType, sensorColors);
// Function that provides sensor value in the range of [0.0, 1.0]
function getSensorValue(surfaceShadingPoint, sensorType) {
// The `SurfaceShadingPoint.id` property matches one of the identifiers passed
// to `generateSurfaceShadingData` function. In our case above, this will either
// be "cafeteria-entrace-01" or "cafeteria-exit-01".
const deviceId = surfaceShadingPoint.id;
// Read the sensor data, along with its possible value range
let sensorValue = readSensorValue(deviceId, sensorType);
const maxSensorValue = getMaxSensorValue(sensorType);
const minSensorValue = getMinSensorValue(sensorType);
// Normalize sensor value to [0, 1.0]
sensorValue = (sensorValue - minSensorValue) / (maxSensorValue - minSensorValue);
return clamp(sensorValue, 0.0, 1.0);
}
// This value can also be a room instead of a floor
const floorName = "01 - Entry Level";
dataVizExtn.renderSurfaceShading(floorName, sensorType, getSensorValue);
}
var viewer;
function view_document(token_id, urns, derivative) {
var options = {
env: 'AutodeskProduction',
api: derivative,
getAccessToken: function(onTokenReady) {
var token = token_id; //token from authentification
var timeInSeconds = 3600;
onTokenReady(token, timeInSeconds);
}//input for viewer initializer function
};
Autodesk.Viewing.Initializer(options, function() {
//fetch the forgeViewer id in the html
var htmlDiv = document.getElementById('forgeViewer');
//create the view at the html div
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv);
//start viewer
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
for (let i = 0; i < urns.length; i ++) {
Autodesk.Viewing.Document.load(urns[i]["urn"], (doc) => {
var viewables = doc.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(doc, viewables,{
preserveView: false,
keepCurrentModels: true,
placementTransform: (new THREE.Matrix4()).setPosition(urns[i]["xform"]), keepCurrentModels: true,
globalOffset: {x:0,y:0,z:0}
})
});
}
loadHeatmaps(this.viewer.model);
});
}
It should work. I've copied it from a tutorial website, and have seen similar pieces of code everywhere. But when I load it this error appears on the log console:
Error on the console
DG_V2:162 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'model')
at loadHeatmaps (DG_V2:162:35)
Could you please help me? I have the feeling that nothing works. Using model, this.model, autodesk.model, autodesk.viewer.model, or any other kind of combination is not working and this is driving me crazy...
Loading modes are async tasks, so you can't get the model before loading completely. Here is the revision of your code snippet.
function view_document(token_id, urns, derivative) {
let options = {
env: 'AutodeskProduction',
api: derivative,
getAccessToken: function(onTokenReady) {
let token = token_id; //token from authentification
let timeInSeconds = 3600;
onTokenReady(token, timeInSeconds);
} //input for viewer initializer function
};
Autodesk.Viewing.Initializer(options, function() {
//fetch the forgeViewer id in the html
let htmlDiv = document.getElementById('forgeViewer');
//create the view at the html div
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv);
//start viewer
let startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
for (let i = 0; i < urns.length; i++) {
Autodesk.Viewing.Document.load(urns[i]["urn"], (doc) => {
let viewables = doc.getRoot().getDefaultGeometry();
let model = await viewer.loadDocumentNode(doc, viewables, {
preserveView: false,
keepCurrentModels: true,
placementTransform: (new THREE.Matrix4()).setPosition(urns[i]["xform"]),
keepCurrentModels: true,
globalOffset: {
x: 0,
y: 0,
z: 0
}
});
await viewer.waitForLoadDone(); //!<<< Wait for loading materials, properties and geometries for this model (URN)
});
}
loadHeatmaps( viewer.getAllModels()[0] ); //!<<< equals to viewer.model
});
}
I am trying to parse an GoJS diagram, user can drag different categories from a plate, circle node, rectangle node, triangle. and he can interconnect them in in one direction until reaching the end.
the required function is to parse the graph and give a list of possible paths according the user dependency graph. sample graph is shown here
my function is something like this code:
function collectPaths(y, x) {
var stack = new go.List(go.node);
var coll = new go.List(go.List);
lock = false;
function find(y, x) {
console.log(y.data.name);
y.findNodesInto().each(function (n) {
console.log(y.data.name + " ●▬● " + n.data.name);
if ((n.data.key == x.data.key) && !(lock)) { // success
console.log(n.data.name);
var path = stack.copy();
path.reverse();
coll.add(path);
} else if((n.data.key !=x.data.key) && lock){
// stack.add(n);
console.log(n.data.name);
if (n.data.category === "triangle") {
pp = pp.findNodesInto();
var it = pp.iterator;
var m = new go.Map(go.node, "number");
lock = true;
while (it.next()) {
m.pop(it.value,it.value);
stack.add(it.value);
console.log(it.value.data.name);
find(it.value, x);
}
var tempList=go.list(go.node);
tempList.each(function (pn) {
pn = tempList.pop();
if (!"undefined") {
stack.add(parent);
find(parent, x);
// stack.add(pn);
console.log(pn.data.name);
} else {
pn = tempList.pop();
find(pn, x);
}
});
} else {
console.log(n.data.name);
stack.add(n);
find(n, x);
stack.removeAt(stack.count - 1);
}
}
lock = false;
});
} // end of full stack collection
find(y, x);
return coll;
}
but the function doesn't give the required output.
expected output like this: for the figure attached as follows:
N30 – N40 – N10
N1 -N2-N3-N4-N10
N5-N6-N9-N10
N5-N10
N7-N8-N10
N7-N8-N11-N10
What I can do ?
The sample https://gojs.net/latest/samples/distances.html demonstrates how to find all paths between any pair of nodes. You want to use the collectAllPaths function -- you can delete the functions involved with creating a random graph or with finding distances between nodes or with helping the user select the start and end nodes interactively.
It was really hard to form this question because it is a difficult question. I have a game_server file in this file we have.
var
game_server = module.exports = { games : {}, game_count:0 },
UUID = require('node-uuid'),
verbose = true;
//Since we are sharing code with the browser, we
//are going to include some values to handle that.
global.window = global.document = global;
//Import shared game library code.
require('./game.core.js');
//A simple wrapper for logging so we can toggle it,
//and augment it for clarity.
game_server.log = function() {
if(verbose) console.log.apply(this,arguments);
};
game_server.fake_latency = 0;
game_server.local_time = 0;
game_server._dt = new Date().getTime();
game_server._dte = new Date().getTime();
//a local queue of messages we delay if faking latency
game_server.messages = [];
setInterval(function(){
game_server._dt = new Date().getTime() - game_server._dte;
game_server._dte = new Date().getTime();
game_server.local_time += game_server._dt/1000.0;
}, 4);
game_server.onMessage = function(client,message) {
if(this.fake_latency && message.split('.')[0].substr(0,1) == 'i') {
//store all input message
game_server.messages.push({client:client, message:message});
setTimeout(function(){
if(game_server.messages.length) {
game_server._onMessage( game_server.messages[0].client, game_server.messages[0].message );
game_server.messages.splice(0,1);
}
}.bind(this), this.fake_latency);
} else {
game_server._onMessage(client, message);
}
};
game_server._onMessage = function(client,message) {
//Cut the message up into sub components
var message_parts = message.split('.');
//The first is always the type of message
var message_type = message_parts[0];
var other_client =
(client.game.player_host.userid == client.userid) ?
client.game.player_client : client.game.player_host;
if(message_type == 'i') {
//Input handler will forward this
this.onInput(client, message_parts);
} else if(message_type == 'p') {
client.send('s.p.' + message_parts[1]);
} else if(message_type == 'c') { //Client changed their color!
if(other_client)
other_client.send('s.c.' + message_parts[1]);
} else if(message_type == 'l') { //A client is asking for lag simulation
this.fake_latency = parseFloat(message_parts[1]);
}
}; //game_server.onMessage
game_server.onInput = function(client, parts) {
//The input commands come in like u-l,
//so we split them up into separate commands,
//and then update the players
var input_commands = parts[1].split('-');
var input_time = parts[2].replace('-','.');
var input_seq = parts[3];
//the client should be in a game, so
//we can tell that game to handle the input
if(client && client.game && client.game.gamecore) {
client.game.gamecore.handle_server_input(client, input_commands, input_time, input_seq);
}
}; //game_server.onInput
//Define some required functions
game_server.createGame = function(player) {
//Create a new game instance
var thegame = {
id : UUID(), //generate a new id for the game
player_host:player, //so we know who initiated the game
player_client:null, //nobody else joined yet, since its new
player_count:1 //for simple checking of state
};
//Store it in the list of game
this.games[ thegame.id ] = thegame;
//Keep track
this.game_count++;
//Create a new game core instance, this actually runs the
//game code like collisions and such.
thegame.gamecore = new game_core( thegame );
//Start updating the game loop on the server
thegame.gamecore.update( new Date().getTime() );
//tell the player that they are now the host
//s=server message, h=you are hosting
player.send('s.h.'+ String(thegame.gamecore.local_time).replace('.','-'));
console.log('server host at ' + thegame.gamecore.local_time);
player.game = thegame;
player.hosting = true;
this.log('player ' + player.userid + ' created a game with id ' + player.game.id);
//return it
return thegame;
At the bottom you can see that we have a player.userid this is the id of the player which is logged in.
now we have a game_core.js and i want to pass the value to the game_core.js so i can use the userid in that file
var frame_time = 60/1000; // run the local game at 16ms/ 60hz
if('undefined' != typeof(global)) frame_time = 45; //on server we run at 45ms, 22hz
( function () {
var lastTime = 0;
var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
}
if ( !window.requestAnimationFrame ) {
window.requestAnimationFrame = function ( callback, element ) {
var currTime = Date.now(), timeToCall = Math.max( 0, frame_time - ( currTime - lastTime ) );
var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
lastTime = currTime + timeToCall;
return id;
};
}
if ( !window.cancelAnimationFrame ) {
window.cancelAnimationFrame = function ( id ) { clearTimeout( id ); };
}
}() );
/* The game_core class */
var game_core = function(game_instance){
//Store the instance, if any
this.instance = game_instance;
//Store a flag if we are the server
this.server = this.instance !== undefined;
//Used in collision etc.
this.world = {
width : 720,
height : 480
};
//We create a player set, passing them
//the game that is running them, as well
if(this.server) {
this.players = {
self : new game_player(this,this.instance.player_host),
other : new game_player(this,this.instance.player_client)
};
this.players.self.pos = {x:20,y:20};
this.players.self.username = this.instance.player_host.username;
console.log(this.players.self.username);
} else {
this.players = {
self : new game_player(this),
other : new game_player(this)
};
//Debugging ghosts, to help visualise things
this.ghosts = {
//Our ghost position on the server
server_pos_self : new game_player(this),
//The other players server position as we receive it
server_pos_other : new game_player(this),
//The other players ghost destination position (the lerp)
pos_other : new game_player(this)
};
this.ghosts.pos_other.state = 'dest_pos';
this.ghosts.pos_other.info_color = 'rgba(255,255,255,0.1)';
this.ghosts.server_pos_self.info_color = 'rgba(255,255,255,0.2)';
this.ghosts.server_pos_other.info_color = 'rgba(255,255,255,0.2)';
this.ghosts.server_pos_self.state = 'server_pos';
this.ghosts.server_pos_other.state = 'server_pos';
this.ghosts.server_pos_self.pos = { x:20, y:20 };
this.ghosts.pos_other.pos = { x:500, y:200 };
this.ghosts.server_pos_other.pos = { x:500, y:200 };
}
//The speed at which the clients move.
this.playerspeed = 120;
//Set up some physics integration values
this._pdt = 0.0001; //The physics update delta time
this._pdte = new Date().getTime(); //The physics update last delta time
//A local timer for precision on server and client
this.local_time = 0.016; //The local timer
this._dt = new Date().getTime(); //The local timer delta
this._dte = new Date().getTime(); //The local timer last frame time
I have been porting a script I have from V2 to V3 and I have hit a snag. I am getting an Elabel undefined error but I am not sure why I am getting this. I have updated the Elabel.js to V3 which is here...ELABLE.JS I am not sure if this is not a good copy of ELabel.js or what. I have tried a couple of different other copies with no success.
Here is the working example of it using V2
V2 EXAMPLE
Here is the V3 example. As you can see in V3 the range rings are not drawn and the map doesn't update and the table doesn't populate. I know it is related to the ELabel.js but I am not sure why and I can't find the issue to why I am getting the undefined error. I know it is related to this because when I remove the script include for the ELable.js I have the same problems on V2 that I am seeing on V3.
V3 EXAMPLE
Since the code is too long to post here, the link to the relevant code is in the link below. Line 135 is where the ELabel error is coming from. This worked great in V2 but not V3. So I don't know if I am overlooking something that has changed in V2 to V3.
EXAMPLE CODE
So can anyone offer any insight on why I am getting this undefined error and shed some light on what I may be doing wrong and overlooking?
-Thanks
Texan, here's te script from my local file, which is working as far as getting the circles and labels to show. All ajax aspects are untested.
The script below should be pasted into the document head, immediately before the closing </head> tag.
This replaces various other inline scripts. The only remaining scripts in the document body should be the google analytics (2 scripts) and StatCounter (1 script). No external scripts should be removed.
<script>
var map;
jQuery(function($) {
var llCenter = new google.maps.LatLng(32.8297,-96.6486);
var URLToKML = 'http://www.mesquiteweather.net/NSGMap/GMStrikes.kml';
var Sec2Update = 30;
var KMLdate = 1372820133;
//var NSdate = 1372927434;
var NSdate = 0; //Force KML file creation on first update
var TZString = 'CDT';
var TZOffset = -5;
var nyLayer;
var lcolor = 'white';//This defines the line color for the target circle
//Check if user wants debug mode
dbg = (gup('dbg')=='y') ? 'y' : 'n';
var force = (gup('force')=='y') ? 'y' : 'n'; //Force updates regardless of NSStrikes.txt date
var mapReady = false;
function initialize() {
var mapOptions = {
center: llCenter,
panControl: false,
zoom: 6,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var radarOptions = {
gmap: map,
name: 'Radar',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function(){
if (map.overlayMapTypes.length==0) {
map.overlayMapTypes.push(null); // create empty overlay entry
map.overlayMapTypes.setAt("1", tileNEX);
}
else {
map.overlayMapTypes.clear();
}
}
}
var radarButton = new buttonControl(radarOptions);
tileNEX = new google.maps.ImageMapType({
getTileUrl: function(tile, zoom) {
return "http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-900913/" + zoom + "/" + tile.x + "/" + tile.y +".png?"+ (new Date()).getTime();
},
tileSize: new google.maps.Size(256, 256),
opacity: 0.70,
name: 'NEXRAD',
isPng: true
});
function MyLogoControl() {
var logo = $('<img/>').attr('src', 'images/watermark_MW_GMap.png').css('cursor', 'pointer').get(0);
google.maps.event.addDomListener(logo, 'click', function() {
window.location = 'http://www.mesquiteweather.net';
});
return logo;
}
var logoControlDiv = $('<div/>').css('padding','5px').append(MyLogoControl()).get(0);
logoControlDiv.index = 0; // used for ordering
map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv);
var nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
google.maps.event.addListenerOnce(map, 'idle', function() {
//You can add circles, or change other parameters
//radials should be set to true for the maximum distance if you want radials
//doDrawCircle(circleUnits, center, circleRadius, lineColor, lineWidth, lineOpacity, fillColor, fillOpacity, opts, radials)
doDrawCircle('MI', llCenter, 62, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 124, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 187, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 249, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 312, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, "#FFFF00", 0, { clickable: false }, false);
//doDrawCircle('MI', llCenter, 374, lcolor, 1, .7, '#00FF00', 0, { clickable: false }, true); // This would add the radials
UpdateKML();//Get the first set of data
});
}
//Function to draw circles
function doDrawCircle(circleUnits, center, circleRadius, liColor, liWidth, liOpa, fillColor, fillOpa, opts, radials) {
var polyLineOptions = {
map: map,
path: null,//added with jQuery.extend()
strokeColor: liColor,
strokeOpacity: liOpa,
strokeWeight: liWidth
};
var bounds = new google.maps.LatLngBounds();
var circlePoints = [];
var d = circleRadius / ((circleUnits == 'KM') ? 6378.8 : 3963.189);
var d2r = Math.PI/180;
var lat1 = d2r * center.lat();//radians
var lng1 = d2r * center.lng();//radians
for (var a=0; a<361; a++ ) {
var tc = d2r * a;
var sin_lat1 = Math.sin(lat1),
cos_lat1 = Math.cos(lat1),
sin_d = Math.sin(d),
cos_d = Math.cos(d),
sin_tc = Math.sin(tc),
cos_tc = Math.cos(tc);
var y = Math.asin(sin_lat1 * cos_d + cos_lat1 * sin_d * cos_tc);
var dlng = Math.atan2(sin_tc * sin_d * cos_lat1, cos_d - sin_lat1 * Math.sin(y));
var x = ((lng1 - dlng + Math.PI) % (2 * Math.PI)) - Math.PI ; // MOD function
var point = new google.maps.LatLng(y/d2r, x/d2r);
circlePoints.push(point);
bounds.extend(point);
if(a==0) {
var offset = new google.maps.Size((circleRadius < 100) ? -5 : -8, 0);
//ELabel(map, point, html, classname, pixelOffset, percentOpacity, isFloatShadow, overlap);
var label = new ELabel(map, point, circleRadius, "style1", offset, 100, false);
label.setMap(map);
}
if (radials && ((a==0) || (a==45) || (a==90) || (a==135) || (a==180) || (a==225) || (a==270) || (a==315))) {
new google.maps.Polyline($.extend({}, polyLineOptions, {
path: [center, point]
}));
}
}
new google.maps.Polyline($.extend({}, polyLineOptions, {
path: circlePoints
}));
map.fitBounds(bounds);//This sets the map bounds to be as big as the target circles, comment out if you don't want it
}
//This function is called on page load to start the refresh of the strikes
function cycle() {
setInterval(CountDown, 1000);
}
var intvl = Sec2Update;
function CountDown() {
intvl -= 1;
if(intvl < 1) {
intvl = Sec2Update;
UpdateKML();
}
$("#cntdwn").html(intvl);
}
//This calls genkml.php on every refresh cycle to generate a new kml file
function UpdateKML() {
$.ajax({
url: 'genkml.php',
type: "GET",
data: {
force: force,
ofd: KMLdate,
nsd: NSdate,
dbg: dbg
},
cache: false,
dataType: '',//????
}).done(function(resp, textStatus) {
var $debugDiv = $("#div1");
if (dbg == 'y') {//Check if we want debug info
if (!$debugDiv.length) {//Check if debug div exists, if not add it to end of body
$debugDiv = $("<div/>").attr('id', 'div1').appendTo('body');
}
var tmpresp = resp || ' ';
$debugDiv.html('Response Status: ' + textStatus + '<br />' + tmpresp);
} else {//Else empty the debug div
$debugDiv.empty();
}
var dates = resp.split("|")[0].split("~");
KMLdate = dates[0];
NSdate = dates[1];
updateHTML(resp);//This calls the updateHTML function if info was returned
});
if(map) {
if(nyLayer) {
map.removeOverlay(nyLayer); //Remove overlays
}
//nyLayer = new KmlLayer(URLToKML + "?rand="+(new Date()).valueOf() );
nyLayer = new google.maps.KmlLayer(URLToKML + "?rand=" + (new Date()).valueOf(), {
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
}
// Time overlayed on map - could be in updateHTML() to just show when .kml read last
$('#currenttime').innerHTML = CurrentTime ("B", "12a", true, TZOffset);
}
function CurrentTime (type, hours, secs, ofs) {
/*
type (char) hours (char) secs (bool) ofs (num)
"U"-UTC "24"=24 hr time true=hh:mm:ss 0=hours from UTC
"B"-User's Browser "12"=12 hr time false=hh:mm
"S"-Web Site "12a"=am/pm
*/
if (type == null){ type = "B"; } // These are the defaults
if (hours == null){ hours = "12a"; }
if (secs == null){ secs = true; }
if (ofs == null){ ofs = 0; }
var currentHour = 0;
var currentMinute = 0;
var currentSecond = 0;
var time = [];
var currentDate = new Date();
if (type == "U") {
currentHour = currentDate.getUTCHours();// UTC
} else if (type == "B") {
currentHour = currentDate.getHours();// Viewer's time
} else {
currentHour = currentDate.getUTCHours() + ofs;// your local time
if(currentHour < 0) { currentHour = currentHour + 24;}
}
currentMinute = currentDate.getMinutes();
currentMinute = (currentMinute < 10 ? "0" : "") + currentMinute;
if (hours == "24") {
if(currentHour == 24) { currentHour = 0 };// use if wanting 24 hour time
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else if (hours == "12") {
if(currentHour == 0) currentHour = 12;
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else {
if(currentHour == 0) currentHour = 12;// else no leading zero for am/pm
}
time.push(currentHour, currentMinute);
if (secs) {
currentSecond = currentDate.getSeconds();
currentSecond = (currentSecond < 10 ? "0" : "") + currentSecond;
time.push(currentSecond);
}
time = time.join(' : ');
if(hours == "12a") {
time = time + " " + (currentHour > 12 ? "PM" : "AM");
}
return time;
}
//This function is only used if you leave the debug checkbox below
// You can remove this function and the checkbox and set the debug
// mode using the dbg=y query parameter
function debug(obj){
if (obj.checked) {
dbg = 'y';
} else {
dbg = 'n';
$('#div1').empty();
}
}
//This function is only used if you leave the Force Update checkbox below
// You can remove this function and the checkbox and set the force
// mode using the force=y query parameter
function forceupdate(obj) {
force = (obj.checked) ? 'y' : 'n';
}
//This function parses out the query parameter value
function gup( name ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
return results ? results[1] : "";
}
/*
You can add custom HTML code here and get access to the additional data that is returned everytime the page calls genkml.php.
In the example below, result is an array that holds 16 values (17, if in debug mode) with each of the values explained below.
*/
function updateHTML(resp) {
var result = resp.split("|");
if (result.length < 16) return;//Make sure there is data
document.getElementById('q1').innerHTML = result[1];//Number of strikes in first quarter of diplay time
document.getElementById('q2').innerHTML = result[2];//Number of strikes in second quarter of diplay time
document.getElementById('q3').innerHTML = result[3];//Number of strikes in third quarter of diplay time
document.getElementById('q4').innerHTML = result[4];//Number of strikes in fourth quarter of diplay time
document.getElementById('numicp').innerHTML = result[6];//Number of IC+ strikes
document.getElementById('numicn').innerHTML = result[5];//Number of IC- strikes
document.getElementById('numcgp').innerHTML = result[7];//Number of CG+ strikes
document.getElementById('numcgn').innerHTML = result[8];//Number of CG- strikes
document.getElementById('ds').innerHTML = result[9];//Total displayed strikes
document.getElementById('ta').innerHTML = result[10];//Total strikes in NSStrikes
document.getElementById('dt').innerHTML = result[11];//Display time
document.getElementById('numicpd').innerHTML = result[13];//Number of IC+ strikes
document.getElementById('numicnd').innerHTML = result[12];//Number of IC- strikes
document.getElementById('numcgpd').innerHTML = result[14];//Number of CG+ strikes
document.getElementById('numcgnd').innerHTML = result[15];//Number of CG- strikes
document.getElementById('tu').innerHTML = Date();//Number of CG- strikes
document.getElementById('sec2up').innerHTML = Sec2Update;//Number of CG- strikes
var dt = result[11] / 4;
document.getElementById('q1t').innerHTML = [0, dt].split('-');//Set time frame headers
document.getElementById('q2t').innerHTML = [dt, 2*dt].split('-');
document.getElementById('q3t').innerHTML = [2*dt, 3*dt].split('-');
document.getElementById('q4t').innerHTML = [3*dt, dt].split('-');
}
//Onload event caller. Does not intefere with OnLoad event in Body tag.
//Put this is after all functions to be called
function addLoadEvent(func) {
$(window).on('load', func);
}
initialize();
FADING_SCROLLER.changecontent();
});
</script>
<script type="text/javascript">
/***********************************************
* Fading Scroller- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************
* Wrapped as module by Beetroot-Beetroot
* Converted to use jQuery calls by Beetroot-Beetroot
* Note: The "proper" approach would be to use the 'color' jQuery plugin
***********************************************/
var FADING_SCROLLER = (function($) {//Module patttern
var delay = 5000; //set delay between message change (in miliseconds)
var maxsteps = 10; //number of steps to take to change from start color to endcolor
var stepdelay = 200; //time in miliseconds of a single step
//**Note: maxsteps*stepdelay will be total time in miliseconds of fading effect
var startcolor = [201,201,201]; //start color (red, green, blue)
var endcolor = [0,0,0]; //end color (red, green, blue)
var fadelinks = 1; //should links inside scroller content also fade like text? 0 for no, 1 for yes.
// *** No need to edit below this line ***
var faderdelay = 0;
var index = 0;
function changecontent() {
var $fscroller = $("#fscroller").css('color', "rgb(" + startcolor.join(', ') + ")");
var $content = $fscroller.find(".NWSinfo div").hide().eq(index).show().end();
if(fadelinks) linkcolorchange(1);
colorfade(1, 15);
index = (index + 1) % $content.length;
}
function linkcolorchange(step) {
$("#fscroller a").each(function() {
$(this).css('color', getstepcolor(step));
});
}
// Rafael Raposo edited function
var fadecounter;
function colorfade(step) {
if(step<=maxsteps) {
$("#fscroller").css('color', getstepcolor(step));
if (fadelinks)
linkcolorchange(step);
step++;
fadecounter = setTimeout(function() {
colorfade(step);
}, stepdelay);
} else {
clearTimeout(fadecounter);
$("#fscroller").css('color', "rgb(" + endcolor.join(', ') + ")");
setTimeout(changecontent, delay);
}
}
//Rafael Raposo's new function
function getstepcolor(step) {
var diff, newcolor = [];
for(var i=0; i<3; i++) {
diff = startcolor[i] - endcolor[i];
if(diff > 0) {
newcolor[i] = startcolor[i] - (Math.round((diff/maxsteps)) * step);
} else {
newcolor[i] = startcolor[i] + (Math.round((Math.abs(diff)/maxsteps)) * step);
}
}
return "rgb(" + newcolor.join(', ') + ")";
}
// *** Expose public methods here ***
return {
changecontent: changecontent
};
})(jQuery);
</script>
I only changed the javascript, not the CSS or HTML. Some comments are included but not really enough considering the scope of the changes.
You will see I wrapped the main script in a $(function(){...}) structure and the Fading Scroller script as a Module. This was done to prevent polluting the global namespace and the possibility of contamination between scripts. I left map in the global namespace in case it's needed in any of the other scripts.
I also made some changes to a local copy of ajaxWDwx.js but I don't think any of them are relevant.