
 //<![CDATA[

var url = document.URL;
if (url.substring(url.lastIndexOf("\/")+1,url.lastIndexOf("\.")) != 'volgauto') {
	var zoomoffset = 0;
	var Height = document.documentElement.clientHeight;
	var Width = document.documentElement.clientWidth;
	if (BrowserDetect.browser != 'Explorer') {
		zoomoffset = -1;
		Height = window.innerHeight-0;
		Width = window.innerWidth-0;
	/**
		if (browser == "opera") {
			var Height = document.body.clientHeight;
			var Width = document.body.clientWidth;
		}
	**/
	}

	if (Height) document.getElementById('map').style.height = (Height)+'px';
	if (Width) document.getElementById('map').style.width = (Width)+'px';
}


var defaultIcon = new GIcon();

// End

var startIcon = new GIcon();
startIcon.image = "http://www.google.com/mapfiles/dd-start.png";
startIcon.iconSize = new GSize(20, 34);
startIcon.iconAnchor = new GPoint(9, 34);
startIcon.infoWindowAnchor = new GPoint(9, 2);

var endIcon = new GIcon(startIcon);
endIcon.image = "http://www.google.com/mapfiles/dd-end.png";

// Specially for the Solar Boat Team:
// Start
var labelIcon = new GIcon();
labelIcon.image = "images/solarboat.png";
labelIcon.shadow = "images/solarboat_shadow.png";
labelIcon.iconSize = new GSize(80, 28);
labelIcon.shadowSize = new GSize(80, 28);
labelIcon.iconAnchor = new GPoint(40, 20);
labelIcon.infoWindowAnchor = new GPoint(40, 8);
labelIcon.infoShadowAnchor = new GPoint(0, 28);

var techcarIcon = new GIcon();
techcarIcon.image = "images/techcar.png";
techcarIcon.iconSize = new GSize(48, 30);
techcarIcon.iconAnchor = new GPoint(24, 15);
techcarIcon.infoWindowAnchor = new GPoint(48, 0);

// Start icon: http://www.google.com/mapfiles/dd-start.png
// End icon  : http://www.google.com/mapfiles/dd-end.png


// Set the vars for the normal points/markers
var i 					= 0;
// j is used for showLoadingText();
var j 					= 0;
var tooltiptext		= ""; 

// Set the vars for the background points/markers
var xmlmarkers 			= [];
var xmlhtmls			= [];
var xmlpoints			= [];
var xmllines			= [];
var m 					= [];
var n 					= [];
var o 					= [];

var labels				= [];

// Set type vars for dynamic saving of marker/polyline
var markertypes			= [];
var polylinetypes		= [];
var overlayarray		= [];
var cmidx;
var clidx;

var sidebar_html 		= [];
var statsbar_html		= [];
var statsbaritems		= [];

var refreshTime			= 10000;
var refreshCounter		= 10000;
var skipRefresh			= false;
var followDevice		= Array();
var refreshDevice		= Array();
var controlValue		= false;

var show_type			= "";
var show_id				= "";
var start_utcd			= "";
var start_utct			= "";
var end_utcd			= "";
var end_utct			= "";
var getstring			= "";
var settings			= [];
var extra_settings		= [];
var currentcolor		= '';
var currentstatus		= '';
var imageurl			= '';

var devicemarkers		= [];

var pngstats			= '';
var pngprogress			= '';

var bounds 				= new GLatLngBounds();
var xml_extra			= [];

var map;

// Define the tooltip var
var tooltip = document.createElement("div");
var dagen = document.createElement("div");

var settingsDiv = document.createElement("div");
var followDiv = document.createElement("div");
var extrainformationDiv = document.createElement("div");
var refreshDiv = document.createElement("div");
var refreshSecDiv = document.createElement("div");
var refreshNowDiv = document.createElement("div");

var settingsDivs = Array();

// Define the Days div elements;
var DayDivs = new Array();
for(var k = 0; k < 7; k++) {
	DayDivs[k] = document.createElement("div");
}

var currentday = "";
var ToDay = _get_today();
var DaysArray = Array();

DaysArray[0] = "100704";
DaysArray[1] = "100705";
DaysArray[2] = "100706";
DaysArray[3] = "100708";
DaysArray[4] = "100709";
DaysArray[5] = "100710";

function initMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		map.enableScrollWheelZoom();
	
	// Center the map on a point
		map.setCenter(new GLatLng(53.203976, 5.792542), 10);
	}  else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}  

	// More tooltip initiation stuff
	document.getElementById('map').appendChild(tooltip);
	tooltip.style.visibility="hidden";

	// _printIkadongaLogo();
	
	_printDayDivs();
	_showDays();
	_printDagen();
	_showFollowDiv();
	_showRefreshDiv();
	_showSettingsDiv();
	
	
	refreshControl(refreshTime);
	_loadMap();
	window.setTimeout('zoomfit();', 500);
	
	GEvent.addListener(map, "click", function(overlay) {
		if (!overlay)	map.closeInfoWindow();
	});

}

function _printIkadongaLogo() {
// Print the Ikadonga Logo
	// Define the Ikadonga div
	var ikadonga = document.createElement("img");
	document.getElementById('map').appendChild(ikadonga);
	ikadonga.style.visibility="hidden";
	if (BrowserDetect.browser=="Explorer" && BrowserDetect.version == 6) ikadonga_filename = "http://www.ikadonga.nl/components/com_ikadonga/images/ikadonga_alpha.gif"; else ikadonga_filename = "http://www.ikadonga.nl/components/com_ikadonga/images/ikadonga_alpha.png";
//	ikadonga.innerHTML = '<img onclick="window.open(\'http://www.ikadonga.nl\', \'_blank\')" src="'+ikadonga_filename+'" alt="" style="cursor: pointer;"/>';
	ikadonga.src = ikadonga_filename;
//	function(){deletepoint(i);};
	ikadonga.onclick = function(){window.open('http://www.ikadonga.nl', '_blank');};
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(2,14));
	pos.apply(ikadonga);
	ikadonga.style.visibility="visible";
}

function _printDayDivs() {
	for(var k = 0; k < 7; k++) {
	// More daydivs initiation stuff
	   document.getElementById('map').appendChild(DayDivs[k]);
	   DayDivs[k].style.visibility="hidden";
	}
}

function _showFollowDiv() {

	document.getElementById('map').appendChild(followDiv);
	followDiv.style.visibility="hidden";

	followDiv.style.width				= "130px";
	followDiv.style.height				= "20px";
	followDiv.style.backgroundColor 	= "#ffffff";
	
	followDevice[5]			= true;	
	followDevice[7]			= true;	
	followDiv.innerHTML = '<input type="checkbox" id="follow" name="follow" onchange="javascript:setFollow(28,this.checked)" checked /><label for="follow">Volg Solarboat</label>';
	
	var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 70 + settingsDivs.length * 20));
	pos.apply(followDiv);
//	followDiv.style.visibility="visible";
	
	_setOpacity(followDiv, 0.8);
	
	settingsDivs[settingsDivs.length] = followDiv;
}

function setFollow(device_id, value) {
	//alert('follow: '+device_id+' is ' + value);
	followDevice[device_id] = value;	
}

function _showRefreshDiv() {

	document.getElementById('map').appendChild(refreshDiv);
	refreshDiv.style.visibility			= "hidden";
	refreshDiv.style.width				= "130px";
	refreshDiv.style.height				= "20px";
	refreshDiv.style.backgroundColor 	= "#ffffff";
	
	refreshDevice[7]		= true;
	refreshDiv.innerHTML = '<input type="checkbox" id="refresh" name="refresh" onchange="javascript:setRefresh(7,this.checked);controlValue = this.checked" checked="checked"/><label for="refresh">Auto refresh</label>';
	
	var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 70 + settingsDivs.length * 20));
	pos.apply(refreshDiv);
	// refreshDiv.style.visibility="visible";
	
	_setOpacity(refreshDiv, 0.8);
	
	settingsDivs[settingsDivs.length] = refreshDiv;
	
	document.getElementById('map').appendChild(refreshSecDiv);
	refreshSecDiv.style.visibility			= "hidden";
	refreshSecDiv.style.width				= "100px";
	refreshSecDiv.style.height				= "20px";
	refreshSecDiv.style.textAlign			= "right";
	refreshSecDiv.style.backgroundColor 	= "#ffffff";
	
	refreshSecDiv.innerHTML = '30sec';
	
	var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(38, 70 + settingsDivs.length * 20));
	pos.apply(refreshSecDiv);
//	refreshSecDiv.style.visibility="visible";
	
	_setOpacity(refreshSecDiv, 0.8);
	settingsDivs[settingsDivs.length] = Array();
	settingsDivs[settingsDivs.length-1][settingsDivs[settingsDivs.length-1].length] = refreshSecDiv;
	
	document.getElementById('map').appendChild(refreshNowDiv);
	refreshNowDiv.style.visibility			= "hidden";
	refreshNowDiv.style.width				= "30px";
	refreshNowDiv.style.height				= "20px";
	refreshSecDiv.style.textAlign			= "left";
	refreshNowDiv.style.backgroundColor 	= "#ffffff";
	
	refreshNowDiv.innerHTML = '<div id="refreshNow" name="refreshNow" onclick="javascript:refreshCounter=100;" style="cursor: pointer;text-align:right">Nu</div>';
	
	var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 70 + (settingsDivs.length - 1) * 20));
	pos.apply(refreshNowDiv);
//	refreshNowDiv.style.visibility="visible";
	
	_setOpacity(refreshNowDiv, 0.8);
	settingsDivs[settingsDivs.length-1][settingsDivs[settingsDivs.length-1].length] = refreshNowDiv;
}

function _showSettingsDiv() {
	document.getElementById('map').appendChild(settingsDiv);
	settingsDiv.style.visibility		= "hidden";
	settingsDiv.style.width				= "150px";
	settingsDiv.style.height			= "20px";
	settingsDiv.style.textAlign			= "left";
	settingsDiv.style.backgroundColor 	= "#ffffff";
	
	settingsDiv.innerHTML = '<input type="checkbox" id="showsettings" name="showsettings" onclick="javascript:switchSettings(this.checked);" /><label for="showsettings" onclick="javascript:switchSettings(this.checked);">Toon Instellingen</label>';	

	var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 50));
	pos.apply(settingsDiv);
	// settingsDiv.style.visibility="visible";
	
	_setOpacity(settingsDiv, 0.8);
}

function switchSettings(que) {

	que = document.getElementById('showsettings').checked;
	var obj = settingsDivs;
	if (que) {
		for(var i = 0; i < obj.length; i++) {
			// alert("Turning On obj[i] length="+obj[i].length);
			// alert("typeof dinges = "+typeof(obj[i]));
			if (!(obj[i].length === parseInt(obj[i].length,10))) {
				obj[i].style.visibility='visible';
			} else {
				for(var j = 0; j < obj[i].length; j++) {
					obj[i][j].style.visibility='visible';
				}
			}
		}
	} else {
		for(var i = 0; i < obj.length; i++) {
			// alert("Turning Of obj[i] length="+obj[i].length);
			// alert("typeof dinges = "+typeof(obj[i]));
			// alert("parseInt dinges: "+parseInt(obj[i].length,10));
			if (!(obj[i].length === parseInt(obj[i].length,10))) {
				obj[i].style.visibility='hidden';
			} else {
				for(var j = 0; j < obj[i].length; j++) {
					obj[i][j].style.visibility='hidden';
				}
			}
		}
	}
}

function setRefresh(device_id, value) {
	//alert('follow: '+device_id+' is ' + value);
	refreshDevice[device_id] = value;
}

function _setOpacity(object, c) {
	if(typeof(object.style.filter)=='string'){object.style.filter='alpha(opacity:'+c*100+')';}
	if(typeof(object.style.KHTMLOpacity)=='string'){object.style.KHTMLOpacity=c;}
	if(typeof(object.style.MozOpacity)=='string'){object.style.MozOpacity=c;}
	if(typeof(object.style.opacity)=='string'){object.style.opacity=c;}	
}

function _showDays() {

	for(var k = 0; k < 6; k++) {

		var e;
		if (k==currentday) {
			e='e';
			ke=k;
		} else e='';

		DayDivs[k].innerHTML = '<img id="imageday'+k+'" onclick="viewraceday(\'' + k + '\'); if(this.src=\'images/button_'+k+'.gif\'){this.src=\'images/button_'+k+'e.png\'}else{this.src=\'images/button_'+k+'.png\'}" src="images/button_'+k+e+'.png" alt="" border="0" style="cursor: pointer;"></a>';
		// center = map.getCenter();
		var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(140 - (22 * (k+1)), 30));
		pos.apply(DayDivs[k]);
		DayDivs[k].style.visibility="visible";
   }
}

function _printDagen() {
	dagen.innerHTML = '<div class="daydivs" id="dagen" style="text-align:center;width:100px;height:220px">Dagen</div>';
	var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(200, 30));
	pos.apply(dagen);
	dagen.style.visibility="visible";
}


function _setsettings(setsettings) {
	var vars = setsettings.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		settings[pair[0]] = pair[1];
	} 
}

function getsettings() {
	var response = _getsettings();
	return response;
}

function _getsettings() {
	var getstring = "";
	for (keyVar in settings) {
		getstring += keyVar+'='+settings[keyVar]+'&';
	}
	getstring += 'timestamp='+(new Date().getTime());
	return getstring;
}

function _getIcontype(type, label) {

  if (type == "brug") {
  		return bridgeIcon;
  }
  if (type == "start") {
  		return startIcon;
  }
  if (type == "end") {
  		return endIcon;
  }
  if (type == "solarboat") {
  		return labelIcon;
  }
  if (type == "techcar") {
  		return techcarIcon;
  }
  if (type == "curpos") {
  		return labelIcon;
  }
  return '';
}
	
function zoomfit() {

	var totalbounds = 0;
	// Loop through the extra_settings array to accumulate the bounds etc
	for (var i=0; i < extra_settings.length; i++) {
		if (typeof(extra_settings[i]) != "undefined") {
			if (typeof(extra_settings[i]["boundcount"]) != "undefined")
				totalbounds = (totalbounds*1) + (extra_settings[i]["boundcount"]*1);
		}
	}

	xml_extra["boundcount"] = xml_extra["linepointcount"] + xml_extra["markercount"];
	// _showText("BoundCount = " + xml_extra["boundcount"] + ", Linepointcount=" + xml_extra["linepointcount"] + ", Markercount=" + xml_extra["markercount"] + " totalbounds=" + totalbounds);
	 if (xml_extra["boundcount"] == 0 && totalbounds == 0) {
		// _showText("Geen gegevens gevonden");
	 	return;
	 }
	 if (!xml_extra["boundcount"] || xml_extra["boundcount"] < totalbounds) {
		window.setTimeout('zoomfit();', 500);
	 	return;
	 }
    // ===== determine the centre from the bounds ======
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
    map.setCenter(new GLatLng(clat,clng));
	map.setZoom(map.getBoundsZoomLevel(bounds)-1);
    _showText('Klaar');
	window.setTimeout('hideText();', 1000);
}

function _showText(text) {
	return false;
	var width  = 200;
	var height = 20;
	var reg = /\(([0-9.]*),\s*([0-9.]*)\)/i;
	var mapsize = reg.exec(map.getSize());
	var map_width = mapsize[1];
	var map_height = mapsize[2];
	tooltip.innerHTML = '<div class="tooltip" id="tooltip" style="text-align:center;width:'+width+'px;height:'+height+'px" onclick="this.style.display=\'none\';"><br/>'+text+'</div>';
	tooltiptext = text;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize( 100 , 0) );
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
	_setOpacity(tooltip, 0.8);
}

// It hides the tooltip      
function hideText() {
   tooltip.style.visibility="hidden";
}

function viewraceday(day) {
	
	bounds = new GLatLngBounds();
	xml_extra = [];
	xml_extra["boundcount"] = -1;

	map.clearOverlays();
	
	refreshCounter = refreshTime;
	
	var url = document.URL;
	if (url.substring(url.lastIndexOf("\/")+1,url.lastIndexOf("\.")) == 'volgauto') {
		document.getElementById('pngstatsbar').innerHTML = '';
	}
	
	
	document.getElementById("statsbar").innerHTML = 'STATISTICS:<br><br>';
	currentday = day;
	_showDays();
	_getXML('xml_2010/elfstedentocht' + day + '.xml?timestamp='+(new Date().getTime()), 1);
	_setsettings('start_utcd='+DaysArray[day]+'&start_utct=0&end_utcd='+DaysArray[day]+'&end_utct=235959');
	_getXML('easytracking.php?' + _getsettings(), 0);
	window.setTimeout('zoomfit();', 500);
}

function _loadMap() {
	bounds = new GLatLngBounds();
	xml_extra = [];
	xml_extra["boundcount"] = -1;

	extra_settings = [];
	_showDays();
	_getXML('xml_2010/elfstedentocht' + currentday + '.xml?timestamp='+(new Date().getTime()), 1);
	_getXML  ('easytracking.php?' + _getsettings(), 0);
}

function _get_today() {
    var X;
    with (new Date()) {
        X = parseFloat((getFullYear() * 100 + getMonth() + 1) * 100 + getDate() - 20000000);
    }
    return X;
}

function _get_now() {
    var X;
    with (new Date()) {
        X = parseFloat((getHours() * 10000 + getMinutes() * 100 + getSeconds()));
    }
    return X;
}

function setcurrentday(Day) {
	currentday = Day;
	_setsettings('start_utcd='+DaysArray[Day]+'&start_utct=0&end_utcd='+DaysArray[Day]+'&end_utct=235959');
}

function refreshControl() {
	// Update the refresh time and display if neccesary
	refreshCounter = refreshCounter - 1000;
	if (refreshCounter < 0) refreshCounter = 0;
	
	if (controlValue == true) {
		var sec = refreshCounter / 1000;
		refreshSecDiv.innerHTML = '<div style="width:100%;text-align:right">' + Math.round(sec) + 'sec</div>';
		if (refreshNowDiv.innerHTML == '') {
			refreshNowDiv.innerHTML = '<div id="refreshNow" name="refreshNow" onclick="javascript:refreshCounter=100;" style="cursor: pointer;text-align:right">Nu</div>';
		}
	} else {
		refreshNowDiv.innerHTML = '';
		refreshSecDiv.innerHTML = '<div onclick="javascript:refresh('+true+');refreshCounter = refreshTime" style="width:100%;cursor: pointer;text-align:right">Manueel refresh</div>';
	}

	if (refreshCounter < 1000) {
		refresh();
		refreshCounter = refreshTime;
	}
	window.setTimeout('refreshControl();', 1000);
}

function refresh(manueel) {
	var ToDay = _get_today();
	var Now = _get_now();
	if (parseFloat(settings["end_utcd"]) < ToDay) {
		return;
	} else if (parseFloat(settings["end_utcd"]) == ToDay && parseFloat(settings["end_utct"]) < Now) {
		return;
	} else if (typeof(refreshDevice[7]) != "undefined") {
		if (refreshDevice[7] != true && manueel != true) {
			return;
		}
	} else if (typeof(refreshDevice[7]) == "undefined") {
		return;
	}
	if (skipRefresh == true) {
		skipRefresh = false;
		return;
	}
	// refresh only the dynamic data
	var file = 'easytracking.php?' + _getsettings();
	if (typeof(extra_settings[0]["lastpoint"]) != "undefined" ) {
		file += '&lastpoint=' + extra_settings[0]["lastpoint"];
	}
	_getXML(file, 0);
}

function _importanceOrder (marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}


function _createBGMarker(point,label,html,type) {
	// The _createBGMarker() function not only sets up
	// the marker and its event handler, but it also
	// causes local copies of the "marker" and "html"
	// variables to be preserved for later use when
	// the event gets triggered. This is a special
	// feature of the Javascript language called
	// "function closure"
	var marker = new GMarker(point,{icon: _getIcontype(type, label), zIndexProcess:_importanceOrder});
	var Importance = 1;
	if (type != "start" && type != "end" && type != "marker") Importance = 3;
	marker.importance = Importance;
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

// make the markers by calling an external function and plot them
function domarkers(idx) {
	var chunk = cmidx + 8;
	while (cmidx < chunk && cmidx < xmlmarkers[idx].length) {
		if (!xmlmarkers[idx][cmidx]["marker"]) { 
			var marker = _createBGMarker(xmlmarkers[idx][cmidx]["point"],'',xmlmarkers[idx][cmidx]["html"],xmlmarkers[idx][cmidx]["type"]);
  			xmlmarkers[idx][cmidx]["marker"] = marker;
			map.addOverlay(marker);
		}
		cmidx++;
	}
	if (cmidx < (xmlmarkers[idx].length-1)) {
		var ft = Math.ceil(((cmidx+1)/xmlmarkers[idx].length)*100);
		_showText('Punten toevoegen... ('+ft+'%)');
		window.setTimeout('domarkers('+idx+')', 100);
	} else {
		hideText();
	}
}

function dolines(idx) {

	var chunk = clidx + 2;
	while (clidx < chunk && clidx < xmllines[idx].length) {
		var line = xmllines[idx][clidx];
		map.addOverlay(line);
		clidx++;
	}
	if (clidx < (xmllines[idx].length)) {
		var ft = Math.ceil(((clidx+1)/xmllines[idx].length)*100);
		_showText('Lijn tekenen... ('+ft+'%)');
		window.setTimeout('dolines('+idx+')', 100);
	} else {
		hideText();
	}
}

function _outputstats(idx, id, name, value) {
	// if (statsbaritems[idx] == 0) {
		// for(var b=0;b<statsbar_html.length;b++) {
			// document.getElementById("statsbar").innerHTML += statsbar_html[b];
	   // }
	// }
	
	if (id=="day1" || id=="day2"|| id=="day3"|| id=="day4"|| id=="day5"|| id=="day6") {
		// statsbar_html[idx] += '<b>Race distance</b>: '+value;
		// document.getElementById("statsbar").innerHTML += '<b>Race distance</b>: '+value+'km<br>';
	} else {
	// if (id=='stats') {
		// statsbar_html[idx] += '<b>'+name+'</b>: '+value+'<br/>';
		var tr = document.createElement('tr');
		var td1 = document.createElement('td');
		var td2 = document.createElement('td');
		td1.appendChild(document.createTextNode(name));
		// td2.appendChild(document.createTextNode(value));
		td2.innerHTML = value;
		tr.appendChild(td1);
		tr.appendChild(td2);

		document.getElementById("statstable").tBodies[0].appendChild(tr);

		// if (BrowserDetect.browser == 'Explorer')
			// document.getElementById("statsbar").innerHTML += '<b>'+name+'</b>: '+value+'<br/>';
	// }	
	}
	statsbaritems[idx]++;
}


function _imgclick (device_id) {
	settings["show_type"]	= 'device';
	settings["show_id"]		= device_id;
	_loadMap();
}

function _getXML (file, idx) {

	_showText("Gegevens ophalen...");
	var request = GXmlHttp.create();
	request.open("GET", file, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;

			if (!xmlDoc) {
				// _showText('Geen gegevens gevonden...');
				return;
			}
			
			extra_settings[idx]			= [];
			// ========= Now check for extra information (eg. counts) ===========
			var extra = xmlDoc.documentElement.getElementsByTagName("extra");
			// read each line
			for (var a = 0; a < extra.length; a++) {
				var setting = extra[a].getElementsByTagName("setting");
				for (var i = 0; i < setting.length; i++) {
					if (typeof( extra_settings[idx][setting[i].getAttribute("name")] ) == "undefined" ) {
						extra_settings[idx][setting[i].getAttribute("name")] = setting[i].getAttribute("value");
					} else {
						extra_settings[idx][setting[i].getAttribute("name")] = (extra_settings[idx][setting[i].getAttribute("name")]*1) + (setting[i].getAttribute("value")*1);
					}
					if (typeof(xml_extra[setting[i].getAttribute("name")]) == "undefined" ) {
						xml_extra[setting[i].getAttribute("name")]=0;
					}
				}
			}
			// ================================================  
			
			
			// Only proceed if lastpoint != resumefromlastpoint
			var proceed = false;
			if (typeof(extra_settings[idx]["lastpoint"]) != "undefined" && typeof(extra_settings[idx]["resumefromlastpoint"]) != "undefined") {
				if (extra_settings[idx]["lastpoint"] != extra_settings[idx]["resumefromlastpoint"]) {
					proceed = true;
				}
			} else proceed = true;
			
			if (proceed) {
			
				if (false) { // Temporarily skip this step... for testing with partial updates of route
					// Remove Old BGMap
					if (xmlmarkers[idx]){
						for (k=0; k < xmlmarkers[idx].length; k++) {
							map.removeOverlay(xmlmarkers[idx][k]["marker"]);
						}
						for (k=0; k < xmllines[idx].length; k++) {
							map.removeOverlay(xmllines[idx][k]);
						}
					}
				}
				
			      // empty the array
					xmlmarkers[idx] 			= [];
					xmlhtmls[idx]				= [];
					xmlpoints[idx]				= [];
					xmllines[idx]				= [];

			      // reset the marker counter
					m[idx] 						= 0;
					n[idx] 						= 1;
					o[idx] 						= 1;
			
				  // reset the sidebar
					markertypes[idx] 			= [];
					polylinetypes[idx] 			= [];
					labels[idx]					= [];
					
					var checked;
					var sTime =(new Date()).getTime();

					var sidebar_html = '';

					// obtain the array of markers and loop through it
					var markers = xmlDoc.documentElement.getElementsByTagName("marker");
					for (var k = 0; k < markers.length; k++) {
						// obtain the attribues of each marker
						xmlmarkers[idx][m[idx]] = [];
						xmlmarkers[idx][m[idx]]["lat"] = parseFloat(markers[k].getAttribute("lat"));
						xmlmarkers[idx][m[idx]]["lon"] = parseFloat(markers[k].getAttribute("lon"));
						xmlmarkers[idx][m[idx]]["point"] = new GLatLng(xmlmarkers[idx][m[idx]]["lat"],xmlmarkers[idx][m[idx]]["lon"]);
						xmlmarkers[idx][m[idx]]["html"] = markers[k].getAttribute("html");
						xmlmarkers[idx][m[idx]]["label"] = markers[k].getAttribute("label");
						xmlmarkers[idx][m[idx]]["device_id"] = markers[k].getAttribute("device_id");
						xmlmarkers[idx][m[idx]]["type"] = markers[k].getAttribute("type");
						
						bounds.extend(xmlmarkers[idx][m[idx]]["point"]);
						if (typeof(xml_extra["markercount"]) == "undefined") xml_extra["markercount"] = 0;
						xml_extra["markercount"]++;
						var type = xmlmarkers[idx][m[idx]]["type"];
						if (type == 'curpos') {
							currentcolor  = markers[k].getAttribute("color");
							currentstatus = markers[k].getAttribute("status");

							// Check if a device should be followed
							if (typeof(followDevice[xmlmarkers[idx][m[idx]]["device_id"]]) != "undefined") {
								if (followDevice[xmlmarkers[idx][m[idx]]["device_id"]] == true)
									map.setCenter(new GLatLng(xmlmarkers[idx][m[idx]]["lat"], xmlmarkers[idx][m[idx]]["lon"]));
							}
							
							if (typeof(devicemarkers[xmlmarkers[idx][m[idx]]["device_id"]]) != "undefined" && devicemarkers[xmlmarkers[idx][m[idx]]["device_id"]]) {
								map.removeOverlay(devicemarkers[xmlmarkers[idx][m[idx]]["device_id"]]);
								devicemarkers[xmlmarkers[idx][m[idx]]["device_id"]] = false;
							}
							
						}
						
						var marker = _createBGMarker(xmlmarkers[idx][m[idx]]["point"],xmlmarkers[idx][m[idx]]["label"],xmlmarkers[idx][m[idx]]["html"],type);
						if (type == 'curpos') devicemarkers[xmlmarkers[idx][m[idx]]["device_id"]] = marker;
						xmlmarkers[idx][m[idx]]["marker"] = marker;
						map.addOverlay(marker);
						m[idx]++;
						
			        }

					// obtain the array of markers and loop through it
					var hidden = xmlDoc.documentElement.getElementsByTagName("hidden");
					for (var b = 0; b < hidden.length; b++) {
						labels[idx][b] = [];
						// obtain the attribues of each hidden item
						labels[idx][b]["label"] = hidden[b].getAttribute("label");
						labels[idx][b]["device_id"] = hidden[b].getAttribute("device_id");
						labels[idx][b]["type"] = hidden[b].getAttribute("type");
						labels[idx][b]["color"]  = hidden[b].getAttribute("color");
						labels[idx][b]["status"] = hidden[b].getAttribute("status");
			      }

			      // ========= Now process the polylines ===========
			      var lines = xmlDoc.documentElement.getElementsByTagName("line");
			      // read each line
					for (var a = 0; a < lines.length; a++) {
						// get any line attributes
							var color = lines[a].getAttribute("color");
							var width  = parseFloat(lines[a].getAttribute("width"));
							var opac	  = lines[a].getAttribute("opac");
							//var type	  = lines[a].getAttribute("type");
							// read each point on that line
							var points = lines[a].getElementsByTagName("point");
							var pts = [];
							for (var i = 0; i < points.length; i++) {
								pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
												   parseFloat(points[i].getAttribute("lon")));
								bounds.extend(pts[i]);
								xml_extra["linepointcount"]++;
							}
							var polyline = new GPolyline(pts,color,width,opac);
							xmllines[idx][a] = polyline;
							//map.addOverlay(polyline);
							//polylinetypes[idx][a] = type;
					}

					// ================================================  
					cmidx = 0;
					clidx = 0;
					window.setTimeout('dolines('+(idx)+')', 10);
					// document.getElementById("statsbar").appendChild(document.createTextNode('STATISTICS:'));
					if (document.getElementById("statstable") != null)
						document.getElementById("statsbar").removeChild(document.getElementById("statstable"));
					var table = document.createElement('table');
					var body = document.createElement("TBODY");
					table.appendChild(body);
					table.id = 'statstable';
					document.getElementById("statsbar").appendChild(table);
					
					var url = document.URL;
					if (url.substring(url.lastIndexOf("\/")+1,url.lastIndexOf("\.")) == 'volgauto') {
						statsbar_html[idx] = '<br><br>';
						statsbaritems[idx] = 0;
				
					    // ========= Now process the stats ===========
					    var stats = xmlDoc.documentElement.getElementsByTagName("stats");
					    // read each line
						for (var a = 0; a < stats.length; a++) {
							// get any line attributes
							var id		= stats[a].getAttribute("id");
							var name	= stats[a].getAttribute("name");
							var value	= stats[a].getAttribute("value");
							// Process the values with an external function to speed up the process
							_outputstats(idx, id, name, value);
						}
					}
					
				// Get a new image in the png div
				var url = document.URL;
				if (url.substring(url.lastIndexOf("\/")+1,url.lastIndexOf("\.")) == 'volgauto' && extra_settings[idx]["lastpoint"] > 0) {
					var pngurl = 'easytracking.php?'+_getsettings()+pngstats+'&graphtype='+document.getElementById('graphtype').value;
					document.getElementById('pngstatsbar').innerHTML = '<img src="'+pngurl+'" alt="" />';
					pngurl = 'easytracking.php?'+_getsettings()+pngprogress+'&graphtype='+document.getElementById('graphtype').value;
					document.getElementById('pngprogressbar').innerHTML = '<img src="'+pngurl+'" alt="" />';
				}
			} else hideText();
		}
		delete request;
   }
   request.send(null);
}