var DH = {
initialized: false,
isIE6CSS: (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? true : false,
isIE: false,
isSafari : (navigator.userAgent && navigator.vendor && (navigator.userAgent.toLowerCase().indexOf("applewebkit") != -1 || navigator.vendor.indexOf("Apple") != -1)),
baseDir: null,
timestamp: 0,
debugWindow: null,
messages: new Array(),
messagesIndex: 0,
includes: new Array(),
onReady: null,
scriptCount: -1,
debug: function(flag, label, value) {
if (flag == false) {
return;
}
var funcName = "none";
if (DH.debug.caller) {
funcName = DH.debug.caller.toString()
funcName = funcName.substring(9, funcName.indexOf(")") + 1)
}
var msg = "-" + funcName + ": " + label + "=" + value
var now = new Date()
var elapsed = now - DH.timestamp
if (elapsed < 10000) {
msg += " (" + elapsed + " msec)"
}
DH.timestamp = now;
if ((DH.debugWindow == null) || DH.debugWindow.closed) {
DH.debugWindow = window.open("", "DebugWin", "toolbar=no,scrollbars=yes,resizable=yes,width=600,height=400");
}
DH.messages[DH.messagesIndex++] = msg;
DH.debugWindow.document.writeln('<html><head><title>Debug Window</title></head><body bgcolor=#DDDDDD>');
for (var i = 0; i < DH.messagesIndex; i++) {
DH.debugWindow.document.writeln('<pre>' + i + ': ' + DH.messages[i] + '</pre>');
}
DH.debugWindow.document.writeln('</body></html>');
DH.debugWindow.document.close();
DH.debugWindow.focus();
},
init: function() {
if (DH.initialized == true) {
return;
}
DH.isIE = !window.opera && navigator.userAgent.indexOf('MSIE') != -1;
if (!document.getElementById || !document.getElementsByTagName) {
alert('Your browser does not support W3C DHTML, use a modern browser like FireFox');
return;
}
if (window.ActiveXObject && !window.XMLHttpRequest) {
window.XMLHttpRequest = function() {
var msxmls = new Array(
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < msxmls.length; i++) {
try {
return new ActiveXObject(msxmls[i]);
} catch (e) {
}
}
return null;
};
}
if (!window.ActiveXObject && window.XMLHttpRequest) {
window.ActiveXObject = function(type) {
switch (type.toLowerCase()) {
case 'microsoft.xmlhttp':
case 'msxml2.xmlhttp':
case 'msxml2.xmlhttp.3.0':
case 'msxml2.xmlhttp.4.0':
case 'msxml2.xmlhttp.5.0':
return new XMLHttpRequest();
}
return null;
};
}
try {
Document.prototype.__defineGetter__("xml", function () {
return (new XMLSerializer()).serializeToString(this);
});
} catch(e) {
}
DH.sprintf = DH.sprintfWrapper.init
DH.initialized = true;
},
addUniqueParm: function(url) {
var extraParm = 'tt=' + new Date().getTime();
if (url.indexOf("?") > 0) {
extraParm = '&' + extraParm;
} else {
extraParm = '?' + extraParm;
}
return url + extraParm;
},
onLoadScript: function() {
if (DH.checkScriptReadyState(this)) {
DH.scriptCount--;
}
if (DH.scriptCount == 0) {
DH.onReady();
}
},
checkIncludes: function() {
if (document.readyState != null) {
var lastReady = 'dono';
while (DH.includes.length > 0 && DH.checkScriptReadyState(DH.includes[0])) {
lastReady = DH.includes[0].readyState;
DH.includes.shift();
}
if (DH.includes.length == 0) {
clearInterval(DH.includesTimer);
alert('loading ready document.readyState != null last=' + lastReady)
DH.onReady();
return true;
} else {
return false;
}
}
else {
clearInterval(DH.includesTimer);
alert('loading ready document.readyState == null')
DH.onReady();
return true;
}
},
checkScriptReadyState: function(scriptObject) {
if (document.readyState == null) {
return true;
}
if (DH.isIE) {
return scriptObject.readyState == "complete" || scriptObject.readyState == "loaded";
} else {
return scriptObject.readyState == "complete" || scriptObject.readyState == "loaded" || scriptObject.readyState == null;
}
},
addEvent: function(elm, evType, callback, useCapture) {
var obj = DH.getObject(elm);
if (obj == null) {
return;
}
if (obj.addEventListener) {
obj.addEventListener(evType, callback, useCapture);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent('on' + evType, callback);
return r;
} else {
obj['on' + evType] = callback;
}
},
removeEvent: function(elm, evType, callback) {
var obj = DH.getObject(elm);
if (obj == null) {
return;
}
if (obj.removeEventListener) {
obj.removeEventListener(evType, callback, false);
return true;
} else if (obj.detachEvent) {
var r = obj.detachEvent('on' + evType, callback);
return r;
} else {
obj['on' + evType] = null;
}
},
getEvent: function(e) {
return window.event ? window.event : e;
},
getEventTarget: function(e) {
var target = window.event ? window.event.srcElement : e ? e.target : null;
if (target != null && target.nodeType == 3) {
target = target.parentNode;
}
return target;
},
cancelEvent: function(e) {
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
return;
}
if (e) {
e.stopPropagation();
e.preventDefault();
}
},
getEventX: function(e) {
var x;
if (e.pageX) {
x = e.pageX;
} else if (e.clientX) {
x = e.clientX;
if (DH.isIE) {
x += document.body.scrollLeft;
}
}
return x;
},
getEventY: function(e) {
var y;
if (e.pageY) {
y = e.pageY;
} else if (e.clientY) {
y = e.clientY;
if (DH.isIE) {
y += document.body.scrollTop;
}
}
return y;
},
blink: function(elm, cnt, interval) {
var obj = DH.getObject(elm)
if (cnt <= 0) {
DH.show(obj);
return;
}
DH.toggleVisibility(obj);
setTimeout(function() {
DH.blink(obj, cnt - 1, interval)
}, interval);
},
fixPNG: function(myImage) {
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (version < 7) && (document.body.filters))
{
var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
var imgTitle = (myImage.title) ?
"title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
var imgStyle = "display:inline-block;" + myImage.style.cssText
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + myImage.width
+ "px; height:" + myImage.height
+ "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
myImage.outerHTML = strNewHTML
}
},
getBaseDir: function() {
if (DH.baseDir != null) {
return DH.baseDir;
}
var head = document.getElementsByTagName('head')[0];
var nodes = head.childNodes;
for (var i = 0; i < nodes.length; ++i) {
var src = nodes.item(i).src;
DH.debug(false, 'src', src)
if (src) {
var index = src.indexOf("/DHTML.js");
if (index < 0) {
index = src.indexOf("/all");
}
if (index >= 0) {
DH.baseDir = src.substring(0, index);
break;
}
}
}
return DH.baseDir;
},
getInsideWindowWidth: function () {
if (window.innerWidth) {
return window.innerWidth;
} else if (DH.isIE6CSS) {
return document.body.parentElement.clientWidth
} else if (document.body && document.body.clientWidth) {
return document.body.clientWidth;
}
return 0;
},
getInsideWindowHeight: function () {
if (window.innerHeight) {
return window.innerHeight;
} else if (DH.isIE6CSS) {
return document.body.parentElement.clientHeight
} else if (document.body && document.body.clientHeight) {
return document.body.clientHeight;
}
return 0;
},
getObject: function(obj) {
if (typeof obj == "string") {
return document.getElementById(obj);
} else {
return obj;
}
},
getObjectInWindow: function(winId, objId) {
try {
var winObj = eval(winId);
return winObj.document.getElementById(objId);
} catch(e) {
return null;
}
},
getStyleObject: function(obj) {
try {
return DH.getObject(obj).style;
} catch(e) {
return null;
}
},
getObjectX: function(obj) {
obj = DH.getObject(obj);
var curLeft = 0;
if (obj.offsetParent) {
do {
curLeft += obj.offsetLeft;
} while (obj = obj.offsetParent);
} else if (obj.x) {
curLeft += obj.x;
}
return curLeft;
},
getObjectY: function(obj) {
obj = DH.getObject(obj);
var curTop = 0;
if (obj.offsetParent) {
do {
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
} else if (obj.y) {
curTop += obj.y;
}
return curTop;
},
getObjectLeft: function (obj) {
var styleObj = DH.getStyleObject(obj);
if (styleObj == null) {
return 0;
}
return parseInt(styleObj.left);
},
getObjectTop: function (obj) {
var styleObj = DH.getStyleObject(obj);
if (styleObj == null) {
return 0;
}
return parseInt(styleObj.top);
},
getObjectWidth: function (obj) {
var elem = DH.getObject(obj);
var result = 0;
if (elem.offsetWidth) {
result = elem.offsetWidth;
} else if (elem.clip && elem.clip.width) {
result = elem.clip.width;
} else if (elem.style && elem.style.pixelWidth) {
result = elem.style.pixelWidth;
}
return parseInt(result);
},
getObjectHeight: function (obj) {
var elem = DH.getObject(obj);
var result = 0;
if (elem.offsetHeight) {
result = elem.offsetHeight;
} else if (elem.clip && elem.clip.height) {
result = elem.clip.height;
} else if (elem.style && elem.style.pixelHeight) {
result = elem.style.pixelHeight;
}
return parseInt(result);
},
_getParameter: function(string, parm, delim) {
if (string.length == 0) {
return '';
}
var sPos = string.indexOf(parm + "=");
if (sPos == -1) {
return '';
}
sPos = sPos + parm.length + 1;
var ePos = string.indexOf(delim, sPos);
if (ePos == -1) {
ePos = string.length;
}
return unescape(string.substring(sPos, ePos));
}
,
getPageParameter: function(parameterName, defaultValue) {
var s = self.location.search;
if ((s == null) || (s.length < 1)) {
return defaultValue;
}
s = DH._getParameter(s, parameterName, '&');
if ((s == null) || (s.length < 1)) {
s = defaultValue;
}
return s;
}
,
getMSDomDocumentPrefix:  function() {
if (DH.msDomDocumentPrefix) {
return DH.msDomDocumentPrefix;
}
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
var o;
for (var i = 0; i < prefixes.length; i++) {
try {
o = new ActiveXObject(prefixes[i] + ".DomDocument");
return DH.msDomDocumentPrefix = prefixes[i];
}
catch (ex) {
}
}
alert("Could not find an installed MSXML parser");
},
createXmlDocument: function () {
try {
if (document.implementation && document.implementation.createDocument) {
var doc = document.implementation.createDocument("", "", null);
if (doc.readyState == null) {
doc.readyState = 1;
doc.addEventListener("load", function () {
doc.readyState = 4;
if (typeof doc.onreadystatechange == "function")
doc.onreadystatechange();
}, false);
}
return doc;
}
if (window.ActiveXObject) {
return new ActiveXObject(DH.getMSDomDocumentPrefix() + ".DomDocument");
}
}
catch (ex) {
}
alert("Sorry, your browser does not support XmlDocument objects");
},
escape : function(s) {
return s.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
},
getXML: function(url, callback) {
DH._xhrBusy();
var xmlhttp = new XMLHttpRequest();
if (!xmlhttp || xmlhttp == null) {
alert('No browser XMLHttpRequest (AJAX) support');
return;
}
var cb = callback;
var async = false;
if (cb) {
async = true;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
cb(xmlhttp.responseXML);
DH._xhrReady();
} else {
alert('Problem retrieving XML data:\n' + xmlhttp.statusText);
}
}
};
}
xmlhttp.open('GET', url, async);
xmlhttp.send(null);
if (!cb) {
DH._xhrReady();
if (xmlhttp.status != 200) {
alert('Problem retrieving XML data:\n' + xmlhttp.statusText);
return null;
}
return xmlhttp.responseXML;
}
}
,
postXML: function(url, doc, callback) {
DH._xhrBusy();
var xmlhttp = new XMLHttpRequest();
if (!xmlhttp || xmlhttp == null) {
alert('No browser XMLHttpRequest (AJAX) support');
return;
}
var cb = callback;
var async = false;
if (cb) {
async = true;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
cb(xmlhttp.responseXML);
DH._xhrReady();
} else {
alert('Problem retrieving XML data using async POST:\n' + xmlhttp.statusText);
}
}
};
}
xmlhttp.open('POST', url, async);
if (this.isSafari) {
xmlhttp.send(doc);
} else {
xmlhttp.send(doc.xml);
}
if (!cb) {
DH._xhrReady();
if (xmlhttp.status != 200) {
alert('Problem retrieving XML data using async POST:\n' + xmlhttp.statusText);
return null;
}
return xmlhttp.responseXML;
}
}
,
getURL: function(url, callback) {
url = DH.addUniqueParm(url);
var xmlhttp = new XMLHttpRequest();
if (!xmlhttp || xmlhttp == null) {
alert('No browser XMLHttpRequest (AJAX) support');
return;
}
var cb = callback;
var async = false;
if (cb) {
async = true;
xmlhttp.onreadystatechange = function() {
DH._xhrReady();
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
cb(xmlhttp.responseText);
} else {
alert('Problem retrieving URL data (' + xmlhttp.status + ')\n' + xmlhttp.statusText);
}
}
};
}
DH._xhrBusy();
xmlhttp.open('GET', url, async);
xmlhttp.send(null);
if (!cb) {
DH._xhrReady();
if (xmlhttp.status != 200) {
alert('Problem retrieving URL data:\n' + xmlhttp.statusText);
return null;
}
return xmlhttp.responseText;
}
}
,
_xhrBusy: function() {
},
_xhrReady: function(httpStatus) {
},
include: function(url) {
var fullPath = DH.getBaseDir() + '/' + url;
fullPath = DH.addUniqueParm(fullPath);
var agent = navigator.userAgent;
var docWrite = (agent.match("MSIE") || agent.match("Safari"));
if (!document.getElementById(url)) {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = fullPath;
script.id = url;
script.onload = DH.onLoadScript;
script.onreadystatechange = DH.onLoadScript;
if (DH.scriptCount == -1) {
DH.scriptCount = 0;
}
DH.scriptCount++;
document.getElementsByTagName('head')[0].appendChild(script);
DH.includes.push(script);
}
},
setObjectXY: function(obj, x, y) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
var units = (typeof theObj.left == "string") ? 'px' : 0;
if (x) theObj.left = x + units;
if (y) theObj.top = y + units;
}
}
,
setObjectWH: function(obj, w, h) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
var units = (typeof theObj.left == "string") ? 'px' : 0;
if (w) theObj.width = w + units;
if (h) theObj.height = h + units;
}
}
,
setObjectXYWH: function(obj, x, y, w, h) {
DH.setObjectXY(obj, x, y);
DH.setObjectWH(obj, w, h);
}
,
shiftTo: function(obj, x, y) {
DH.setObjectXY(obj, x, y);
}
,
shiftTo: function(obj, x, y) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
var units = (typeof theObj.left == "string") ? 'px' : 0;
theObj.left = x + units;
theObj.top = y + units;
}
}
,
shiftBy: function(obj, deltaX, deltaY) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
var units = (typeof theObj.left == "string") ? 'px' : 0;
theObj.left = (parseInt(theObj.left) + deltaX) + units;
theObj.top = (parseInt(theObj.top) + deltaY) + units;
}
}
,
setBGColor: function(obj, color) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.backgroundColor = color;
}
}
,
setHTML: function(obj, html) {
var theObj = DH.getObject(obj);
if (theObj != null) {
theObj.innerHTML = html;
}
}
,
addHTML: function(obj, html) {
var theObj = DH.getObject(obj);
if (theObj != null) {
theObj.innerHTML += html;
}
}
,
setOpacity: function(obj, val) {
var o = DH.getObject(obj);
if (o != null) {
if (typeof(o.style.filter) == 'string') {
o.style.filter = 'alpha(opacity:' + val * 100 + ')';
}
if (typeof(o.style.KHTMLOpacity) == 'string') {
o.style.KHTMLOpacity = val;
}
if (typeof(o.style.MozOpacity) == 'string') {
o.style.MozOpacity = val;
}
if (typeof(o.style.opacity) == 'string') {
o.style.opacity = val;
}
}
}
,
setZIndex: function(obj, zOrder) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.zIndex = zOrder;
}
}
,
show: function(obj) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.visibility = "visible";
}
}
,
isVisible: function(obj) {
var theObj = DH.getStyleObject(obj);
if (theObj == null) {
return false;
}
return theObj.visibility == "visible" ? true : false;
}
,
toggleVisibility: function(obj) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.visibility = (theObj.visibility == "visible") ? "hidden" : "visible";
}
}
,
toggleDisplay: function(obj) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.display = (theObj.display == "none") ? "block" : "none";
}
}
,
displayOn: function(obj) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.display = 'block';
}
}
,
displayOff: function(obj) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.display = 'none';
}
}
,
hide: function(obj) {
var theObj = DH.getStyleObject(obj);
if (theObj != null) {
theObj.visibility = "hidden";
}
}
,
dragging: false,
dragTarget
:
null,
dragStartX
:
0,
dragStartY
:
0,
dragEnable
:
function (target, onStart, onDrag, onEnd) {
target.onStart = onStart;
target.onDrag = onDrag;
target.onEnd = onEnd;
DH.addEvent(target, 'mousedown', DH._dragStart, false);
}
,
dragDisable: function (target) {
target.onStart = null;
target.onDrag = null;
target.onEnd = null;
DH.removeEvent(target, 'mousedown', DH._dragStart);
}
,
_dragStart: function (e) {
DH.dragging = true;
DH.dragTarget = DH.getEventTarget(e);
e = DH.getEvent(e);
DH.dragStartX = DH.getEventX(e);
DH.dragStartY = DH.getEventY(e);
DH.addEvent(document, 'mousemove', DH._dragMove, false);
DH.addEvent(document, 'mouseup', DH._dragEnd, false);
if (DH.dragTarget.onStart != null) {
DH.dragTarget.onStart(DH.dragTarget, DH.dragStartX, DH.dragStartY);
}
}
,
_dragMove: function (e) {
if (DH.dragging == true) {
e = DH.getEvent(e);
var ex = DH.getEventX(e);
var ey = DH.getEventY(e);
if (DH.dragTarget.onDrag != null) {
DH.dragTarget.onDrag(DH.dragTarget, ex, ey, ex - DH.dragStartX, ey - DH.dragStartY);
}
DH.dragStartX = ex;
DH.dragStartY = ey;
return true;
} else {
return false;
}
}
,
_dragEnd: function (e) {
e = DH.getEvent(e);
if (DH.dragTarget.onEnd != null) {
DH.dragTarget.onEnd(DH.dragTarget, DH.getEventX(e), DH.getEventY(e));
}
DH.dragging = false;
DH.dragTarget = null;
DH.cancelEvent(e);
DH.removeEvent(document, 'mousemove', DH._dragMove);
DH.removeEvent(document, 'mouseup', DH._dragEnd);
return false;
},
sprintfWrapper : {
init : function () {
if (typeof arguments == "undefined") {
return null;
}
if (arguments.length < 1) {
return null;
}
if (typeof arguments[0] != "string") {
return null;
}
if (typeof RegExp == "undefined") {
return null;
}
var string = arguments[0];
var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
var matches = new Array();
var strings = new Array();
var convCount = 0;
var stringPosStart = 0;
var stringPosEnd = 0;
var matchPosEnd = 0;
var newString = '';
var match = null;
while (match = exp.exec(string)) {
if (match[9]) {
convCount += 1;
}
stringPosStart = matchPosEnd;
stringPosEnd = exp.lastIndex - match[0].length;
strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
matchPosEnd = exp.lastIndex;
matches[matches.length] = {
match: match[0],
left: match[3] ? true : false,
sign: match[4] || '',
pad: match[5] || ' ',
min: match[6] || 0,
precision: match[8],
code: match[9] || '%',
negative: parseInt(arguments[convCount]) < 0 ? true : false,
argument: String(arguments[convCount])
};
}
strings[strings.length] = string.substring(matchPosEnd);
if (matches.length == 0) {
return string;
}
if ((arguments.length - 1) < convCount) {
return null;
}
var code = null;
var match = null;
var i = null;
var substitution;
for (i = 0; i < matches.length; i++) {
if (matches[i].code == '%') {
substitution = '%'
}
else if (matches[i].code == 'b') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
substitution = DH.sprintfWrapper.convert(matches[i], true);
}
else if (matches[i].code == 'c') {
matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
substitution = DH.sprintfWrapper.convert(matches[i], true);
}
else if (matches[i].code == 'd') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
substitution = DH.sprintfWrapper.convert(matches[i]);
}
else if (matches[i].code == 'f') {
matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
substitution = DH.sprintfWrapper.convert(matches[i]);
}
else if (matches[i].code == 'o') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
substitution = DH.sprintfWrapper.convert(matches[i]);
}
else if (matches[i].code == 's') {
matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
substitution = DH.sprintfWrapper.convert(matches[i], true);
}
else if (matches[i].code == 'x') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
substitution = DH.sprintfWrapper.convert(matches[i]);
}
else if (matches[i].code == 'X') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
substitution = DH.sprintfWrapper.convert(matches[i]).toUpperCase();
}
else {
substitution = matches[i].match;
}
newString += strings[i];
newString += substitution;
}
newString += strings[i];
return newString;
},
convert : function(match, nosign) {
if (nosign) {
match.sign = '';
} else {
match.sign = match.negative ? '-' : match.sign;
}
var l = match.min - match.argument.length + 1 - match.sign.length;
var pad = new Array(l < 0 ? 0 : l).join(match.pad);
if (!match.left) {
if (match.pad == "0" || nosign) {
return match.sign + pad + match.argument;
} else {
return pad + match.sign + match.argument;
}
} else {
if (match.pad == "0" || nosign) {
return match.sign + match.argument + pad.replace(/0/g, ' ');
} else {
return match.sign + match.argument + pad;
}
}
}
}
}
DH.addEvent(window, 'load', DH.init, false);
var GMAP = {
map: null,
mapDiv: null,
mapTypes: [],
defaultCenter: null,
defaultZoom: 10,
defaultMapName: 'satellite',
DEGREES_PER_RADIAN: 360 / (2 * Math.PI),
RAD_PER_DEGREE: 0.01745566,
keyNone : {
key: "",
reg: "^"
},
keyArray : new Array(),
addKey: function(aName, aKey, aURLRegExp) {
GMAP.keyArray[aName] = { key: aKey, reg: aURLRegExp };
},
addMapType: function(aName, aSpec) {
GMAP.mapTypes[aName] = aSpec;
},
addTileMap: function(aTileSpec) {
var tileLayer = new GTileLayer(new GCopyrightCollection("GT"),
aTileSpec.minZoom ? aTileSpec.minZoom : 1,
aTileSpec.maxZoom ? aTileSpec.maxZoom: 20);
tileLayer.getTileUrl = function(point, zoom) {
return aTileSpec.baseURL + "/" + zoom + "/" + point.x + "/" + point.y + "." + aTileSpec.imageType;
}
tileLayer.isPng = function() {
return aTileSpec.imageType == 'png';
}
tileLayer.getOpacity = function() {
return 1.0;
}
var mapLayers = [tileLayer];
var mapType = new GMapType(mapLayers, G_SATELLITE_MAP.getProjection(), aTileSpec.id);
GMAP.addMapType(aTileSpec.id, mapType);
},
setMapType: function(aName) {
GMAP.map.setMapType(GMAP.mapTypes[aName]);
},
getMapSize: function(aName) {
return new GSize(DH.getObjectWidth(GMAP.mapDiv), DH.getObjectHeight(GMAP.mapDiv));
},
loadGoogleMapScript: function(aVersion) {
var version = '2.225';
if (aVersion) {
version = aVersion;
}
var k;
for (k in GMAP.keyArray) {
var key = GMAP.keyArray[k];
var regexp = new RegExp(key.reg);
if (regexp.test(window.location.href)) {
document.write('<' + 'script src="http://maps.google.com/maps?file=api&amp;v=' + version + '&amp;key=' + key.key + '" type="text/javascript"><' + '/script>');
break;
}
}
},
makePath: function(aNumber) {
return DH.sprintf("%03d/%03d/%03d", aNumber/1000000, (aNumber/1000)%1000, aNumber%1000);
},
makeTileCachePath: function(aRootDir, zoom, x, y, fileExtension) {
return aRootDir + "/" + zoom + "/" + GMAP.makePath(x) + "/" + GMAP.makePath(y) + fileExtension;
},
setDefaultMapParms: function(aCenter, aZoom, aMapName) {
GMAP.defaultCenter = aCenter;
GMAP.defaultZoom = aZoom;
GMAP.defaultMapName = aMapName;
},
showMap: function() {
var center = DH.getPageParameter('center', null);
if (center == null) {
if (GMAP.defaultCenter == null) {
GMAP.defaultCenter = new GLatLng(52.37261, 4.900435);
}
center = GMAP.defaultCenter;
} else {
var llArr = center.split(',');
center = new GLatLng(llArr[1], llArr[0]);
}
var mapName = DH.getPageParameter('map', GMAP.defaultMapName);
var zoomLevel = DH.getPageParameter('zoom', null);
if (zoomLevel == null) {
zoomLevel = GMAP.defaultZoom;
} else {
zoomLevel = parseInt(zoomLevel);
}
GMAP.map.setCenter(center, zoomLevel, GMAP.mapTypes[mapName]);
},
pixelToLatLon: function(x, y) {
return GMAP.map.fromContainerPixelToLatLng(new GPoint(x,y));
},
createGMap: function(divId) {
GMAP.mapDiv = DH.getObject(divId);
GMAP.resize();
var mapOpts = {
size: GMAP.getMapSize(),
draggableCursor:"default",
draggingCursor:"default"
}
GMAP.map = new GMap2(GMAP.mapDiv, mapOpts);
for (var i in GMAP.mapTypes) {
GMAP.map.addMapType(GMAP.mapTypes[i]);
}
},
isInBox: function(pt, bounds) {
return (pt.x > bounds.minX && pt.y > bounds.minY && pt.x < bounds.maxX && pt.y < bounds.maxY);
},
distance: function(a, b) {
if (a.x == b.x && a.y == b.y) {
return 0.0;
}
var rad = 0.01745566;
Lo = Math.abs(a.x - b.x);
Drad = Math.acos((Math.sin(a.y * rad) * Math.sin(b.y * rad)) + (Math.abs(Math.cos(a.y * rad)) * Math.abs(Math.cos(b.y * rad)) * Math.cos(Lo * rad)));
Crad = Math.acos((Math.sin(b.y * rad) - (Math.sin(a.y * rad) * Math.cos(Drad))) / (Math.cos(a.y * rad) * Math.sin(Drad)));
var Cdeg = Crad * 57.295779;
return Drad * 57.295779 * 69.06 * 1.6094;
},
heading: function(lat1, lon1, lat2, lon2) {
var v1, v2;
lat1 = lat1 * GMAP.RAD_PER_DEGREE;
lon1 = lon1 * GMAP.RAD_PER_DEGREE;
lat2 = lat2 * GMAP.RAD_PER_DEGREE;
lon2 = lon2 * GMAP.RAD_PER_DEGREE;
v1 = Math.sin(lon1 - lon2) * Math.cos(lat2);
v2 = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2);
if (Math.abs(v1) < 1e-15) {
v1 = 0.0;
}
if (Math.abs(v2) < 1e-15) {
v2 = 0.0;
}
var course = Math.atan2(v1, v2);
course = course * GMAP.DEGREES_PER_RADIAN
if (course < 0) {
course = -course;
}
if (lon2 < lon1) {
course = 360 - course;
}
return course;
},
speed: function(a, b) {
return (a.distanceFrom(b) / 1000) / ((b.time - a.time) / 3600000);
},
positionOverview: function () {
var mapOverview = DH.getObject('map_overview');
DH.setObjectXY(mapOverview, DH.getObjectWidth(GMAP.mapDiv) - DH.getObjectWidth(mapOverview) - 4, DH.getObjectTop(GMAP.mapDiv) + 4);
},
resize: function() {
var topAnchor = DH.getObject("topanchor");
var bottomAnchor = DH.getObject("bottomanchor");
DH.setObjectXYWH(GMAP.mapDiv, 0, DH.getObjectY(topAnchor), DH.getObjectX(bottomAnchor), DH.getInsideWindowHeight() - DH.getObjectY(topAnchor));
if (GMAP.map) {
GMAP.map.checkResize();
if (DH.getObject('map_overview')) {
setTimeout("GMAP.positionOverview()", 1);
}
}
}
}
var MAGIC_NUMBER = 6356752.3142;
var DEG2RAD = 0.0174532922519943;
var PI = 3.14159267;
function dd2MercMetersLng(p_lng) {
return MAGIC_NUMBER * (p_lng * DEG2RAD);
}
function dd2MercMetersLat(p_lat) {
if (p_lat >= 85) p_lat = 85;
if (p_lat <= -85) p_lat = -85;
return MAGIC_NUMBER * Math.log(Math.tan(((p_lat * DEG2RAD) + (PI / 2)) / 2));
}
var CustomGetTileUrl = function(a, b, c) {
if (typeof(window['this.myMercZoomLevel']) == "undefined") this.myMercZoomLevel = 0;
if (typeof(window['this.myStyles']) == "undefined") this.myStyles = "";
var lULP = new GPoint(a.x * 256, (a.y + 1) * 256);
var lLRP = new GPoint((a.x + 1) * 256, a.y * 256);
var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP, b, c);
var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP, b, c);
if (this.myMercZoomLevel != 0 && map.getZoom() < this.myMercZoomLevel) {
var lBbox = dd2MercMetersLng(lUL.lngDegrees) + "," + dd2MercMetersLat(lUL.latDegrees) + "," + dd2MercMetersLng(lLR.lngDegrees) + "," + dd2MercMetersLat(lLR.latDegrees);
var lSRS = "EPSG:54004";
} else {
var lBbox = lUL.x + "," + lUL.y + "," + lLR.x + "," + lLR.y;
var lSRS = "EPSG:4326";
}
var lURL = this.myBaseURL;
lURL += "&REQUEST=GetMap";
lURL += "&SERVICE=WMS";
lURL += "&VERSION=" + this.myVersion;
lURL += "&LAYERS=" + this.myLayers;
lURL += "&STYLES=" + this.myStyles;
lURL += "&FORMAT=" + this.myFormat;
lURL += "&BGCOLOR=" + this.myBgColor;
lURL += "&TRANSPARENT=TRUE";
lURL += "&SRS=" + lSRS;
lURL += "&BBOX=" + lBbox;
lURL += "&WIDTH=256";
lURL += "&HEIGHT=256";
lURL += "&reaspect=false";
return lURL;
}
function createWMSSpec(wmsURL, gName, gShortName, wmsLayers, wmsStyles, wmsFormat, wmsVersion, wmsBgColor, wmsSrs) {
var tile = new GTileLayer(new GCopyrightCollection(""), 1, 17);
tile.myLayers = wmsLayers;
tile.myStyles = (wmsStyles ? wmsStyles : "");
;
tile.myFormat = (wmsFormat ? wmsFormat : "image/gif");
;
tile.myVersion = (wmsVersion ? wmsVersion : "1.1.1");
tile.myBgColor = (wmsBgColor ? wmsBgColor : "0xFFFFFF");
tile.myBaseURL = wmsURL;
tile.getTileUrl = CustomGetTileUrl;
var layer = [tile];
var mapType = new GMapType(layer, G_SATELLITE_MAP.getProjection(), gName, G_SATELLITE_MAP);
return mapType;
}
function createWMSOverlaySpec(gSpec, wmsSpec, gName, gShortName) {
wmsSpec.getTileLayers()[0].getOpacity = function() {
return 1.0;
}
var layers = [gSpec.getTileLayers()[0], wmsSpec.getTileLayers()[0]];
return new GMapType(layers, gSpec.getProjection(), gShortName);
}
var SIG = '<a style="background-color:#555555; font:10px verdana;text-decoration:none;padding:2px;color:yellow;" href="#" onClick="window.open(\'http://www.geotracing.com\'); return false;">GeoTracing Powered</a>';
GMAP.addKey('geotracing',
'ABQIAAAAD3bxjYK2kuWoA5XU4dh89xRLLtc0-1T5fqcwUKDTcgBoUGcRixSIPo5Dq2y4XMqndWO7D5kczi5x-w',
"^https?://geotracing.com/.*");
GMAP.addKey('www.geotracing',
'ABQIAAAAD3bxjYK2kuWoA5XU4dh89xRLLtc0-1T5fqcwUKDTcgBoUGcRixSIPo5Dq2y4XMqndWO7D5kczi5x-w',
"^https?://.*.geotracing.com/.*");
GMAP.loadGoogleMapScript();
var GW = {
url: '/proto.srv',
timeoutMins : 5,
protocolVersion : '4.0',
userId: null,
agentKey: null,
onNegRsp: null,
webRoot: null,
IS_SAFARI : (navigator.userAgent && navigator.vendor && (navigator.userAgent.toLowerCase().indexOf("applewebkit") != -1 || navigator.vendor.indexOf("Apple") != -1)),
loginReqDoc: null,
recovering: false,
user: null,
pwd: null,
init: function(nrspCallback, theTimeoutMins, theWebRoot) {
if (!document.getElementsByTagName) {
alert('No browser XML support');
return;
}
GW.onNegRsp = nrspCallback;
GW.timeoutMins = theTimeoutMins ? theTimeoutMins : GW.timeoutMins;
if (theWebRoot) {
GW.webRoot = theWebRoot;
} else {
GW.webRoot = GW._getWebRoot();
}
GW.url = GW.webRoot + GW.url;
GW.request(GW.createRequest('ses-create-req'), null);
},
isLoggedIn: function() {
return GW.userId != null;
},
createCallback: function(cbFunOrObj, name) {
if (cbFunOrObj == null) {
return null;
}
var callback;
if (name && cbFunOrObj[name + 'Rsp']) {
callback = new GWCallbackObj(cbFunOrObj, name + 'Rsp', name + 'NegRsp');
} else {
callback = new GWCallbackFun(cbFunOrObj);
}
return callback;
},
createRequest: function(tag) {
var xmlDoc = XmlDocument.create();
var elm = xmlDoc.createElement(tag);
xmlDoc.appendChild(elm);
return xmlDoc;
},
login: function(callback, user, password, ismd5) {
var doc = GW.createRequest('ses-login-req');
var xml = doc.documentElement;
xml.setAttribute('name', user);
xml.setAttribute('password', password);
xml.setAttribute('agent', "web");
xml.setAttribute('ismd5', ismd5);
GW.user = user;
GW.pwd = password;
xml.setAttribute('protocolVersion', GW.protocolVersion);
GW.loginReqDoc = doc;
GW.request(doc, GW.createCallback(callback, 'login'));
},
logout: function(callback) {
var doc = GW.createRequest('ses-logout-req');
GW.request(doc, GW.createCallback(callback, 'logout'));
},
selectApp: function() {
alert('selectApp is no longer required, pls remove from your code')
},
request: function(aReqDoc, aCallback) {
if (aCallback == null || !aCallback) {
return GW._send(null, aReqDoc);
} else {
var cb = aCallback;
if (!cb instanceof GWCallbackObj && !cb instanceof GWCallbackFun) {
cb = GW.createCallback(aCallback);
}
GW._send(cb, aReqDoc);
}
},
isPositive: function(element) {
return element.tagName.lastIndexOf('-rsp') != -1;
},
storeSession: function() {
GW._createCookie('agentkey', GW.agentKey, 1);
},
restoreSession: function() {
GW.agentKey = GW._readCookie('agentkey');
},
clearAccount: function() {
GW.user = ' ';
GW.pwd = ' ';
GW._eraseCookie('kwacc');
},
storeAccount: function() {
GW._createCookie('kwacc', GW.user + ',' + GW.pwd, 365);
},
getAccountData: function() {
var data = GW._readCookie('kwacc');
return (data && data != null && data.length > 0) ? data.split(',') : null;
},
_camelizeCmd: function(s) {
if (s.indexOf('-nrsp') > 0) {
s = s.substring(0, s.indexOf('-nrsp')) + '-neg-rsp';
}
return GW._camelize(s.substring(s.indexOf('-') + 1, s.length));
},
_camelize: function(s) {
var parts = s.split('-'), len = parts.length;
if (len == 1) return parts[0];
var camelized = s.charAt(0) == '-'
? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
: parts[0];
for (var i = 1; i < len; i++)
camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
return camelized;
},
_getWebRoot: function() {
var webRoot;
var head = document.getElementsByTagName('head')[0];
var nodes = head.childNodes;
for (var i = 0; i < nodes.length; ++i) {
var src = nodes.item(i).src;
if (src) {
var index = src.indexOf("GWClient.js");
if (index < 0) {
index = src.indexOf("all");
}
if (index >= 0) {
if (src.indexOf("lib") >= 0) {
index = src.indexOf("lib");
}
webRoot = src.substring(0, index);
break;
}
}
}
return webRoot;
},
_negativeRsp: function(callback, element) {
var errorId = element.getAttribute('errorId'),
errorStr = element.getAttribute('error'),
details = element.getAttribute('details'), tagName = element.tagName;
try {
callback.doNegRsp(errorId, errorStr, details, tagName);
} catch(ex) {
throw ex;
}
},
_recoverSession: function(callback, reqDoc) {
GW.agentKey = null;
GW.userId = null;
GW.recovering = true;
var onLoginRsp = function(rsp) {
GW.agentKey = rsp.getAttribute('agentkey');
GW.userId = rsp.getAttribute('userid');
GW.recovering = false;
return GW._send(callback, reqDoc);
}
GW._send(GW.createCallback(onLoginRsp), GW.loginReqDoc);
},
_send: function(callback, doc) {
var xmlhttp = new XMLHttpRequest();
var async = false;
if (callback) {
async = true;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var element = xmlhttp.responseXML.documentElement;
var tagName = element.tagName;
if (GW.isPositive(element)) {
switch (tagName) {
case 'ses-create-rsp':
GW.agentKey = element.getAttribute('agentkey');
break;
case 'ses-login-rsp':
GW.agentKey = element.getAttribute('agentkey');
GW.userId = element.getAttribute('userid');
break;
case 'ses-logout-rsp':
GW.userId = null;
break;
}
try {
callback.doRsp(element);
} catch(ex) {
throw ex;
}
} else if (element.getAttribute('errorId') == '4007') {
if (GW.isLoggedIn()) {
GW._recoverSession(callback, doc);
} else if (GW.recovering) {
setTimeout(function() {
GW._send(callback, doc)
}, 3000);
} else {
GW._negativeRsp(callback, element);
}
} else {
GW._negativeRsp(callback, element);
}
}
}
}
var qs = GW.agentKey == null ? '?gw_timeout=' + GW.timeoutMins : '?agentkey=' + GW.agentKey;
qs += '&gw_t=' + (new Date().getTime());
var method = 'POST';
if (doc.documentElement.childNodes.length == 0) {
method = 'GET';
qs += '&gw_cmd=' + doc.documentElement.nodeName;
var attrs = doc.documentElement.attributes;
var i;
for (i = 0; i < attrs.length; i++) {
qs += '&' + attrs[i].name + '=' + attrs[i].value;
}
}
xmlhttp.open(method, GW.url + qs, async);
if (method == 'POST') {
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
if (this.IS_SAFARI) {
xmlhttp.send(doc);
} else {
xmlhttp.send(doc.xml);
}
} else {
xmlhttp.send(null);
}
if (!callback) {
if (xmlhttp.status != 200) {
alert('Problem retrieving XML data:\n' + xmlhttp.statusText);
return null;
}
var element = xmlhttp.responseXML.documentElement;
if (element.getAttribute('errorId') == '4007') {
if (GW.isLoggedIn()) {
return GW._recoverSession(callback, doc);
} else if (GW.recovering) {
setTimeout(function() {
GW._send(callback, doc)
}, 3000);
return;
}
}
if (GW.isPositive(element)) {
switch (element.tagName) {
case 'ses-create-rsp':
GW.agentKey = element.getAttribute('agentkey');
break;
case 'ses-login-rsp':
GW.agentKey = element.getAttribute('agentkey');
GW.userId = element.getAttribute('userid');
break;
case 'ses-logout-rsp':
GW.userId = null;
break;
}
}
return element;
}
},
_createCookie: function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
},
_readCookie: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
},
_eraseCookie: function(name) {
GW._createCookie(name, "", -1);
}
}
function GWCallbackObj(obj, rsp, nrsp) {
this.obj = obj;
this.rsp = rsp;
if (!this.obj[this.rsp]) {
alert('He JoeS de functie ' + rsp + ' moet wel bestaan in je object !!');
}
this.nrsp = nrsp;
}
GWCallbackObj.prototype.doRsp = function(element) {
this.obj[this.rsp](element);
}
GWCallbackObj.prototype.doNegRsp = function(errorId, errorStr, details, tagName) {
if (this.obj[this.nrsp]) {
this.obj[this.nrsp](errorId, errorStr, details, tagName);
} else {
GW.onNegRsp(errorId, errorStr, details, tagName);
}
}
function GWCallbackFun(fun) {
this.fun = fun;
}
GWCallbackFun.prototype.doRsp = function(element) {
this.fun(element);
}
GWCallbackFun.prototype.doNegRsp = function(errorId, errorStr, details, tagName) {
GW.onNegRsp(errorId, errorStr, details, tagName);
}
function getDomDocumentPrefix() {
if (getDomDocumentPrefix.prefix)
return getDomDocumentPrefix.prefix;
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
var o;
for (var i = 0; i < prefixes.length; i++) {
try {
o = new ActiveXObject(prefixes[i] + ".DomDocument");
return getDomDocumentPrefix.prefix = prefixes[i];
}
catch (ex) {
}
;
}
throw new Error("Could not find an installed XML parser");
}
function getXmlHttpPrefix() {
if (getXmlHttpPrefix.prefix)
return getXmlHttpPrefix.prefix;
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
var o;
for (var i = 0; i < prefixes.length; i++) {
try {
o = new ActiveXObject(prefixes[i] + ".XmlHttp");
return getXmlHttpPrefix.prefix = prefixes[i];
}
catch (ex) {
}
;
}
throw new Error("Could not find an installed XML parser");
}
function XmlDocument() {
}
XmlDocument.create = function () {
try {
if (document.implementation && document.implementation.createDocument) {
var doc = document.implementation.createDocument("", "", null);
if (doc.readyState == null) {
doc.readyState = 1;
doc.addEventListener("load", function () {
doc.readyState = 4;
if (typeof doc.onreadystatechange == "function")
doc.onreadystatechange();
}, false);
}
return doc;
}
if (window.ActiveXObject)
return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
}
catch (ex) {
}
throw new Error("Your browser does not support XmlDocument objects");
};
if (window.DOMParser &&
window.XMLSerializer &&
window.Node && Node.prototype && Node.prototype.__defineGetter__) {
Document.prototype.loadXML = function (s) {
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
while (this.hasChildNodes())
this.removeChild(this.lastChild);
for (var i = 0; i < doc2.childNodes.length; i++) {
this.appendChild(this.importNode(doc2.childNodes[i], true));
}
};
try {
Document.prototype.__defineGetter__("xml", function () {
return (new XMLSerializer()).serializeToString(this);
});
} catch(e) {
}
}
if (window.ActiveXObject && !window.XMLHttpRequest) {
window.XMLHttpRequest = function() {
var msxmls = new Array(
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < msxmls.length; i++) {
try {
return new ActiveXObject(msxmls[i]);
} catch (e) {
}
}
return null;
};
}
if (!window.ActiveXObject && window.XMLHttpRequest) {
window.ActiveXObject = function(type) {
switch (type.toLowerCase()) {
case 'microsoft.xmlhttp':
case 'msxml2.xmlhttp':
case 'msxml2.xmlhttp.3.0':
case 'msxml2.xmlhttp.4.0':
case 'msxml2.xmlhttp.5.0':
return new XMLHttpRequest();
}
return null;
};
}
function copyChildNodes(nodeFrom, nodeTo) {
if ((!nodeFrom) || (!nodeTo)) {
throw "Both source and destination nodes must be provided";
}
;
var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
var nodes = nodeFrom.childNodes;
if (ownerDoc.importNode) {
for (var i = 0; i < nodes.length; i++) {
nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
}
;
} else {
for (var i = 0; i < nodes.length; i++) {
nodeTo.appendChild(nodes[i].cloneNode(true));
}
}
}
GW.CMT = {
add: function(callback, commentObj) {
var req = GW.createRequest('cmt-insert-req');
GW.UTIL.addObject(req, 'comment', commentObj);
GW.request(req, GW.createCallback(callback, 'add'));
},
markRead: function(callback, commentId, targetId) {
var req = GW.createRequest('cmt-update-state-req');
GW.UTIL.setAttr(req, 'state', 2);
GW.UTIL.setOptAttr(req, 'id', commentId);
GW.UTIL.setOptAttr(req, 'target', targetId);
GW.request(req, GW.createCallback(callback, 'markRead'));
},
markReadForTarget: function(callback, targetId) {
GW.CMT.markRead(callback, null, targetId);
},
markReadForComment: function(callback, commentId) {
GW.CMT.markRead(callback, commentId, null);
},
del: function(callback, commentId) {
var req = GW.createRequest('cmt-delete-req');
GW.UTIL.setAttr(req, 'id', commentId);
GW.request(req, GW.createCallback(callback, 'del'));
},
delForTarget: function(callback, targetId) {
var req = GW.createRequest('cmt-delete-for-target-req');
GW.UTIL.setAttr(req, 'targetid', targetId);
GW.request(req, GW.createCallback(callback, 'delForTarget'));
}
}
GW.EVENT = {
FETCH_INTERVAL_MILLIS: 8000,
listener: null,
send: function(callback, topic, argObj) {
var req = GW.createRequest('event-send-req');
GW.UTIL.setAttr(req, 'topic', topic);
if (argObj) {
GW.UTIL.setAttrs(req, argObj);
}
GW.request(req, GW.createCallback(callback, 'send'));
},
subscribe: function(callback, topics) {
var req = GW.createRequest('event-subscribe-req');
GW.UTIL.setAttr(req, 'topics', topics);
GW.request(req, GW.createCallback(callback, 'subscribe'));
},
start: function(callback, aListener) {
GW.EVENT.listener = aListener;
var startRsp = function(xmlElm) {
GW.EVENT._fetchReq();
if (callback != null) {
GW.createCallback(callback, 'start').doRsp(xmlElm);
}
}
GW.request(GW.createRequest('event-start-req'), GW.createCallback(startRsp));
},
stop: function(callback) {
GW.EVENT.listener = null;
GW.request(GW.createRequest('event-stop-req'), GW.createCallback(callback, 'stop'));
},
unsubscribe: function(callback, topics) {
var req = GW.createRequest('event-unsubscribe-req');
if (topics) {
GW.UTIL.setAttr(req, 'topics', topics);
}
GW.request(req, GW.createCallback(callback, 'unsubscribe'));
},
_fetchReq: function() {
GW.request(GW.createRequest('event-fetch-req'), GW.createCallback(GW.EVENT, '_fetch'));
},
_fetchRsp: function(xmlElm) {
if (GW.EVENT.listener == null) {
return;
}
try {
var indicationElms = xmlElm.childNodes;
for (var i = 0; i < indicationElms.length; i++) {
GW.EVENT.listener.onIndication(indicationElms[i]);
}
} catch (e) {
throw e;
}
setTimeout(GW.EVENT._fetchReq, GW.EVENT.FETCH_INTERVAL_MILLIS);
},
_fetchNegRsp: function(errorId, errorStr, details, tagName) {
if (GW.EVENT.listener == null) {
return;
}
setTimeout(GW.EVENT._fetchReq, GW.EVENT.FETCH_INTERVAL_MILLIS);
}
}
GW.MEDIA = {
iframeCnt: 0,
callback: null,
getBaseURL: function() {
return GW.webRoot + '/media.srv';
},
addRef: function(callback, argObj) {
var req = GW.createRequest('medium-insert-req');
if (argObj.userid == -1) {
argObj.userId = undefined;
}
GW.UTIL.addObject(req, 'medium', argObj);
GW.request(req, GW.createCallback(callback, 'addRef'));
},
upload: function(callback, form) {
var rsp = document.createElement('input');
rsp.name = 'rsp';
rsp.type = 'hidden';
rsp.value = 'jsonjs';
form.appendChild(rsp);
var agentkey = document.createElement('input');
agentkey.name = 'agentkey';
agentkey.type = 'hidden';
agentkey.value = GW.agentKey;
form.appendChild(agentkey);
var iframeId = 'kwrspframe' + GW.MEDIA.iframeCnt;
form.target = iframeId;
if (!form.name.value) {
form.name.value = 'unnamed';
}
GW.MEDIA._createRspIFrame(iframeId);
form.submit();
GW.MEDIA.callback = callback;
GW.MEDIA.iframeCnt++;
return false;
},
del: function(callback, id) {
var req = GW.createRequest('medium-delete-req');
GW.UTIL.setAttr(req, 'id', id);
GW.request(req, GW.createCallback(callback, 'del'));
},
update: function(callback, id, name, desc) {
var req = GW.createRequest('medium-update-req');
GW.UTIL.setAttr(req, 'id', id);
var elm = req.createElement('medium');
GW.UTIL.addOptTextElement(elm, 'name', name);
GW.UTIL.addOptTextElement(elm, 'description', desc);
req.documentElement.appendChild(elm);
GW.request(req, GW.createCallback(callback, 'update'));
},
_serverRsp: function(jsonRsp) {
if (GW.MEDIA.callback != null) {
GW.MEDIA.callback(jsonRsp);
GW.MEDIA.callback = null;
}
},
_checkRspIFrame: function(callback, iframeId) {
var iframe = window.frames[iframeId];
if (!iframe) {
iframe = DH.getObject(iframeId);
if (!iframe) {
alert('cannot get rspFrame: ' + iframeId);
return;
}
}
var iframeDoc;
if (iframe.contentDocument) {
iframeDoc = iframe.contentDocument;
} else if (iframe.contentWindow) {
iframeDoc = iframe.contentWindow.document;
} else if (iframe.document) {
iframeDoc = iframe.document;
}
if (iframeDoc && iframeDoc.documentElement && iframeDoc.documentElement.tagName.indexOf('rsp') != -1) {
callback(iframeDoc.documentElement);
} else {
var f = function() {
GW.MEDIA._checkRspIFrame(callback, iframeId);
}
if (iframeDoc && iframeDoc.documentElement && iframeDoc.documentElement.innerHTML.indexOf('rsp') != -1) {
var id = iframeDoc.body.getElementsByTagName('B')[0].innerHTML;
var rsp = GW.createRequest('medium-insert-rsp');
rsp.documentElement.setAttribute('id', id);
callback(rsp.documentElement);
return;
}
setTimeout(f, 50);
}
},
_createRspIFrame: function(iframeId) {
var iframeDiv = document.createElement('DIV');
iframeDiv.style.visibility = 'hidden';
iframeDiv.style.position = 'absolute';
iframeDiv.style.top = '0px';
iframeDiv.style.left = '0px';
iframeDiv.style.width = '0px';
iframeDiv.style.height = '0px';
iframeDiv.innerHTML = '<iframe id="' + iframeId + '"  name="' + iframeId + '" style="width: 0px; height: 0px; border: 0px;"><\/iframe>';
document.body.appendChild(iframeDiv);
return true;
}
}
GW.TAG = {
add: function(callback, itemIds, tags) {
var req = GW.createRequest('tagging-tag-req');
GW.UTIL.setAttr(req, 'items', itemIds);
GW.UTIL.setAttr(req, 'tags', tags);
GW.UTIL.setAttr(req, 'mode', 'add');
GW.request(req, GW.createCallback(callback, 'add'));
},
replace: function(callback, itemIds, tags) {
var req = GW.createRequest('tagging-tag-req');
GW.UTIL.setAttr(req, 'items', itemIds);
GW.UTIL.setAttr(req, 'tags', tags);
GW.UTIL.setAttr(req, 'mode', 'replace');
GW.request(req, GW.createCallback(callback, 'replace'));
},
remove: function(callback, itemIds, tags) {
var req = GW.createRequest('tagging-untag-req');
GW.UTIL.setAttr(req, 'items', itemIds);
GW.UTIL.setAttr(req, 'tags', tags);
GW.request(req, GW.createCallback(callback, 'remove'));
}
}
GW.TRACE = {
addMediumToTrace: function(callback, mediumId, userId) {
var req = GW.createRequest('trace-add-medium-req');
GW.UTIL.setAttr(req, 'id', mediumId);
GW.UTIL.setOptAttr(req, 'userid', userId);
GW.request(req, GW.createCallback(callback, 'addMediumToTrace'));
},
create: function(callback, name) {
var req = GW.createRequest('trace-create-req');
GW.UTIL.setOptAttr(req, 'name', name);
GW.request(req, GW.createCallback(callback, 'create'));
},
get: function(callback, id, argObj) {
var req = GW.createRequest('trace-export-req');
GW.UTIL.setAttr(req, 'id', id);
if (argObj) {
GW.UTIL.setAttrs(req, argObj);
}
GW.request(req, GW.createCallback(callback, 'get'));
},
write: function(callback, lon, lat, time, ele) {
var req = GW.createRequest('trace-write-req');
var pt = req.createElement('pt');
GW.UTIL.setAttr(pt, 'lon', lon);
GW.UTIL.setAttr(pt, 'lat', lat);
GW.UTIL.setOptAttr(pt, 't', time);
GW.UTIL.setOptAttr(pt, 'ele', ele);
req.documentElement.appendChild(pt);
GW.request(req, GW.createCallback(callback, 'write'));
},
suspend: function(callback, id) {
var req = GW.createRequest('trace-suspend-req');
GW.UTIL.setOptAttr(req, 'id', id);
GW.request(req, GW.createCallback(callback, 'suspend'));
},
resume: function(callback, id) {
var req = GW.createRequest('trace-resume-req');
GW.UTIL.setOptAttr(req, 'id', id);
GW.request(req, GW.createCallback(callback, 'resume'));
},
del: function(callback, id) {
var req = GW.createRequest('trace-delete-req');
GW.UTIL.setAttr(req, 'id', id);
GW.request(req, GW.createCallback(callback, 'del'));
}
}
GW.QUERY = {
queryStore: function(aCmd, aCallback, theOtherArgs) {
var req = GW.createRequest('query-store-req');
var argv = GW.QUERY.queryStore.arguments;
var argc = arguments.length;
if (argc < 2) {
alert('get command must have at least 2 argv (cmd+callback)');
return;
}
GW.UTIL.setAttr(req, 'cmd', aCmd);
if (typeof theOtherArgs == 'object') {
for (var field in theOtherArgs) {
GW.UTIL.setAttr(req, field, theOtherArgs[field]);
}
} else {
for (var i = 2; i < argc; i++) {
GW.UTIL.setAttr(req, argv[i], argv[++i]);
}
}
if (aCallback != null) {
var qr = new GW.QUERY._queryRspHandler(aCallback);
GW.request(req, GW.createCallback(qr.onQueryRsp));
} else {
return GW.QUERY._rsp2XMLRecords(GW.request(req));
}
},
_rsp2XMLRecords: function(xmlElm) {
var records = [];
if (!xmlElm) {
return records;
}
var recordElements = xmlElm.getElementsByTagName('record');
for (var i = 0; i < recordElements.length; i++) {
records.push(new XMLRecord(recordElements[i]));
}
return records;
},
_queryRspHandler: function(cb) {
this.onQueryRsp = function(rsp) {
GW.createCallback(cb, 'queryStore').doRsp(GW.QUERY._rsp2XMLRecords(rsp));
}
}
}
GW.USER = {
create: function(callback, name, password, email, fullname, role) {
var req = GW.createRequest('user-create-req');
GW.UTIL.setAttr(req, 'name', name);
GW.UTIL.setAttr(req, 'password', password);
GW.UTIL.setAttr(req, 'email', email);
GW.UTIL.setAttr(req, 'fullname', fullname);
GW.UTIL.setOptAttr(req, 'role', role);
GW.request(req, GW.createCallback(callback, 'create'));
},
signup: function(callback, fullname, name, password, email, invite, profile, lang, newsletter) {
var req = GW.createRequest('user-signup-req');
GW.UTIL.setAttr(req, 'fullname', fullname);
GW.UTIL.setAttr(req, 'name', name);
GW.UTIL.setAttr(req, 'password', password);
GW.UTIL.setAttr(req, 'email', email);
GW.UTIL.setAttr(req, 'invite', invite);
GW.UTIL.setOptAttr(req, 'profile', profile);
GW.UTIL.setOptAttr(req, 'lang', lang);
GW.UTIL.setOptAttr(req, 'newsletter', newsletter);
GW.request(req, GW.createCallback(callback, 'signup'));
},
verify: function(callback, email, verify) {
var req = GW.createRequest('user-verify-req');
GW.UTIL.setAttr(req, 'email', email);
GW.UTIL.setAttr(req, 'verify', verify);
GW.request(req, GW.createCallback(callback, 'verify'));
},
getProfile: function(callback) {
var req = GW.createRequest('user-get-profile-req');
return GW.request(req, GW.createCallback(callback, 'getProfile'));
},
update: function(callback, id, name, password, email) {
var req = GW.createRequest('user-update-req');
GW.UTIL.setAttr(req, 'id', id);
GW.UTIL.setOptAttr(req, 'name', name);
GW.UTIL.setOptAttr(req, 'password', password);
GW.UTIL.setOptAttr(req, 'email', email);
GW.request(req, GW.createCallback(callback, 'update'));
},
updateProfile: function(callback, profileObj) {
var req = GW.createRequest('user-update-profile-req');
GW.UTIL.addObject(req, 'profile', profileObj);
return GW.request(req, GW.createCallback(callback, 'updateProfile'));
},
del: function(callback, id) {
var req = GW.createRequest('user-delete-req');
GW.UTIL.setAttr(req, 'id', id);
GW.request(req, GW.createCallback(callback, 'del'));
}
}
GW.UTIL = {
escape : function(s) {
return s.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
},
expandQueryString: function(qs, name, value) {
if (value && value != null) {
qs += ('&' + name + '=' + value);
}
return qs;
},
addArray: function(parent, name, arr) {
var doc = parent.ownerDocument;
if (parent.nodeName == '#document') {
doc = parent;
parent = doc.documentElement;
}
var arrElm = doc.createElement(name);
var elmName = name.substring(0, name.indexOf('list'));
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
if (typeof arr[i] == 'object') {
GW.UTIL.addObject(arrElm, elmName, arr[i]);
} else {
GW.UTIL.addTextElement(arrElm, elmName, arr[i]);
}
}
}
parent.appendChild(arrElm);
return arrElm;
},
addOptArray: function(parent, name, arr) {
if (arr && arr != null) {
return GW.UTIL.addArray(parent, name, arr);
}
},
addObject: function(parent, name, obj) {
var doc = parent.ownerDocument;
if (parent.nodeName == '#document') {
doc = parent;
parent = doc.documentElement;
}
var elm = doc.createElement(name);
var field, value, type;
for (field in obj) {
value = obj[field];
type = typeof value;
if (type == 'object' && value && value.constructor == (new Array).constructor) {
type = 'array';
}
if (value == undefined || value == null) {
GW.UTIL.addTextElement(elm, field, null);
continue;
}
switch (type) {
case 'object' :
GW.UTIL.addObject(elm, field, value);
break;
case 'array' :
GW.UTIL.addArray(elm, field, value);
break;
case 'boolean' :
GW.UTIL.addTextElement(elm, field, value ? 'true' : 'false');
break;
case 'number' :
case 'string' :
if (field == 'id' || (field == 'name' && parent.nodeName == 'mediumlist')) {
GW.UTIL.setAttr(elm, field, value);
} else {
GW.UTIL.addTextElement(elm, field, value);
}
break;
default:
break;
}
}
parent.appendChild(elm);
return elm;
},
addOptObject: function(parent, name, obj) {
if (obj && obj != null) {
return GW.UTIL.addObject(parent, name, obj);
}
},
addElement: function(parent, name) {
var doc = parent.ownerDocument;
if (parent.nodeName == '#document') {
doc = parent;
parent = doc.documentElement;
}
var elm = doc.createElement(name);
parent.appendChild(elm);
return elm;
},
addTextElement: function(parent, name, text) {
var elm = GW.UTIL.addElement(parent, name);
if (text != undefined && text != null) {
var doc = parent.ownerDocument;
if (parent.nodeName == '#document') {
doc = parent;
}
var textNode = doc.createTextNode(text);
elm.appendChild(textNode);
}
return elm;
},
addOptTextElement: function(parent, name, text) {
if (text != undefined && text != null) {
return GW.UTIL.addTextElement(parent, name, text);
}
},
addTextElements: function(node, obj) {
var name;
for (name in obj) {
GW.UTIL.addOptTextElement(node, name, obj[name]);
}
},
getChildText: function(parent, childName) {
function getElement(childName)
{
return parent.getElementsByTagName(childName)[0] || false;
}
if (getElement(childName) && getElement(childName).firstChild)
{
return getElement(childName).firstChild.nodeValue;
}
else
{
return false;
}
},
setAttrs: function(node, obj) {
var name;
for (name in obj) {
GW.UTIL.setOptAttr(node, name, obj[name]);
}
},
setAttr: function(node, name, value) {
if (node.nodeName == '#document') {
node = node.documentElement;
}
if (value == undefined || value == null) {
alert('error: no value passed for attr ' + name);
return;
}
if (typeof value == 'boolean') {
value = value ? 'true' : 'false';
}
node.setAttribute(name, value);
},
setOptAttr: function(node, name, value) {
if (value != undefined && value != null) {
GW.UTIL.setAttr(node, name, value);
}
}
}
function Record(anObj) {
this.getField = function(name) {
return null;
}
this.toHTML = function() {
return null;
}
}
function ObjRecord(anObj) {
Record.apply(this);
this.rec = anObj;
this.getField = function(name) {
return this.rec[name];
}
this.toHTML = function() {
var html = '<pre>';
var fieldCount = fields.length;
var nextField;
for (j  in this.recs) {
nextField = fields[j];
html += j + '=' + this.rec[j];
html += '\n';
}
html += '\n</pre>';
return html;
}
}
function XMLRecord(xmlElement) {
Record.apply(this);
this.xml = xmlElement;
this.id = -1;
if (this.xml.attributes && this.xml.getAttribute("id")) {
this.id = this.xml.getAttribute("id");
} else  if (this.getField("id") != null) {
this.id = this.getField("id");
}
this.getField = function(name) {
if (name == 'id' && this.id > 0) {
return this.id;
}
var field = this.getXMLField(name);
if (field != null && field.childNodes.length > 0) {
return field.childNodes[0].nodeValue;
} else {
return null;
}
}
this.getXMLField = function(name) {
var list = this.xml.getElementsByTagName(name);
if (list && list.length > 0) {
return list[0];
} else {
return null;
}
}
this.toHTML = function() {
var html = '<pre>';
var xml = this.xml;
html += (xml.tagName + ' id=' + this.id + '\n');
var fields = xml.childNodes;
var fieldCount = fields.length;
var nextField;
for (var j = 0; j < fieldCount; j++) {
nextField = fields[j];
html += (nextField.tagName + '=');
if (nextField.childNodes[0]) {
html += nextField.childNodes[0].nodeValue;
}
html += '\n';
}
html += '\n</pre>';
return html;
}
}
var CMT = {
commentPanel: null,
currentTarget: '0',
panelOpen: false,
commentList: 'empty',
addComment: function() {
var cmtForm = DH.getObject('commentform');
var commentObj = {target: CMT.currentTarget,
content: cmtForm.content.value,
author: cmtForm.name.value,
url: cmtForm.url.value,
email: cmtForm.email.value};
GW.CMT.add(CMT.addCommentRsp, commentObj);
return false;
},
addCommentRsp: function(aRspDoc) {
CMT.hideAddCommentForm();
if (aRspDoc != null) {
} else {
alert('NULL response');
}
CMT.displayComments();
},
displayComments: function() {
var cmtList = DH.getObject('commentlist');
if (cmtList) {
cmtList.innerHTML = 'loading comments...';
}
GW.QUERY.queryStore('q-by-example', CMT.displayCommentsRsp, {table: 'gw_comment', target: CMT.currentTarget});
},
displayCommentsRsp: function(records) {
var html = records.length + ' comments for ' + CMT.currentType + ' "' + CMT.currentName + '"<br/>';
var date;
var url;
for (var i = 0; i < records.length; i++) {
html += '<hr>'
html = html + '<p>From: ' + records[i].getField('author') + '<br/>';
time = new Number(records[i].getField('creationdate'));
date = new Date(time);
html = html + 'Date: ' + date.format("DDD D MMM YYYY HH:mm:ss") + '<br/>';
url = records[i].getField('url');
if (url != null) {
html = html + 'Website: <a href="' + url + '" target="_new">' + url + '</a></p>';
}
html = html + '<p><i>' + records[i].getField('content') + '</i></p>';
}
CMT.commentList = html;
CMT._waitForPanelLoaded();
},
isCommentPanelOpen: function() {
return CMT.panelOpen;
},
onPanelClose: function() {
CMT.panelOpen = false;
},
showCommentPanel: function(aTargetId, aTargetType, aTargetName) {
if (CMT.commentPanel == null) {
CMT.commentPanel = new Panel('commentpanel', '#000044', 'white', null, CMT.onPanelClose);
CMT.commentPanel.setDimension(500, 500);
CMT.commentPanel.setXY(50, 50);
}
CMT.currentTarget = aTargetId + '';
CMT.currentType = aTargetType;
CMT.currentName = aTargetName;
CMT.commentPanel.show();
CMT.commentPanel.loadContent('content/comment.html');
CMT.commentPanel.setTitle('Comments for ' + CMT.currentType + '[' + CMT.currentTarget + ']' );
CMT.displayComments();
CMT.panelOpen = true;
return false;
},
hideAddCommentForm: function() {
DH.getStyleObject('commentform').display = 'none';
DH.show('addcommentlink');
},
showAddCommentForm: function() {
DH.getStyleObject('commentform').display = 'block';
DH.hide('addcommentlink');
},
_waitForPanelLoaded: function(html) {
var cmtList = DH.getObject('commentlist');
if (cmtList) {
cmtList.innerHTML = CMT.commentList;
} else {
setTimeout("CMT._waitForPanelLoaded()", 75);
}
}
}
Date.MONTHS = [
'January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
];
Date.DAYS = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday'
];
Date.SUFFIXES = [
'st','nd','rd','th','th','th','th','th','th','th',
'th','th','th','th','th','th','th','th','th','th',
'st','nd','rd','th','th','th','th','th','th','th',
'st'
];
Date.prototype.format = function(mask) {
var formatted = ( mask != null ) ? mask : 'DD-MMM-YY';
var letters = 'DMYHdhmst'.split('');
var temp = new Array();
var count = 0;
var regexA;
var regexB = /\[(\d+)\]/;
var day = this.getDay();
var date = this.getDate();
var month = this.getMonth();
var year = this.getFullYear().toString();
var hours = this.getHours();
var minutes = this.getMinutes();
var seconds = this.getSeconds();
var formats = new Object();
formats[ 'D' ] = date;
formats[ 'd' ] = date + Date.SUFFIXES[ date - 1 ];
formats[ 'DD' ] = ( date < 10 ) ? '0' + date : date;
formats[ 'DDD' ] = Date.DAYS[ day ].substring(0, 3);
formats[ 'DDDD' ] = Date.DAYS[ day ];
formats[ 'M' ] = month + 1;
formats[ 'MM' ] = ( month + 1 < 10 ) ? '0' + ( month + 1 ) : month + 1;
formats[ 'MMM' ] = Date.MONTHS[ month ].substring(0, 3);
formats[ 'MMMM' ] = Date.MONTHS[ month ];
formats[ 'Y' ] = ( year.charAt(2) == '0' ) ? year.charAt(3) : year.substring(2, 4);
formats[ 'YY' ] = year.substring(2, 4);
formats[ 'YYYY' ] = year;
formats[ 'H' ] = hours;
formats[ 'HH' ] = ( hours < 10 ) ? '0' + hours : hours;
formats[ 'h' ] = ( hours > 12 || hours == 0 ) ? Math.abs(hours - 12) : hours;
formats[ 'hh' ] = ( formats[ 'h' ] < 10 ) ? '0' + formats[ 'h' ] : formats[ 'h' ];
formats[ 'm' ] = minutes;
formats[ 'mm' ] = ( minutes < 10 ) ? '0' + minutes : minutes;
formats[ 's' ] = seconds;
formats[ 'ss' ] = ( seconds < 10 ) ? '0' + seconds : seconds;
formats[ 't' ] = ( hours < 12 ) ?  'A' : 'P';
formats[ 'tt' ] = ( hours < 12 ) ?  'AM' : 'PM';
for (var i = 0; i < letters.length; i++) {
regexA = new RegExp('(' + letters[ i ] + '+)');
while (regexA.test(formatted)) {
temp[ count ] = RegExp.$1;
formatted = formatted.replace(RegExp.$1, '[' + count + ']');
count++;
}
}
while (regexB.test(formatted)) {
formatted = formatted.replace(regexB, formats[ temp[ RegExp.$1 ] ]);
}
return formatted;
}
var FEAT = {
current: null
}
function Feature(theId, name, desc, type, time, lon, lat) {
this.id = theId;
this.name = name;
this.type = type;
this.desc = desc;
if (!this.desc || this.desc == null || this.desc == 'null') {
this.desc = 'no description';
}
this.time = new Number(time);
this.tlabel = null;
this.iconId = 'featicon' + this.id;
this.previewId = 'feat' + this.id;
this.previewTileId = 'featurepreview';
this.bgColor = GTW.FEATURE_BG_COLOR;
this.fgColor = GTW.FEATURE_FG_COLOR;
if (lon && lat) {
this.gLatLng = new GLatLng(lat, lon);
}
this.userName = null;
this.record = null;
this.blink = function(cnt) {
DH.blink(this.iconId, cnt, 150);
}
this.blowUp = function(cnt) {
GMAP.map.showMapBlowup(this.getGLatLng());
}
this.display = function() {
FEAT.current = this;
if (this.record != null && this.record != -1) {
this._display();
return;
}
this._queryInfo();
}
this.getBGColor = function() {
return this.bgColor;
}
this.getDate = function() {
var date = new Date(this.time);
return date.format("DDD D MMM YYYY HH:mm:ss");
}
this.getGLatLng = function() {
return this.gLatLng;
}
this.getTitle = function() {
return this.name;
}
this.getPreviewTile = function() {
return DH.getObject(this.previewTileId);
}
this.remove = function() {
if (this.tlabel == null) {
return;
}
GMAP.map.removeTLabel(this.tlabel);
this.tlabel = null;
}
this.show = function() {
if (this.getGLatLng() == null) {
return;
}
var tl = new TLabel(true);
tl.id = 'tlab' + this.id;
tl.anchorLatLng = this.getGLatLng();
tl.anchorPoint = 'center';
tl.content = this.getIconDiv();
tl.setScaling(this.iconId, 16, 16, .2);
GMAP.map.addTLabel(tl);
this.tlabel = tl;
var self = this;
this.onMouseOverIcon = function (e) {
self.display();
DH.cancelEvent(e);
}
DH.addEvent(DH.getObject(this.iconId), 'mouseover', this.onMouseOverIcon, false);
}
this._display = function() {
if (FEAT.current != this && this.record != null && this.record != -1) {
return;
}
this._displayTitle();
this._displayInfo();
this._displayPreview();
this._displayDescr();
this._displayUser();
}
this._displayTitle = function() {
DH.setHTML('featuretitle', this.getTitle());
}
this._displayUser = function() {
this.userName = this.record.getField('user');
if (this.userName != null) {
DH.setHTML('tracerinfo', this.userName);
var tracer = GTW.getTracer(this.userName);
if (!tracer || tracer == null) {
tracer = GTW.createTracer(this.userName);
}
tracer.showInfo();
}
}
this._displayInfo = function() {
DH.setHTML('featureinfo', this.getDate() + ' <span class="cmtlink"><a href="#" onclick="CMT.showCommentPanel(' + this.id + ',\'' + this.type + '\',\'' + this.name + '\')" >comments (' + this.record.getField('comments') + ')</a></span>');
if (CMT.isCommentPanelOpen() == true) {
}
}
this._displayDescr = function() {
DH.setHTML('featuredesc', this.desc);
}
this._queryInfo = function() {
if (this.record == -1) {
return;
}
var self = this;
this.onGetRecord = function(result) {
self.record = -1;
if (result != null && result.length > 0) {
self.record = result[0];
}
self._display();
}
this.record = -1;
GW.QUERY.queryStore("q-medium-info", this.onGetRecord, {id: this.id});
}
}
function FeatureSet() {
this.features = [];
this.index = 0;
this.getFeature = function(index) {
if (this.features.length == 0 || index < 0 || index >= this.features.length) {
return null;
}
return this.features[index];
}
this.getFeatureById = function(id) {
for (var i = 0; i < this.features.length; i++) {
if (this.features[i].id == id) {
return this.features[i];
}
}
return undefined;
}
this.addMedia = function(records) {
for (var i = 0; i < records.length; i++) {
this.addMedium(records[i]);
}
}
this.addMedium = function(record) {
var medium = GTW.createMediumByRecord(record);
this.addFeature(medium);
}
this.addFeature = function(feature) {
this.features[this.features.length] = feature;
}
this.clear = function () {
for (var i = 0; i < this.features.length; i++) {
if (this.features[i]) {
this.features[i].remove();
}
}
}
this.dispose = function () {
for (var i = 0; i < this.features.length; i++) {
if (this.features[i]) {
this.features[i].remove();
delete this.features[i];
}
}
this.features = [];
}
this.getCurrent = function () {
return this.features[this.index];
}
this.show = function () {
for (var i = 0; i < this.features.length; i++) {
if (this.features[i]) {
this.features[i].show();
}
}
}
this.displayFirst = function(centerMap) {
this.index = 0;
return this._displayFeature(this.features[this.index], centerMap);
}
this.displayLast = function (centerMap) {
this.index = this.features.length - 1;
return this._displayFeature(this.features[this.index], centerMap);
}
this.displayNext = function (centerMap) {
if (++this.index >= this.features.length) {
this.index = 0;
}
return this._displayFeature(this.features[this.index], centerMap);
}
this.displayPrev = function (centerMap) {
if (--this.index <= 0) {
this.index = this.features.length - 1;
}
return this._displayFeature(this.features[this.index], centerMap);
}
this._displayFeature = function(feature, centerMap) {
if (feature) {
var blinks = 12;
if (centerMap && centerMap == true) {
GMAP.map.panTo(feature.getGLatLng());
blinks = 20;
}
feature.display();
feature.blink(blinks);
return feature;
}
}
}
function FeaturePlayer() {
this.featureSet = new FeatureSet();
this.controls = DH.getObject('featurecontrols');
var self = this;
this.onFirst = function(e) {
DH.cancelEvent(e);
self.featureSet.displayFirst(false);
}
this.onPrev = function(e) {
DH.cancelEvent(e);
self.featureSet.displayPrev(false);
}
this.onNext = function(e) {
DH.cancelEvent(e);
self.featureSet.displayNext(false);
}
this.onLast = function(e) {
DH.cancelEvent(e);
self.featureSet.displayLast(false);
}
DH.addEvent('featfirst', 'click', self.onFirst, false);
DH.addEvent('featprev', 'click', self.onPrev, false);
DH.addEvent('featnext', 'click', self.onNext, false);
DH.addEvent('featlast', 'click', self.onLast, false);
this.setFeatureSet = function (fc) {
this.featureSet = fc;
}
this.show = function() {
DH.show(this.controls);
}
this.hide = function() {
DH.hide(this.controls)
}
}
function Factory(theClassDefs) {
this.classDefs = [];
if (theClassDefs) {
this.classDefs = theClassDefs;
}
this.create = function(aName) {
var className = this.classDefs[aName];
if (!className) {
alert('cannot find real class name for ' + aName);
return null;
}
var obj = null;
if (arguments.length > 1) {
var argv = [];
var argStr = ' ';
for (var i = 1; i < arguments.length; i++) {
argv[i-1] = arguments[i];
argStr += 'argv[' + (i-1) + ']';
if (i < arguments.length - 1) {
argStr += ', ';
}
}
obj = eval('new ' + className + '(' + argStr + ')');
} else {
obj = eval('new ' + className + '()');
}
return obj;
}
this.getClassDef = function(aName) {
return this.classDefs[aName];
}
this.setClassDef = function(aName, aClassName) {
this.classDefs[aName] = aClassName;
}
}
var GTW = {
TRACE_COLOR: '#ff9900',
TRACER_ICON_URL: 'media/blueball.gif',
FEATURE_BG_COLOR: '#ff0000',
FEATURE_FG_COLOR: '#ffffff',
tracers: [],
followTracer: null,
featureSet:null,
tracePlayer: null,
featurePlayer: null,
traceAutoPlayer: null,
imageFullPanel: null,
polyLineWidth: 3,
polyLineOpacity: 0.80,
minTracePtDist: 12,
maxTracePt: 1000,
factory: null,
boot: function() {
GTW.factory = new Factory();
GTW.factory.setClassDef('Tracer', 'Tracer');
GTW.factory.setClassDef('Medium', 'Medium');
},
getFactory: function() {
return GTW.factory;
},
init: function() {
GTW.featureSet = new FeatureSet();
GTW.clearPanels();
},
clearFeatures: function() {
GTW.featureSet.dispose();
},
clearMap: function() {
GTW.clearTracers();
GTW.clearFeatures();
GTW.stopAutoPlay();
GTW.clearPanels();
},
clearFeaturePlayer: function() {
if (GTW.featurePlayer != null) {
GTW.featurePlayer.hide();
}
},
clearPanels: function() {
GTW.clearFeaturePlayer();
GTW.clearTracePlayer();
DH.setHTML('tracerinfo', ' ');
DH.setHTML('traceinfo', ' ');
DH.setHTML('traceview', 'trace info');
DH.setHTML('featuretitle', ' ');
DH.setHTML('featureinfo', ' ');
DH.setHTML('featurepreview', 'feature preview');
DH.setHTML('featuredesc', 'feature description (if avail)');
},
clearTracePlayer: function() {
if (GTW.tracePlayer != null) {
GTW.tracePlayer.hide();
}
},
clearTracers: function() {
var tracerName;
for (tracerName in GTW.tracers) {
var t = GTW.getTracer(tracerName);
t.clear();
t.hide();
}
},
createMedium: function(id, name, desc, type, mime, time, lon, lat) {
var medium = GTW.factory.create('Medium', id, name, desc, type, mime, time, lon, lat);
return medium;
},
createMediumByRecord: function(record) {
var medium = GTW.createMedium(record.getField('id'),
record.getField('name'),
record.getField('description'),
record.getField('kind'),
record.getField('mime'),
record.getField('creationdate'),
record.getField('lon'),
record.getField('lat'));
if (record.getField('user') != null) {
medium.userName = record.getField('user');
}
if (record.getField('owner') != null) {
medium.userId = record.getField('owner');
}
return medium;
},
createTracer: function(name, lon, lat, time) {
var tracer = GTW.getTracer(name);
if (tracer) {
if (lon && lat) {
tracer.setLocation(new GLatLng(lat, lon), time);
}
return tracer;
}
var point;
if (lon && lat) {
point = new GLatLng(lat, lon);
}
tracer = GTW.factory.create('Tracer', name, GTW.TRACE_COLOR, GTW.TRACER_ICON_URL, point, time);
tracer.init();
GTW.tracers[name] = tracer;
return tracer;
},
createTracerByRecord: function(record) {
var userName = record.getField('user');
if (userName == null) {
userName = record.getField('name');
}
var tracer = GTW.createTracer(userName,
record.getField('lon'), record.getField('lat'), record.getField('time'));
tracer.id = record.id;
if (record.getField('color') != null) {
tracer.color = record.getField('color');
}
return tracer;
},
displayMedia: function(records) {
GTW.featureSet.dispose();
GTW.featureSet.addMedia(records);
GTW.featureSet.show();
GTW.getFeaturePlayer().setFeatureSet(GTW.featureSet);
GTW.getFeaturePlayer().show()
GTW.featureSet.displayFirst();
},
displayTracePlayer: function() {
GTW.getTracePlayer().show();
},
formatDate: function(time) {
var date = new Date(time);
return date.format("DD-MM-YY");
},
formatTime: function(time) {
var date = new Date(time);
return date.format("HH:mm:ss");
},
formatDateAndTime: function(time) {
try {
var date = new Date(time);
return date.format("DD-MM-YY HH:mm:ss");
} catch(e) {
return 'date format error: t=' + time + ' e=' + e;
}
},
getImageFullPanel: function() {
if (GTW.imageFullPanel == null) {
GTW.imageFullPanel = new Panel('imagefullpanel', 'red', 'white');
GTW.imageFullPanel.setDimension(640, 510);
GTW.imageFullPanel.setXY(50, 50);
}
GTW.imageFullPanel.show();
return GTW.imageFullPanel;
},
getTracer: function(name) {
return GTW.tracers[name];
},
getTracePlayer: function() {
if (GTW.tracePlayer == null) {
GTW.tracePlayer = new TracePlayer();
}
return GTW.tracePlayer;
},
getFeaturePlayer: function() {
if (GTW.featurePlayer == null) {
GTW.featurePlayer = new FeaturePlayer();
}
return GTW.featurePlayer;
},
getTracers: function() {
return GTW.tracers;
},
startAutoPlay: function() {
GTW.stopAutoPlay();
GTW.traceAutoPlayer = new TraceAutoPlayer();
GTW.traceAutoPlayer.start();
},
stopAutoPlay: function() {
if (GTW.traceAutoPlayer != null) {
GTW.traceAutoPlayer.stop();
GTW.traceAutoPlayer = null;
}
},
showStatus: function(msg) {
DH.setHTML('status', msg);
}
}
function LiveListener(aStatusElm) {
this.statusElm = DH.getObject(aStatusElm);
this.clearStatus = function() {
DH.setHTML(this.statusElm, '&nbsp;');
}
this.showStatus = function(aTracer, aMsg) {
DH.setHTML(this.statusElm, aTracer.name + ' ' + aMsg);
DH.blink(this.statusElm, 4, 150);
}
this.onCommentAdd = function(event) {
}
this.onMove = function(tracer, event) {
tracer.setLive();
if (tracer.activeTrace == null) {
tracer.newTrace(event.getAttribute('traceid'), event.getAttribute('tracename'));
tracer.show();
}
tracer.move(event.getAttribute('lon'), event.getAttribute('lat'), event.getAttribute('t'));
this.showStatus(tracer, 'moves');
}
this.onHeartbeat = function(tracer, event) {
this.showStatus(tracer, 'sends heartbeat');
}
this.onMediumAdd = function(tracer, event) {
var medium = GTW.createMedium(event.getAttribute('id'),
event.getAttribute('name'),
'live upload by ' + tracer.name,
event.getAttribute('kind'),
event.getAttribute('mime'),
event.getAttribute('time'),
event.getAttribute('lon'),
event.getAttribute('lat'));
medium.userName = tracer.name;
tracer.addMedium(medium);
medium.show();
medium.blink(20);
medium.display();
this.showStatus(tracer, 'adds ' + event.getAttribute('kind'));
}
this.onTraceCreate = function(tracer, event) {
tracer.newTrace(event.getAttribute('id'), event.getAttribute('name'));
this.showStatus(tracer, 'creates trace ' + event.getAttribute('name'));
}
this.onTraceDelete = function(tracer, event) {
tracer.deleteTrace(event.getAttribute('id'), event.getAttribute('name'));
this.showStatus(tracer, 'deletes trace ' + event.getAttribute('name'));
}
this.onTraceSuspend = function(tracer, event) {
tracer.suspendTrace();
this.showStatus(tracer, 'suspends trace');
}
this.onTraceResume = function(tracer, event) {
tracer.resumeTrace();
this.showStatus(tracer, 'resumes trace');
}
this.onTraceResume = function(tracer, event) {
tracer.resumeTrace();
this.showStatus(tracer, 'resumes trace');
}
this.onIndication = function (event) {
var eventType = event.getAttribute('event');
var tracerName = event.getAttribute('username');
var tracer = GTW.getTracer(tracerName);
if (!tracer && eventType != 'comment-add') {
tracer = GTW.createTracer(tracerName, event.getAttribute('lon'), event.getAttribute('lat'), event.getAttribute('time'));
}
if (GTAPP.mode != 'live') {
this.showStatus(tracer, '<a href="#" onclick="GTAPP.mLive();return false">is live &lt;show it!&gt;</a>');
return;
}
if (eventType == 'user-move') {
this.onMove(tracer, event);
} else if (eventType == 'user-hb') {
this.onHeartbeat(tracer, event);
} else if (eventType == 'medium-add') {
this.onMediumAdd(tracer, event);
} else if (eventType == 'trace-create') {
this.onTraceCreate(tracer, event);
} else if (eventType == 'trace-delete') {
this.onTraceDelete(tracer, event);
} else if (eventType == 'trace-suspend') {
this.onTraceSuspend(tracer, event);
} else if (eventType == 'trace-resume') {
this.onTraceResume(tracer, event);
} else if (eventType == 'comment-add') {
this.onCommentAdd(event);
} else {
this.showStatus(tracer, 'unhandled event ' + eventType);
}
}
}
function Medium(id, name, desc, type, mime, time, lon, lat) {
Feature.apply(this, new Array(id, name, desc, type, time, lon, lat))
this.mime = mime;
this.url = 'media.srv?id=' + this.id;
this.init = function() {
}
this.getIconDiv = function() {
if (this.type == 'text') {
var src = 'media/poi.gif';
var img = '<img id="' + this.iconId + '" title="' + this.getTitle() + '" src="' + src + '" border="0"  alt="" />';
return '<div class="texticon" style="border: 1px solid ' + this.bgColor + ';" >' + img + '</div>';
} else {
return '<div class="medicon" id="' + this.iconId + '" style="background-color:' + this.getBGColor() + ';" >&nbsp;&nbsp;&nbsp;&nbsp;</div>';
}
}
this.getTitle = function() {
return this.name + ' [' + this.id + ']';
}
this._displayPreview = function() {
if (this.type == 'video') {
this._displayVideo();
} else if (this.type == 'image') {
this._displayImage();
} else if (this.type == 'audio') {
this._displayAudio();
} else if (this.type == 'text') {
this._displayText();
}
}
this.displayImageFull = function() {
var url = this.url + '&resize=640x480';
var panel = GTW.getImageFullPanel();
panel.setTitle(this.getTitle());
panel.setContent('<img title="' + this.getTitle() + '" src="' + url + '" border="0"  />');
}
this._displayAudio = function() {
var previewTile = this.getPreviewTile()
previewTile.innerHTML = '<img class="mediumpreview" id="' + this.previewId + '" title="click to play" src="media/audioicon.jpg" border="0"  />';
var medium = this;
this.onClick = function(e) {
DH.cancelEvent(e);
var url = medium.url;
content = '<embed src="' + medium.url + '"/>';
previewTile.innerHTML = content;
}
DH.addEvent(this.previewId, 'click', this.onClick, false);
}
this._displayImage = function() {
var src = this.url + '&resize=320x240';
var previewTile = this.getPreviewTile()
previewTile.innerHTML = '<img class="mediumpreview" id="' + this.previewId + '" title="click to see larger image" src="' + src + '" border="0"  />';
var medium = this;
this.onClick = function(e) {
DH.cancelEvent(e);
medium.displayImageFull();
}
DH.addEvent(this.previewId, 'click', this.onClick, false);
}
this._displayText = function() {
var src = this.url + '&resize=320x240';
var previewTile = this.getPreviewTile()
previewTile.innerHTML = 'getting text...';
var self = this;
this.onLoadText = function(text) {
self.getPreviewTile().innerHTML = text;
}
DH.getURL(this.url, this.onLoadText);
}
this._displayVideo = function() {
var previewTile = this.getPreviewTile()
this.url = GW.MEDIA.getBaseURL() + '%3Fid=' + this.id;
previewTile.innerHTML = '<p id="jwplayer"><a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.</p>';
var s1 = new SWFObject(DH.getBaseDir() + '/mediaplayer.swf',"single","288","216","7");
s1.addParam("allowfullscreen","true");
s1.addVariable("file", this.url + '%26format=flv');
s1.addVariable("image",this.url + '%26format=jpg');
s1.addVariable("type", "flv");
s1.addVariable("width","288");
s1.addVariable("height","216");
s1.write("jwplayer");
}
}
function Menu(anId) {
Widget.apply(this, new Array(anId));
this.replaceItem = function(id, name, fn, arg) {
var li = DH.getObject(id);
if (!li) {
return;
}
var a = li.getElementsByTagName('a')[0];
a.innerHTML = name;
if (fn) {
a.setAttribute('fn', fn);
if (arg) {
a.setAttribute('arg', arg);
}
}
}
this.replaceItemText = function(id, text) {
var li = DH.getObject(id);
if (!li) {
return;
}
var a = li.getElementsByTagName('a')[0];
a.innerHTML = text;
}
this.removeItem = function(id) {
var li = DH.getObject(id);
if (!li) {
return;
}
this._unbindLink(li.getElementsByTagName('a')[0]);
li.parentNode.removeChild(li);
delete li;
}
this._onSelect = function (e) {
var anchor = DH.getEventTarget(e);
DH.cancelEvent(e);
var fn = anchor.getAttribute('fn');
if (fn) {
var arg = anchor.getAttribute('arg');
if (!arg) {
eval(fn + '()');
} else {
eval(fn + '("' + arg + '")');
}
}
}
this._bindLink = function(link) {
var onSelect = this._onSelect;
DH.addEvent(link, 'click', onSelect, false);
}
this._unbindLink = function(link) {
var onSelect = this._onSelect;
DH.removeEvent(link, 'click', onSelect);
}
this._fixIE = function(li) {
li.onmouseover = function() {
this.className += " sfhover";
}
li.onmouseout = function() {
this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
}
}
var links = this.getContainer().getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
this._bindLink(links[i]);
}
if (DH.isIE == true) {
var sfEls = this.getContainer().getElementsByTagName("LI");
for (var i = 0; i < sfEls.length; i++) {
this._fixIE(sfEls[i]);
}
}
}
function Panel(id, bgColor, fgColor, onActivate, onClose) {
Widget.apply(this, new Array(id));
this.activate = function() {
this.setZ(Widget.curZ++);
this.show();
if (this.onActivate != null && DH.isVisible(this.getContainer()) == true) {
this.onActivate();
}
}
this.clear = function() {
if (this.content) {
}
this.content.innerHTML = ' ';
}
this.close = function() {
this.clear();
this.hide();
if (this.onClose != null) {
this.onClose();
}
}
this.hideFooter = function() {
DH.hide(this.footer);
DH.hide(this.resizer);
}
this.loadContent = function(url, onLoad) {
this.clear();
this.setContent('LOADING...');
var panel = this;
this.onLoadContent = function(cont) {
panel.setContent(cont);
if (onLoad) {
onLoad();
}
}
DH.getURL(url, this.onLoadContent);
}
this.setContent = function(cont) {
this.clear();
if (typeof cont == "string") {
this.content.innerHTML = cont;
} else {
this.content.appendChild(cont);
}
}
this.setTitle = function(title) {
this.header.innerHTML = title;
}
this.setBGColor = function(color) {
this.bgcolor = color;
DH.setBGColor(this.header, color);
DH.setBGColor(this.footer, color);
}
this.setFGColor = function(color) {
this.fgcolor = color;
DH.getStyleObject(this.header).color = color;
DH.getStyleObject(this.footer).color = color;
}
this.setDimension = function(w, h) {
DH.getStyleObject(this.getContainer()).width = w + 'px';
DH.getStyleObject(this.getContainer()).height = h + 'px';
this._fixIEScroll();
}
this._fixIEScroll = function() {
if (DH.isIE == true) {
var ch = DH.getObjectHeight(this.container) - DH.getObjectHeight(this.header) - DH.getObjectHeight(this.footer);
DH.getStyleObject(this.content).height = ch + 'px';
var cw = DH.getObjectWidth(this.container);
DH.getStyleObject(this.content).width = cw + 'px';
}
}
this.container = document.createElement('div');
var container = this.container;
container.className = 'pn-container';
container.id = container.className + id;
var header = document.createElement('div');
header.className = 'pn-header';
header.id = header.className + id;
var closer = document.createElement('div');
closer.className = 'pn-closer';
closer.id = closer.className + id;
var content = document.createElement('div');
content.className = 'pn-content';
content.id = content.className + id;
var footer = document.createElement('div');
footer.className = 'pn-footer';
footer.id = footer.className + id;
var resizer = document.createElement('div');
resizer.className = 'pn-resizer';
resizer.id = resizer.className + id;
container.appendChild(header);
container.appendChild(content);
container.appendChild(footer);
container.appendChild(resizer);
container.appendChild(closer);
document.body.appendChild(container);
this.header = header;
this.closer = closer;
this.resizer = resizer;
this.content = content;
this.footer = footer;
this.onActivate = null;
this.onClose = null;
if (onActivate) {
this.onActivate = onActivate;
}
if (onClose) {
this.onClose = onClose;
}
this.setXY((Math.round((Math.random() * 600) + 1)), 100 + (Math.round((Math.random() * 300) + 1)))
this.setContent('');
this.setBGColor(bgColor);
this.setFGColor(fgColor);
this.setTitle(id);
this._fixIEScroll();
var panel = this;
this.onCloserClick = function(e) {
panel.close();
DH.cancelEvent(e);
}
this.onDragStart = function(target, x, y) {
panel.activate();
}
this.onDrag = function(target, x, y, dx, dy) {
if (target.className == 'pn-header' || target.className == 'pn-footer') {
panel.setXY(panel.container.offsetLeft + dx, panel.container.offsetTop + dy);
} else if (target.className == 'pn-resizer') {
panel.setDimension(x - panel.container.offsetLeft, y - panel.container.offsetTop);
}
}
DH.addEvent(this.closer, 'click', this.onCloserClick, true);
DH.dragEnable(this.header, this.onDragStart, this.onDrag, null);
DH.dragEnable(this.resizer, this.onDragStart, this.onDrag, null);
DH.dragEnable(this.closer, this.onDragStart, this.onDrag, null);
DH.dragEnable(this.footer, this.onDragStart, this.onDrag, null);
}
function Selector(title, id, callback) {
Widget.apply(this, new Array(id));
this.addOption = function(name, label, value) {
var option = document.createElement('option');
option.id = this.getId() + 'o' + Widget.curOptionId++;
option.name = name;
option.value = value;
option.label = label;
var text = document.createTextNode(label);
option.appendChild(text)
this.select.appendChild(option);
}
this.clear = function() {
while (this.select.hasChildNodes() == true) {
this.select.removeChild(this.select.childNodes[0])
}
this.addOption('title', this.title, this.title);
}
this.remove = function() {
this.hide();
this.clear();
document.body.removeChild(this.form);
}
this.setCallback = function(fun) {
this.callback = fun;
}
this.callback = callback;
var form = document.createElement('form');
form.className = 'sel-form';
form.id = this.getId();
var select = document.createElement('select');
select.className = 'sel-select';
select.id = select.className + this.getId();
form.appendChild(select);
document.body.appendChild(form);
this.form = form;
this.select = select;
this.title = title;
this.addOption('title', this.title, this.title);
var selector = this;
this.onSelect = function(e) {
var option = selector.select.options[selector.select.selectedIndex];
if (selector.select.selectedIndex != 0) {
selector.callback(option.name, option.childNodes.item(0).nodeValue, option.value);
}
DH.cancelEvent(e);
}
DH.addEvent(this.select, 'change', selector.onSelect, false);
}
var TRACER = {
current: null,
BLINK_INTERVAL_SHOW: 250,
BLINK_INTERVAL_HIDE: 250,
MARKER_OFFSET_X: 5,
MARKER_OFFSET_Y: 5
}
function Tracer(name, color, iconURL, pt, time) {
this.record = null;
this.id = -1;
this.name = name;
this.color = color;
this.point = pt;
if (this.point && time) {
this.point.time = new Number(time);
}
this.iconURL = iconURL;
this.activeTrace = null;
this.tlabel = null;
this.hidden = false;
this.live = false;
this.full = false;
this.lastPoint = null;
this.thumbId = null;
this.thumbURL = 'media/default-user-thumb-4x3.jpg';
this.init = function() {
if (this.point) {
this.setLocation(this.point);
}
}
this.activate = function () {
if (this.activeTrace != null && GTW.tracePlayer != null) {
GTW.tracePlayer.setTrace(this.activeTrace);
}
this.panTo();
}
this.addMedium = function (medium) {
if (this.activeTrace != null) {
this.activeTrace.featureSet.addFeature(medium);
}
}
this.blink = function() {
DH.toggleVisibility(this.iconId);
this.blinkInterval = DH.isVisible(this.iconId) ? TRACER.BLINK_INTERVAL_SHOW : TRACER.BLINK_INTERVAL_HIDE;
var self = this;
setTimeout(function() {
self.blink();
}, this.blinkInterval);
}
this.clear = function () {
this.hide();
this.deleteTrace();
}
this.createTLabel = function () {
this.iconId = 'icon' + this.name;
var html = '<a href="#"><span class="tracer"><img id="' + this.iconId + '" src="' + this.iconURL + '" border="0" />&nbsp;<span class="tracername" >' + this.name + '</span></span></a>';
tl = new TLabel();
tl.glide = true;
tl.id = 'tlab' + this.name;
tl.anchorLatLng = this.point;
tl.anchorPoint = 'topLeft';
tl.content = html;
tl.markerOffset = new GSize(TRACER.MARKER_OFFSET_X, TRACER.MARKER_OFFSET_Y);
return tl;
}
this.getColor = function () {
if (this.record != null && this.record != -1) {
var userColor =  this.record.getField('color');
if (userColor != null) {
this.color  = userColor;
}
}
return this.color;
}
this.deleteTrace = function () {
if (this.activeTrace != null) {
this.activeTrace.remove();
}
this.activeTrace = null;
}
this.hasTrace = function () {
return this.activeTrace != null;
}
this.getActiveTrace = function () {
return this.activeTrace;
}
this.newTrace = function (id, name) {
this.deleteTrace(id, name);
this.activeTrace = new Trace(id, name, this);
}
this.readTrace = function (id, name, doDraw) {
var tracer = this;
this.onGetTraceRsp = function (rspElm) {
tracer.deleteTrace();
var trace = new Trace(id, name, tracer);
trace.setGTX(rspElm.getElementsByTagName('gtx')[0]);
if (doDraw == true) {
trace.draw();
}
tracer.showInfo();
var lastPoint = trace.getLastPoint();
if (lastPoint != null) {
tracer.setLocation(lastPoint, lastPoint.time, true);
}
tracer.activeTrace = trace;
if (GTW.tracePlayer != null) {
GTW.tracePlayer.setTrace(trace);
}
trace.showTitle();
trace.showInfo();
GTW.showStatus('trace drawn');
}
GTW.showStatus('drawing trace ' + name + '...');
var args = {format: 'gtx', attrs: 'lon,lat,t', media: 'true', mindist: GTW.minTracePtDist, maxpoints: GTW.maxTracePt};
GW.TRACE.get(this.onGetTraceRsp, id, args);
}
this.getLocation = function() {
return this.point;
}
this.setLocation = function(point, time, force) {
if (point == null) {
return;
}
this.lastPoint = this.point;
this.point = point;
if (time) {
this.point.time = new Number(time);
}
if (this.tlabel == null) {
this.tlabel = this.createTLabel();
GMAP.map.addTLabel(this.tlabel);
var self = this;
this.onClick = function(e) {
DH.cancelEvent(e);
self.showInfo();
self.popupInfoWindow();
}
DH.addEvent(this.tlabel.elm, 'click', this.onClick, false);
} else {
if (force) {
this.tlabel.forceToLatLng(this.point);
} else {
this.tlabel.moveToLatLng(this.point);
}
}
}
this.move = function(lon, lat, time) {
pt = new GLatLng(lat, lon);
if (time) {
pt.time = new Number(time);
}
this.setLocation(pt);
if (this.activeTrace != null) {
this.activeTrace.addLivePoint(pt);
}
this.showLiveInfo();
}
this.show = function() {
if (this.tlabel != null) {
DH.show(this.tlabel.id);
}
this.showInfo();
this.hidden = false;
}
this.hide = function() {
if (this.tlabel != null) {
DH.hide(this.tlabel.id);
}
this.hidden = true;
}
this.isLive = function() {
return this.live;
}
this.resumeTrace = function() {
}
this.popupInfoWindow = function() {
var html = '<h3>' + this.name + '</h3>';
html += 'Was here on ' + GTW.formatDateAndTime(this.point.time) + '<br/>at ' + this.point.lng() + ', ' + this.point.lat();
GMAP.map.openInfoWindowHtml(this.point, html);
}
this.setLive = function() {
if (this.live == true) {
return;
}
this.live = true;
this.blink();
}
this.showLiveInfo = function() {
this.showInfo();
var speed = 'unknown';
if (this.point != null && this.lastPoint != null) {
speed = GMAP.speed(this.lastPoint, this.point);
speed = speed.toFixed(2) + ' km/h';
}
DH.setHTML('traceview', GTW.formatDateAndTime(this.point.time) + ' <br/>' + speed);
}
this.showInfo = function() {
DH.setHTML('tracerid', this.name);
if (!DH.getObject("tracerimg").src) {
DH.getObject("tracerimg").src = this.thumbURL;
}
DH.setHTML('tracerdesc', '&nbsp;');
TRACER.current = this;
if (this.record != null && this.record != -1) {
this._showInfo();
return;
}
this._queryInfo();
}
this.suspendTrace = function() {
}
this.isVisible = function() {
return this.hidden == false;
}
this.panTo = function () {
if (this.point != null) {
GMAP.map.setCenter(this.point, GMAP.map.getZoom());
}
}
this._showInfo = function() {
if (TRACER.current != this && this.record != null && this.record != -1) {
return;
}
DH.getObject("tracerimg").src = this.thumbURL;
var desc = this.record.getField('desc');
if (desc == null) {
desc = ' ';
}
var tracePoints = this.record.getField('tracepoints');
if (tracePoints == null) {
tracePoints = 0;
}
var tracesDist = this.record.getField('tracesdist');
if (tracesDist == null) {
tracesDist = 0;
}
var stats =  tracesDist + ' km&nbsp;&nbsp;&nbsp;' + tracePoints + ' points';
DH.setHTML('tracerdesc', '<i>' + desc + '</i><br/>' + stats + '<br/><span class="cmtlink"><a title="Show list of traces from ' + this.name + '" href="#" onclick="GTAPP.mUserTraces(\'' + this.name + '\')" >traces (' + this.record.getField('traces') + ')</a>&nbsp;&nbsp;<a title="Show all media (photos etc) from this user" href="#" onclick="GTAPP.mShowMediaByUser(\'' + this.name + '\')" >media (' + this.record.getField('media') + ')</a>&nbsp;&nbsp;<a href="#" title="Show user\'s messages or send message to this user" onclick="CMT.showCommentPanel(' + this.id + ',\'user\',\'' + this.name + '\')" >msgs (' + this.record.getField('comments') + ')</a>&nbsp;&nbsp;</span>');
if (CMT.isCommentPanelOpen() == true) {
}
}
this._queryInfo = function() {
if (this.record == -1) {
return;
}
var self = this;
this.onGetRecord = function(result) {
self.record = -1;
if (result != null && result.length > 0) {
self.record = result[0];
self.id = self.record.getField("id");
self.thumbId = self.record.getField("iconid");
if (self.thumbId != null) {
self.thumbURL = 'media.srv?id=' + self.thumbId + "&resize=80x60!";
}
}
self._showInfo();
}
this.record = -1;
GW.QUERY.queryStore("q-user-info", this.onGetRecord, {user: this.name});
}
}
function Trace(id, name, tracer) {
this.id = id;
this.name = name;
this.startDate = 0;
this.endDate = 0;
this.tracer = tracer;
this.segments = [];
this.featureSet = new FeatureSet();
this.polyLines = [];
this.color = tracer.getColor();
this.addPoint = function (aPoint) {
if (this.segments.length == 0) {
this.segments[0] = [];
}
this.segments[this.segments.length - 1].push(aPoint);
}
this.addLivePoint = function (aPoint) {
var lastPoint = this.getLastPoint();
this.addPoint(aPoint);
if (lastPoint != null) {
this.clearPolyLines();
for (var i = 0; i < this.segments.length; i++) {
this.drawPoints(this.segments[i]);
}
}
}
this.addMedium = function (medium) {
this.featureSet.addFeature(medium);
medium.show();
}
this.clear = function () {
this.clearPolyLines();
this.featureSet.clear();
}
this.clearPolyLines = function () {
for (var i = 0; i < this.polyLines.length; i++) {
GMAP.map.removeOverlay(this.polyLines[i]);
}
this.polyLines = [];
}
this.draw = function () {
var bounds;
for (var i = 0; i < this.segments.length; i++) {
this.drawPoints(this.segments[i]);
}
for (var i = 0; i < this.polyLines.length; i++) {
if (i == 0) {
bounds = this.polyLines[i].getBounds();
} else {
var nextBounds = this.polyLines[i].getBounds();
bounds.extend(nextBounds.getSouthWest());
bounds.extend(nextBounds.getNorthEast());
}
}
if (bounds) {
var zoom = GMAP.map.getBoundsZoomLevel(bounds);
GMAP.map.setCenter(bounds.getCenter(), zoom);
}
GTW.getFeaturePlayer().setFeatureSet(this.featureSet);
this.featureSet.show();
this.featureSet.displayFirst();
}
this.drawPoints = function (ptArr) {
if (ptArr.length > 200) {
this.drawPoints(ptArr.slice(0, 200));
this.drawPoints(ptArr.slice(200));
return;
}
var pl = new GPolyline(ptArr, this.color, GTW.polyLineWidth, GTW.polyLineOpacity);
GMAP.map.addOverlay(pl);
this.polyLines.push(pl);
}
this.getLastPoint = function () {
var segment = this.getSegment(this.segments.length - 1);
if (segment == null) {
return null;
}
return this.getPoint(this.segments.length - 1, segment.length - 1);
}
this.getPoint = function (segIndex, ptIndex) {
var segment = this.getSegment(segIndex);
if (segment == null) {
return null;
}
if (segment.length == 0 || ptIndex < 0 || ptIndex >= segment.length) {
return null;
}
return segment[ptIndex];
}
this.getSegment = function (segIndex) {
if (this.segments.length <= 0 || segIndex < 0 || segIndex >= this.segments.length) {
return null;
}
return this.segments[segIndex];
}
this.getTracer = function() {
return this.tracer;
}
this.remove = function () {
this.clear();
this.polyLines = [];
this.segments = [];
this.featureSet.clear();
DH.setHTML('tracetitle', '&nbsp;');
DH.setHTML('traceview', 'trace info');
}
this.setGTX = function (gtx) {
if (gtx.documentElement) {
gtx = gtx.documentElement;
}
var infoElm = gtx.getElementsByTagName('info')[0];
if (infoElm) {
this.name = infoElm.getAttribute('name');
this.startDate = new Number(infoElm.getAttribute('startdate'));
this.endDate = new Number(infoElm.getAttribute('enddate'));
}
var segElms = gtx.getElementsByTagName('seg');
this.segments = [];
if (segElms) {
this.distance = 0;
for (i = 0; i < segElms.length; i++) {
var ptElements = segElms[i].getElementsByTagName('pt');
if (!ptElements || ptElements.length == 0) {
continue;
}
var ptArr = [];
var nextPt;
for (j = 0; j < ptElements.length; j++) {
nextPt = new GLatLng(ptElements[j].getAttribute('lat'), ptElements[j].getAttribute('lon'));
nextPt.time = new Number(ptElements[j].getAttribute('t'));
nextPt.distance = 0;
nextPt.speed = 0;
if (j > 0) {
nextPt.distance = GMAP.distance(ptArr[j - 1], nextPt);
nextPt.speed = nextPt.distance / ((nextPt.time - ptArr[j - 1].time) / 3600000);
this.distance += nextPt.distance;
}
ptArr.push(nextPt);
}
this.segments.push(ptArr);
}
}
var mediumElements = gtx.getElementsByTagName('medium');
this.media = [];
if (mediumElements) {
var nextMedium;
var nextDesc = 'no description';
for (i = 0; i < mediumElements.length; i++) {
nextMedium = mediumElements[i];
if (nextMedium.childNodes[0]) {
nextDesc = nextMedium.childNodes[0].nodeValue;
}
medium = GTW.createMedium(nextMedium.getAttribute('id'),
nextMedium.getAttribute('name'),
nextDesc,
nextMedium.getAttribute('kind'),
nextMedium.getAttribute('mime'),
nextMedium.getAttribute('time'),
nextMedium.getAttribute('lon'),
nextMedium.getAttribute('lat'));
medium.userName = this.tracer.name;
this.featureSet.addFeature(medium);
}
}
}
this.showInfo = function() {
DH.setHTML('traceview', 'start: ' + GTW.formatDateAndTime(this.startDate) + '<br/>end: ' + GTW.formatDateAndTime(this.endDate) + '<br/>distance: ' + this.distance.toFixed(2) + ' km'
+ '<br/><span class="cmtlink"><a title="Show or make comments on this trace" href="#" onclick="CMT.showCommentPanel(' + this.id + ',\'trace\',\'' + this.name + '\')" >[comments]</a>&nbsp;&nbsp;<a target="_new" title="A direct link to this trace. Use right-mouse to copy." href="index.html?cmd=showtrace&id=' + this.id + '&user=' + this.tracer.name +'">[link]</a>&nbsp;&nbsp;<a title="A link to the GPX file for this trace. Use right-mouse to copy link." target="_new" href="proto.srv?gw_cmd=trace-export-req&format=gpx&mindist=20&id=' + this.id + '">[gpx]</a></span>');
if (CMT.isCommentPanelOpen() == true) {
CMT.showCommentPanel(this.id, 'trace', this.name);
}
}
this.showTitle = function() {
DH.setHTML('traceinfo', this.name + ' [' + this.id + ']');
}
this.showTitle();
}
function TraceAutoPlayer() {
this.INTERVAL_MILLIS = 2000;
this.intervalId = null;
this.tracer = null;
this.lastTracer = null;
this.state = 'IDLE';
this.n = 0;
this.start = function() {
this.stop();
var self = this;
this.intervalId = setInterval(function() {
self._doWork()
}, this.INTERVAL_MILLIS);
}
this.stop = function() {
if (this.intervalId == null) {
return;
}
clearInterval(this.intervalId);
this.intervalId = null;
}
this._doWork = function() {
if (this.intervalId == null) {
return;
}
if (this.state == 'IDLE') {
if (this.tracer != null) {
this.lastTracer = this.tracer;
this.tracer = null;
}
this.state = 'READING';
this._getRandomTrace();
} else if (this.state == 'READING') {
GTW.showStatus('reading next trace... ' + (this.n++));
if (this.tracer != null && this.tracer.getActiveTrace() != null) {
this.state = 'READY';
}
} else if (this.state == 'READY') {
GTW.showStatus('ready');
var trace = this.tracer.getActiveTrace();
var tracePlayer = GTW.getTracePlayer();
this.tracer.show();
tracePlayer.setTrace(trace);
tracePlayer.hide();
tracePlayer.play();
this.state = 'PLAYING';
} else if (this.state == 'PLAYING') {
var tracePlayer = GTW.getTracePlayer();
if (tracePlayer.isPlaying() == false) {
this.state = 'IDLE';
} else if (this.tracer.getActiveTrace() != null) {
GTW.showStatus('playing ' + this.tracer.name + '/' + this.tracer.getActiveTrace().name);
}
}
}
this._getRandomTrace = function() {
var player = this;
this.onQueryTraceRsp = function (records) {
GTW.showStatus('read ' + records[0].getField('name'));
player.tracer = GTW.createTracerByRecord(records[0]);
player.tracer.readTrace(records[0].getField('id'), records[0].getField('name'), false);
if (player.lastTracer != null) {
player.lastTracer.clear();
player.lastTracer = null;
}
}
GW.QUERY.queryStore('q-random-trace', this.onQueryTraceRsp);
}
}
function TracePlayer() {
this.trace = null;
this.active = false;
this.playing = false;
this.intervalId = null;
this.segIndex = 0;
this.pointIndex = 0;
this.featureIndex = 0;
this.nextFeature = null;
this.playPoints = [];
this.FEATURE_DISPLAY_TIME = 2000;
this.POINT_INTERVAL_TIME = 100;
this.featureShowing = false;
this.controls = DH.getObject('tracecontrols')
var self = this;
this.onPlayPause = function(e) {
DH.cancelEvent(e);
if (self.isActive() == false) {
self.play();
return;
}
if (self.isPlaying()) {
self.pause();
} else {
self.resume();
}
}
this.onStop = function(e) {
DH.cancelEvent(e);
self.stop();
if (self.trace != null) {
self.trace.draw();
}
}
this.onNext = function(e) {
DH.cancelEvent(e);
self.next();
}
this.onPrev = function(e) {
DH.cancelEvent(e);
self.prev();
}
DH.addEvent('traceplaypause', 'click', this.onPlayPause, true);
DH.addEvent('tracestop', 'click', this.onStop, true);
DH.addEvent('tracenext', 'click', this.onNext, true);
DH.addEvent('traceprev', 'click', this.onPrev, true);
this.hide = function() {
DH.hide(this.controls);
GTW.getFeaturePlayer().hide();
}
this.isActive = function() {
return this.active;
}
this.isPlaying = function() {
return this.active == true && this.playing == true;
}
this.next = function() {
if (this.isPlaying() == true) {
return;
}
if (this.isActive() == false) {
this._initPlay();
}
this._playNext();
}
this.prev = function() {
this.showInfo('not yet implemented');
}
this.showInfo = function(msg) {
DH.setHTML('traceview', msg);
}
this.showTraceInfo = function() {
this.showInfo('start: ' + GTW.formatDateAndTime(this.trace.startDate) + '<br/>end: ' + GTW.formatDateAndTime(this.trace.endDate) + '<br/>distance: ' + this.trace.distance.toFixed(2) + ' km');
}
this.pause = function() {
this.playing = false;
if (this.playPoints.length > 0) {
this.trace.drawPoints(this.playPoints);
var lastPt = this.playPoints[this.playPoints.length - 1]
this.playPoints = [];
this.playPoints.push(lastPt);
}
this.showInfo('paused');
this._stopLoop();
}
this.play = function() {
if (this.isActive() == false) {
this._initPlay();
}
this.playing = true;
this.showInfo('playing');
this._startLoop(this.POINT_INTERVAL_TIME);
}
this.resume = function() {
GTW.showStatus('playing resumed');
this.playing = true;
var player = this;
this._startLoop(this.POINT_INTERVAL_TIME);
}
this.show = function() {
DH.show(this.controls);
GTW.getFeaturePlayer().show();
}
this.stop = function() {
this.pause();
this.active = false;
this.intervalId = null;
this.segIndex = 0;
this.pointIndex = 0;
this.curPoint = null;
this.featureIndex = 0;
this.nextFeature = null;
this.playPoints = [];
this.trace.showInfo();
}
this.setTrace = function(trace) {
if (this.trace == trace) {
return;
}
if (this.isActive() == true) {
this.stop();
}
this.trace = trace;
GTW.getFeaturePlayer().setFeatureSet(trace.featureSet);
this.trace.showInfo();
}
this._initPlay = function() {
if (this.trace == null) {
return;
}
this.trace.clear();
this.segIndex = 0;
this.pointIndex = 0;
this.featureIndex = 0;
this.distance = 0;
this.nextFeature = this.trace.featureSet.getFeature(this.featureIndex++);
this.curPoint = this.trace.getPoint(0, this.pointIndex++);
if (this.curPoint == null) {
return;
}
GMAP.map.panTo(this.curPoint);
this.active = true;
}
this._startLoop = function(interval) {
this._stopLoop();
var player = this;
this.intervalId = setInterval(function() {
player._playNext()
}, interval);
}
this._stopLoop = function() {
if (this.intervalId == null) {
return;
}
clearInterval(this.intervalId);
this.intervalId = null;
}
this._playNext = function() {
try {
if (this.isPlaying() == true && this.featureShowing == true) {
this.featureShowing == false;
this._startLoop(this.POINT_INTERVAL_TIME);
}
var segment = this.trace.getSegment(this.segIndex);
if (this.curPoint != null) {
if (!GMAP.map.getBounds().contains(this.curPoint)) {
GMAP.map.panTo(this.curPoint);
if (this.isPlaying() == true) {
this.featureShowing = true;
this._startLoop(this.FEATURE_DISPLAY_TIME);
}
}
var endOfSeg = this.pointIndex >= segment.length - 1;
var endOfTrace = endOfSeg && (this.segIndex >= this.trace.segments.length - 1);
if (this.nextFeature != null && (this.curPoint.time >= this.nextFeature.time || endOfTrace == true)) {
this._playFeature(this.nextFeature);
this.nextFeature = this.trace.featureSet.getFeature(this.featureIndex++);
return;
}
this.trace.getTracer().setLocation(this.curPoint, this.curPoint.time, true);
this.playPoints.push(this.curPoint);
this.distance += this.curPoint.distance;
if (this.playPoints.length % 5 == 0 || this.isPlaying() == false) {
this.showInfo(GTW.formatDateAndTime(this.curPoint.time) + ' - ' + this.distance.toFixed(2) + ' km - ' + this.curPoint.speed.toFixed(2) + ' km/h');
}
if (this.playPoints.length % 5 == 0 || endOfSeg == true) {
this.trace.drawPoints(this.playPoints);
this.playPoints = [];
if (endOfSeg == false) {
this.playPoints.push(this.curPoint);
}
}
}
if (segment != null && ++this.pointIndex >= segment.length) {
this.playPoints = [];
this.showInfo('end of segment');
this.pointIndex = 0;
++this.segIndex;
}
if (this.segIndex >= this.trace.segments.length && this.nextFeature == null) {
this.stop();
} else {
this.curPoint = this.trace.getPoint(this.segIndex, this.pointIndex);
}
} catch(e) {
this.stop();
this.showInfo('traceplay canceled');
}
}
this._playFeature = function(feature) {
feature.show();
feature.blink(6);
feature.display();
this.featureShowing = true;
if (this.isPlaying() == true) {
this._startLoop(this.FEATURE_DISPLAY_TIME);
}
}
}
Widget.curZ = 10000;
Widget.curOptionId = 1;
function BBox(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.toString = function() {
return 'x=' + this.x + ' y=' + this.y + ' w=' + this.w + ' h=' + this.h;
}
}
function Widget(id) {
this.container = null;
this.id = id;
this.getContainer = function() {
if (this.container == null) {
this.container = DH.getObject(this.id);
}
return this.container;
}
this.getBBox = function() {
var cont = this.getContainer();
return new BBox(DH.getObjectX(cont), DH.getObjectY(cont), DH.getObjectWidth(cont), DH.getObjectHeight(cont));
}
this.hide = function() {
DH.hide(this.getContainer());
}
this.getId = function() {
return this.id;
}
this.isVisible = function() {
DH.isVisible(this.getContainer());
}
this.setOpacity = function(o) {
DH.setOpacity(this.getContainer(), o);
}
this.setXY = function(x, y) {
DH.shiftTo(this.getContainer(), x, y);
}
this.setWidth = function(w) {
DH.getStyleObject(this.getContainer()).width = w;
}
this.setZ = function(z) {
DH.setZIndex(this.getContainer(), z);
}
this.show = function() {
DH.show(this.getContainer());
}
}
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
var MYAPP = {
WINDOW_TITLE: 'GeoTracing - TraceLand',
DOC_TITLE: 'TraceLand',
WEBROOT: '/tland',
init: function() {
GTAPP.createMap = MYAPP.createMap;
MYAPP.TRACES_OVERLAY_ROOT = '/tile/tland';
MYAPP.TRACES_OVERLAY_NAME = 'Trace Map';
},
start: function() {
if (DH.getPageParameter('cmd', null) == null) {
GTAPP.mShowMediaInBbox(90);
}
},
createMap: function() {
GTAPP.blinkStatus('Creating map...');
GMAP.addMapType('map', G_NORMAL_MAP);
GMAP.addMapType('satellite', G_SATELLITE_MAP);
GMAP.addMapType('terrain', G_PHYSICAL_MAP);
GMAP.addMapType('hybrid', G_HYBRID_MAP);
GMAP.addTileMap({id: 'OSM', baseURL: "http://tile.openstreetmap.org", imageType: 'png'});
var WMS_URL_GREY = 'media/greysquare.jpg?';
var G_MAP_GREY = createWMSSpec(WMS_URL_GREY, "Blank", "Blank", "bl", "bla", "image/jpeg", "1.1.1");
GMAP.addMapType('blanc', G_MAP_GREY);
GMAP.createGMap('map');
GMAP.map.addControl(new GMapTypeControl());
GMAP.map.addControl(new GOverviewMapControl());
GMAP.map.addControl(new GLargeMapControl());
GMAP.map.addControl(new GScaleControl());
GMAP.map.enableContinuousZoom();
GMAP.map.enableDoubleClickZoom();
GMAP.setDefaultMapParms(new GLatLng(52.312183, 4.852850), 5, 'satellite');
GMAP.showMap();
GTAPP.showTracesOverlay();
GTAPP.showStatus('Map created');
}
}
var GTAPP = {
statusId: null,
mode: 'none',
mediaSelectFun: null,
defaultMode: 'live',
menu: null,
userSelector: null,
traceSelector: null,
SIG: '<a title="Powered by GeoTracing" href="http://www.geotracing.com" target="_new"><img src="media/powered-gt.png" border="0" onload="DH.fixPNG(this)" /></a>',
initialized: false,
liveListener: null,
busyIcon: null,
overlayListener: null,
pointQueryInProgress: false,
init: function() {
if (GTAPP.initialized == true) {
return;
}
DH.init();
GTAPP.addBusyIndicator();
GTAPP.busyOn();
GTW.boot();
MYAPP.init();
document.title = 'Please set MYAPP.WINDOW_TITLE to appear here';
if (MYAPP.WINDOW_TITLE) {
document.title = MYAPP.WINDOW_TITLE;
}
if (DH.getObject('title')) {
DH.setHTML('title', MYAPP.DOC_TITLE);
}
DH.hide(DH.getObject('help'));
GTAPP.showStatus('Initializing...');
GTAPP.createMap();
GTAPP.addSig();
GTW.init();
GTAPP.createMenu();
GTAPP.showStatus('init OK');
GMAP.resize();
DH.addEvent(window, 'resize', GMAP.resize, false);
GW.init(GTAPP.onError, 5, MYAPP.WEBROOT);
GTAPP.startEventListener();
GTAPP.doPageCommand();
GTAPP.initialized = true;
if (MYAPP.start) {
MYAPP.start();
}
GTAPP.busyOff();
GEvent.addListener(GMAP.map, "moveend", GTAPP.bboxChange);
},
startEventListener: function() {
GTAPP.createLiveListener();
GW.EVENT.start(GTAPP.onResponse, GTAPP.liveListener);
},
addSig: function() {
var id = 'gtsig';
if (!DH.getObject(id)) {
var b = document.createElement('div');
b.id = id;
b.style.position = 'absolute';
b.style.left = '30%';
b.style.bottom = '5px';
if (DH.getObject('bottom_interface') != null) {
b.style.bottom = (DH.getObjectHeight('bottom_interface') + 5) + 'px';
}
b.style.zIndex = 25600;
b.innerHTML = GTAPP.SIG;
document.body.appendChild(b);
}
},
addBusyIndicator: function() {
var id = 'busyicon';
if (!DH.getObject(id)) {
var b = document.createElement('img');
b.id = id;
b.style.position = 'absolute';
b.style.left = '30%';
b.style.top = '40%';
b.style.zIndex = 30000;
b.src = "media/loading.gif";
document.body.appendChild(b);
GTAPP.busyIcon = DH.getObject(id);
DH.hide(GTAPP.busyIcon);
DH._xhrBusy = GTAPP.busyOn;
DH._xhrReady = GTAPP.busyOff;
}
},
bboxChange: function() {
if (GTAPP.mode != 'media') {
return;
}
if (GTAPP.mediaSelectFun != null) {
GTAPP.mediaSelectFun(GTAPP.mediaSelectArg);
}
},
createLiveListener: function() {
GTAPP.liveListener = new LiveListener('livestatus');
},
createMap: function() {
alert('createMap needs to be defined in your app');
},
createMenu: function() {
DH.setHTML('menucontainer', DH.getURL('mainmenu.html'));
GTAPP.menu = new Menu('mainmenu');
},
doPageCommand: function() {
var cmd = DH.getPageParameter('cmd', null);
if (cmd == null) {
return;
}
if (cmd == 'showtrace') {
var id = DH.getPageParameter('id', null);
var tracerName = DH.getPageParameter('user', null);
if (id == null || tracerName == null) {
alert('need trace id (id) and user name (user)');
return;
}
GTAPP.showStatus('Drawing trace for user ' + tracerName);
GTAPP.onTraceSelect(id, null, tracerName);
GTW.displayTracePlayer();
GTAPP.showStatus('Trace drawn for user ' + tracerName);
return true;
} else if (cmd == 'autoplay') {
if (GTAPP.menu != null) {
GTAPP.menu.hide();
}
GTAPP.mAutoPlay();
} else if (cmd == 'live') {
var tracerName = DH.getPageParameter('user', null);
if (tracerName != null) {
GTW.followTracer = tracerName;
}
GTAPP.mLive();
} else if (cmd == 'archive') {
var tracerName = DH.getPageParameter('user', null);
if (tracerName != null) {
GTAPP.onUserSelect(null, tracerName);
}
} else {
return false;
}
},
onResponse: function(xmlElm) {
switch (xmlElm.tagName) {
case 'event-start-rsp':
GW.EVENT.subscribe(GW.onResponse, '/gt');
break;
case 'event-subscribe-rsp':
break;
default:
GTAPP.showStatus(xmlElm.tagName + ' rcvd');
break;
}
},
onError: function(id, error, details) {
alert('error response: ' + error + ' details: ' + details);
},
onQueryActiveUsers: function(records) {
GTAPP.showStatus(records.length + ' active users');
GTAPP.userSelector = new Selector('Follow User', 'usersel', GTAPP.onActiveUserSelect);
GTAPP.userSelector.hide();
for (i = 0; i < records.length; i++) {
traceId = records[i].getField('id');
traceName = records[i].getField('name');
tracerName = records[i].getField('user');
GTAPP.userSelector.addOption(traceId, tracerName + ' - ' + traceName, tracerName);
tracer = GTW.createTracerByRecord(records[i]);
if (GTW.followTracer != null && GTW.followTracer == tracerName) {
GTAPP.showStatus('following ' + tracerName + '...');
GTAPP.onActiveUserSelect(traceId, traceName, tracerName);
GTW.followTracer = null;
}
}
GTAPP.mode = 'live';
GTAPP.showMode();
var bbox = GTAPP.menu.getBBox();
GTAPP.userSelector.setXY((bbox.x + bbox.w + 40), bbox.y);
GTAPP.userSelector.show();
GTAPP.showStatus('Live Mode - ' + records.length + ' users');
},
onQueryTraces: function (records) {
GTAPP.traceSelector = new Selector('Select a Trace', 'tracesel', GTAPP.onTraceSelect);
GTAPP.traceSelector.hide();
var traceId, traceName, tracerName;
for (var i = 0; i < records.length; i++) {
traceId = records[i].getField('id');
traceName = records[i].getField('name');
tracerName = records[i].getField('user');
GTAPP.traceSelector.addOption(traceId, tracerName + ' - ' + traceName, tracerName);
}
var bbox = GTAPP.menu.getBBox();
GTAPP.traceSelector.setXY((bbox.x + bbox.w + 40), bbox.y);
GTAPP.traceSelector.show();
GTAPP.showStatus('Archive Mode - ' + records.length + ' traces');
},
onQueryAllUsers: function (records) {
GTAPP.showStatus('Got ' + records.length + ' users');
GTAPP.userSelector = new Selector('Select a User', 'usersel', GTAPP.onUserSelect);
GTAPP.userSelector.hide();
var userId, userName;
for (var i = 0; i < records.length; i++) {
userId = records[i].getField('id');
userName = records[i].getField('name');
GTAPP.userSelector.addOption(userId, userName, userName);
}
GTAPP.userSelector.setWidth(10);
var bbox = GTAPP.menu.getBBox();
GTAPP.userSelector.setXY((bbox.x + bbox.w + 40), bbox.y);
GTAPP.userSelector.show();
GTAPP.showStatus('Archive Mode - ' + records.length + ' users');
},
onQueryUserTraces: function (records) {
GTAPP.traceSelector = new Selector('Select a Trace', 'tracesel', GTAPP.onTraceSelect);
GTAPP.traceSelector.hide();
var traceId, traceName, userName;
for (var i = 0; i < records.length; i++) {
traceId = records[i].getField('id');
traceName = records[i].getField('name');
userName = records[i].getField('user');
GTAPP.traceSelector.addOption(traceId, traceName, userName);
}
var bbox = null;
if (GTAPP.userSelector && GTAPP.userSelector != null) {
bbox = GTAPP.userSelector.getBBox();
GTAPP.traceSelector.setXY((bbox.x + bbox.w + 40), bbox.y);
} else {
bbox = GTAPP.menu.getBBox();
GTAPP.traceSelector.setXY((bbox.x + bbox.w + 40), bbox.y);
}
GTAPP.traceSelector.show();
GTAPP.showStatus('Archive - user has ' + records.length + ' traces');
},
onQueryMedia: function (records) {
GTAPP.showStatus('Found ' + records.length + ' media, displaying...');
GTW.displayMedia(records);
GTAPP.showStatus('Displaying ' + records.length + ' media');
},
onQueryTracePoints: function (records) {
GTAPP.pointQueryInProgress = false;
if (records.length == 0) {
return;
}
var date = new Date(new Number(records[0].getField('time')));
var myHtml = '<p>GPS trace point by ' + records[0].getField('username') + ' <br/>on ' + date.format("DDD D MMM YYYY HH:mm:ss") + '</p>';
myHtml += '<p><a href="javascript:GTAPP.onTracePointTraceSelect(' + records[0].getField('traceid') + ',\'gps\',\'' + records[0].getField('username') + '\')">Show the GPS trace.</a></p>';
var latlng = new GLatLng(records[0].getField('lat'), records[0].getField('lon'));
GMAP.map.openInfoWindowHtml(latlng, myHtml);
},
onTracePointTraceSelect: function(traceId, traceName, tracerName) {
GTAPP.mode = 'traces';
GTAPP.showMode();
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.onTraceSelect(traceId, traceName, tracerName);
},
clearMap: function () {
GTW.clearMap();
},
hideStatus: function() {
DH.hide('status');
if (GTAPP.statusId != null) {
clearInterval(GTAPP.statusId);
GTAPP.statusId = null;
}
},
blinkStatus: function(txt) {
GTAPP.hideStatus();
DH.setHTML('status', txt);
GTAPP.statusId = setInterval(function() {
DH.toggleVisibility('status')
}, 400);
},
showMode: function() {
DH.setHTML('mode', GTAPP.mode);
},
showStatus: function(txt) {
GTAPP.hideStatus();
DH.setHTML('status', txt);
DH.show('status');
},
_deleteSelectors: function() {
if (GTAPP.traceSelector != null) {
GTAPP.traceSelector.remove();
GTAPP.traceSelector = null;
}
if (GTAPP.userSelector != null) {
GTAPP.userSelector.remove();
GTAPP.userSelector = null;
}
},
onShowTrace: function(traceId, traceName, tracerName) {
GTAPP.mode = 'archive';
GTAPP.showMode();
GTAPP.onTraceSelect(traceId, traceName, tracerName);
},
onTraceSelect: function(traceId, traceName, tracerName) {
GTAPP.clearMap();
GTW.displayTracePlayer();
var tracer = GTW.createTracer(tracerName);
tracer.readTrace(traceId, traceName, true);
tracer.show();
},
onActiveUserSelect: function(traceId, traceName, tracerName) {
var tracer = GTW.getTracer(tracerName);
if (!tracer) {
GTAPP.showStatus('no tracer for ' + tracerName);
return;
}
GTW.displayTracePlayer();
tracer.panTo();
tracer.readTrace(traceId, traceName, true);
tracer.show();
},
onUserSelect: function(userId, loginName) {
if (GTAPP.traceSelector && GTAPP.traceSelector != null) {
GTAPP.traceSelector.remove();
GTAPP.traceSelector = null;
}
var tracer = GTW.createTracer(loginName);
tracer.showInfo();
GTAPP.blinkStatus('Getting traces for ' + loginName + "...");
GW.QUERY.queryStore('q-traces-by-user', GTAPP.onQueryUserTraces, {user: loginName});
},
mAutoPlay: function() {
if (GTAPP.mode == 'autoplay') {
return;
}
GTAPP.showStatus('autoplay');
GTAPP.mode = 'autoplay';
GTAPP.showMode();
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTW.startAutoPlay();
},
mArchive: function() {
if (GTAPP.mode == 'archive') {
return;
}
GTAPP.mode = 'archive';
GTAPP.showMode();
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting all users...');
GW.QUERY.queryStore('q-all-users', GTAPP.onQueryAllUsers);
},
mLive: function(e) {
GTAPP.showMode();
if (GTAPP.mode == 'live') {
return;
}
GTAPP.liveListener.clearStatus();
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting active users...');
GW.QUERY.queryStore('q-active-traces', GTAPP.onQueryActiveUsers);
},
mLastTraces: function(max) {
GTAPP.mode = 'traces';
GTAPP.showMode();
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting last ' + max + ' traces...');
GW.QUERY.queryStore('q-recent-traces', GTAPP.onQueryTraces, {max: max});
},
mUserTraces: function(loginName) {
GTAPP.mode = 'traces';
GTAPP.showMode();
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting traces for ' + loginName + "...");
GW.QUERY.queryStore('q-traces-by-user', GTAPP.onQueryUserTraces, {user: loginName});
},
mAllTraces: function() {
GTAPP.mode = 'traces';
GTAPP.showMode();
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting all traces...');
GW.QUERY.queryStore('q-all-traces', GTAPP.onQueryTraces);
},
mMy: function() {
window.open('my', 'MyGeoTracing');
},
mWebTracer: function() {
window.open('webtracer', 'WebTracer');
},
mHideMedia: function() {
GTAPP.mode = 'media';
GTAPP.showMode();
GTAPP.mediaSelectFun = null;
GTAPP.mediaSelectArg = 0;
GTAPP.clearMap();
GTAPP._deleteSelectors();
},
mShowMedia: function(max) {
GTAPP.mode = 'media';
GTAPP.showMode();
GTAPP.mediaSelectFun = GTAPP.mShowMedia;
GTAPP.mediaSelectArg = max;
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting random media...');
GW.QUERY.queryStore('q-locative-media', GTAPP.onQueryMedia, {random: true, max: max});
},
mShowRecentMedia: function(max) {
GTAPP.mode = 'media';
GTAPP.showMode();
GTAPP.mediaSelectFun = GTAPP.mShowRecentMedia;
GTAPP.mediaSelectArg = max;
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting last ' + max + ' media...');
GW.QUERY.queryStore('q-recent-media', GTAPP.onQueryMedia, {max: max});
},
mShowRecentMediaInBbox: function(max) {
GTAPP.mode = 'media';
GTAPP.showMode();
GTAPP.mediaSelectFun = GTAPP.mShowRecentMediaInBbox;
GTAPP.mediaSelectArg = max;
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting last ' + max + ' media in area...');
var bounds = GMAP.map.getBounds();
var bbox = bounds.getSouthWest().x + ',' + bounds.getSouthWest().y + ',' + bounds.getNorthEast().x + ',' + bounds.getNorthEast().y;
GW.QUERY.queryStore('q-recent-media', GTAPP.onQueryMedia, {max: max, bbox: bbox});
},
mShowMediaByUser: function(user) {
GTAPP.mode = 'media';
GTAPP.showMode();
GTAPP.mediaSelectFun = null;
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting media for ' + user + '...');
GW.QUERY.queryStore('q-media-by-user', GTAPP.onQueryMedia, {user: user});
},
mShowMediaInBbox: function(max) {
GTAPP.mode = 'media';
GTAPP.showMode();
GTAPP.mediaSelectFun = GTAPP.mShowMediaInBbox;
GTAPP.mediaSelectArg = max;
GTAPP.clearMap();
GTAPP._deleteSelectors();
GTAPP.blinkStatus('Getting random media in area...');
var bounds = GMAP.map.getBounds();
var bbox = bounds.getSouthWest().x + ',' + bounds.getSouthWest().y + ',' + bounds.getNorthEast().x + ',' + bounds.getNorthEast().y;
GW.QUERY.queryStore('q-locative-media', GTAPP.onQueryMedia, {random: true, max: max, bbox: bbox});
},
mShowHelp: function(url) {
var helpPanel = new Panel('INFO', '#000044', 'white');
helpPanel.setXY(100, 100);
helpPanel.setDimension(600, 500);
helpPanel.loadContent(url);
},
mSetMap: function(type) {
GMAP.setMapType(type);
},
busyOn: function() {
if (GTAPP.busyIcon) {
DH.show(GTAPP.busyIcon);
}
},
busyOff: function() {
if (GTAPP.busyIcon) {
DH.hide(GTAPP.busyIcon);
}
},
hideTracesOverlay: function() {
GMAP.map.removeOverlay(GTAPP.tracesOverlay);
GTAPP.tracesOverlay = undefined;
GEvent.removeListener(GTAPP.overlayListener);
},
showTracesOverlay: function() {
var tracesLayer = new GTileLayer(new GCopyrightCollection(), 8, 18);
tracesLayer.getTileUrl = function(tile, zoom) {
return GMAP.makeTileCachePath(MYAPP.TRACES_OVERLAY_ROOT + '/all', zoom, tile.x, tile.y, ".png?t=" + new Date().getTime());
};
tracesLayer.isPng = function() {
return true;
}
tracesLayer.getOpacity = function() {
return 1.0;
}
GTAPP.tracesOverlay = new GTileLayerOverlay(tracesLayer);
GMAP.map.addOverlay(GTAPP.tracesOverlay);
GTAPP.overlayListener = GEvent.addListener(GMAP.map, "click", function(overlay, latlng) {
if (latlng && GTAPP.pointQueryInProgress == false) {
GTAPP.pointQueryInProgress = true;
var clickP = GMAP.map.fromLatLngToContainerPixel(latlng);
var p1 = GMAP.map.fromContainerPixelToLatLng(clickP);
var p2 = GMAP.map.fromContainerPixelToLatLng(new GPoint(clickP.x+3,clickP.y+4));
var radius = Math.round(p1.distanceFrom(p2));
GW.QUERY.queryStore('q-trace-points', GTAPP.onQueryTracePoints, {lon: latlng.lng(), lat: latlng.lat(), max: 1, radius: radius});
}
});
},
toggleTracesOverlay: function() {
if (GTAPP.tracesOverlay) {
GTAPP.menu.replaceItemText('menutracestoggle', 'Show ' + MYAPP.TRACES_OVERLAY_NAME);
GTAPP.hideTracesOverlay();
} else {
GTAPP.menu.replaceItemText('menutracestoggle', 'Hide ' + MYAPP.TRACES_OVERLAY_NAME);
GTAPP.showTracesOverlay();
}
}
}
DH.addEvent(window, 'load', GTAPP.init, false);
var diffpos = function(x, y) {
this.x = x;
this.y = y;
}
var diffusions = new Array(new diffpos(-5, -5), new diffpos(0, -5), new diffpos(5, -5), new diffpos(-5, 0), new diffpos(0, 0), new diffpos(5, 0), new diffpos(-5, 5), new diffpos(0, 5), new diffpos(5, 5), new diffpos(10, 5));
var TLABEL = {
SMOOTH_FACTOR: .050,
ANIMATE_INTERVAL: 150,
DEBUG: false,
G_MAP_PANE: undefined
}
function TLabel(diffuse) {
this.diffuse = false;
this.elm = null;
this.glide = false;
if (diffuse) {
this.diffuse = diffuse;
}
if (!TLABEL.G_MAP_PANE) {
TLABEL.G_MAP_PANE = G_MAP_MARKER_PANE;
GMap2.prototype.addTLabel = function(a) {
a.initialize(this);
}
GMap2.prototype.removeTLabel = function(a) {
this.getPane(TLABEL.G_MAP_PANE).removeChild(a.elm);
delete(b);
}
}
}
TLabel.prototype.debug = function(s) {
if (TLABEL.DEBUG == true) {
GLog.write(s);
}
}
TLabel.prototype.initialize = function(a) {
if (typeof(a.TLabelBugged == 'undefined')) {
this.addTBug(a);
}
this.map = a;
var b = document.createElement('span');
b.setAttribute('id', this.id);
b.innerHTML = this.content;
if (navigator.userAgent.toLowerCase().indexOf('safari') != -1) {
document.body.appendChild(b);
}
b.style.position = 'absolute';
b.style.zIndex = 25000;
if (this.percentOpacity) {
this.setOpacity(this.percentOpacity);
}
this.elm = b;
this.w = this.elm.offsetWidth;
this.h = this.elm.offsetHeight;
this.mapTray = this.map.getPane(TLABEL.G_MAP_PANE);
this.mapTray.appendChild(b);
if (!this.markerOffset) {
this.markerOffset = new GSize(0, 0);
}
this.moveToXY();
GEvent.bind(a, "moveend", this, this.forceToXY);
}
TLabel.prototype.forceToLatLng = function(aGLatLng) {
this.anchorLatLng = aGLatLng;
this.forceToXY();
}
TLabel.prototype.moveToLatLng = function(aGLatLng) {
this.anchorLatLng = aGLatLng;
this.moveToXY();
}
TLabel.prototype.forceToXY = function() {
this.getXY();
if (this.glide == true) {
this.x = this.targetX;
this.y = this.targetY;
}
this.moveElm();
}
TLabel.prototype.moveToXY = function() {
this.getXY();
if (this.glide == true) {
this.animate();
} else {
this.moveElm();
}
}
TLabel.prototype.moveElm = function() {
this.elm.style.left = this.x + 'px';
this.elm.style.top = this.y + 'px';
}
TLabel.prototype.getXY = function(a, b) {
var xy = this.map.fromLatLngToDivPixel(this.anchorLatLng)
var x = parseInt(xy.x);
var y = parseInt(xy.y);
with (Math) {
switch (this.anchorPoint) {
case 'topLeft':break;
case 'topCenter':x -= floor(this.w / 2);break;
case 'topRight':x -= this.w;break;
case 'midRight':x -= this.w;y -= floor(this.h / 2);break;
case 'bottomRight':x -= this.w;y -= this.h;break;
case 'bottomCenter':x -= floor(this.w / 2);y -= this.h;break;
case 'bottomLeft':y -= this.h;break;
case 'midLeft':y -= floor(this.h / 2);break;
case 'center':x -= floor(this.w / 2);y -= floor(this.h / 2);break;
default:break;
}
}
if (this.scaleElmId) {
var zoom = this.map.getZoom();
if (this.lastZoom && (zoom == this.lastZoom)) {
}
this.lastZoom = zoom;
var scale = Math.pow(3, (zoom / 8)) / 12;
scale = Math.max(this.minScaleFactor, scale);
var sw = Math.round(scale * this.maxW);
var sh = Math.round(scale * this.maxH);
var icon = document.getElementById(this.scaleElmId);
if (!icon) {
return;
}
icon.style.width = sw + 'px';
icon.style.height = sh + 'px';
this.markerOffset.width = sw / 2;
this.markerOffset.height = sh / 2;
}
if (this.diffuse == true) {
x = x - this.markerOffset.width + diffusions[Math.floor(Math.random() * 10)].x;
y = y - this.markerOffset.height + diffusions[Math.floor(Math.random() * 10)].y;
} else {
x = x - this.markerOffset.width;
y = y - this.markerOffset.height;
}
if (this.glide == true) {
this.targetX = x;
this.targetY = y;
if (!this.x) {
this.x = x;
this.y = y;
}
} else {
this.x = x;
this.y = y;
}
xy.x = x;
xy.y = y;
return xy;
}
TLabel.prototype.setScaling = function(aScaleElmId, aMaxW, aMaxH, aMinScaleFactor) {
this.scaleElmId = aScaleElmId;
this.maxW = aMaxW;
this.maxH = aMaxH;
this.minScaleFactor = .3;
if (aMinScaleFactor) {
this.minScaleFactor = aMinScaleFactor;
}
}
TLabel.prototype.animate = function(show) {
var obj = this;
this.debug('animate enter');
if (!this.animating || this.animating == null) {
this.debug('start animation');
this.animating = window.setInterval(function() {
obj.glideElm()
}, TLABEL.ANIMATE_INTERVAL);
}
}
TLabel.prototype.glideElm = function() {
var diffX = Math.abs(this.targetX - this.x);
var diffY = Math.abs(this.targetY - this.y);
if (diffX <= 1 && diffY <= 1) {
if (this.animating) {
this.debug('stop animation');
window.clearTimeout(this.animating);
this.animating = null;
}
this.moveElm();
return;
}
var deltaX = TLABEL.SMOOTH_FACTOR * (this.targetX - this.x);
var deltaY = TLABEL.SMOOTH_FACTOR * (this.targetY - this.y);
if (Math.abs(deltaX) <= 1 && Math.abs(deltaY) <= 1) {
deltaX = deltaX < 0 ? -1.0 : 1.0;
deltaY = deltaY < 0 ? -1.0 : 1.0;
}
this.x = this.x + deltaX;
this.y = this.y + deltaY;
this.x = Math.round(this.x);
this.y = Math.round(this.y);
this.moveElm();
}
TLabel.prototype.setOpacity = function(b) {
if (b < 0) {
b = 0;
}
if (b > 100) {
b = 100;
}
var c = b / 100;
var d = this.elm;
if (typeof(d.style.filter) == 'string') {
d.style.filter = 'alpha(opacity:' + b + ')';
}
if (typeof(d.style.KHTMLOpacity) == 'string') {
d.style.KHTMLOpacity = c;
}
if (typeof(d.style.MozOpacity) == 'string') {
d.style.MozOpacity = c;
}
if (typeof(d.style.opacity) == 'string') {
d.style.opacity = c;
}
}
TLabel.prototype.addTBug = function(a) {
if (typeof(a.TLabelBugged) == 'undefined') {
var b = document.createElement('div');
b.id = 'TLabelBug';
b.style.position = 'absolute';
b.style.right = '0px';
if (a.TBugged > 0) {
b.style.bottom = '32px';
} else {
b.style.bottom = '20px';
}
b.style.backgroundColor = '#f2efe9';
b.style.zIndex = 25500;
b.innerHTML = '<a href="http://gmaps.tommangan.us/tlabel.html" style="font:10px verdana;text-decoration:none;margin:0px;padding:2px;color:#000;">Made with TLabel</a>';
document.getElementById(a.getContainer().id).appendChild(b);
var c = 0.7;
var d = document.getElementById(b.id);
if (typeof(d.style.filter) == 'string') {
d.style.filter = 'alpha(opacity:' + c * 100 + ')';
}
if (typeof(d.style.KHTMLOpacity) == 'string') {
d.style.KHTMLOpacity = c;
}
if (typeof(d.style.MozOpacity) == 'string') {
d.style.MozOpacity = c;
}
if (typeof(d.style.opacity) == 'string') {
d.style.opacity = c;
}
a.TLabelBugged = 1;
}
}
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;