// global vars
var geocoder = null;
var gm = null;
var map = null;
var mgr = null;
var progressBar = null;
var aMarkers = new Array();
var aMarkersOnMap = new Array();
var aIcons = new Array();
var defaultIconURL = "http://maps.gstatic.com/intl/nl_nl/mapfiles/marker.png";
var defaultHiliteIconURL = "http://maps.gstatic.com/intl/nl_nl/mapfiles/marker_yellow.png";
var aXMLMarkers = new Array();
var canvasID = "gMapCanvas";
var sidebarID = "gMapSidebar";
var kmlDebugID = "debugKMLxml"
var debugKML = false;
var defaultAddress = "Amsterdam, Netherlands";
var defaultZoom = 8;
var maxZoomOut = 8;
var collection = null;
var additionalSearchCriteria = "";
var aListStartPos = new Array();
var arrayIndex = 0;
var prevZoom = null;
var IE6orLess = null;
var onMouseOverShowInfoboxWithMarker = false;
var onMouseOverMarkerShowInfobox = true;
var isRestore = false;
var onInitializeMapDisplayMarkers = true;
var withList = true;
var allowDuplicateMarkers = false;
var callback = null; 
var defMaptype = G_NORMAL_MAP
var disableScrollWheelZoom = false
var searchOnMove = true
var defaultMarkerWidth = 32;
var defaultMarkerHeight = 32;
var viewportZoom = 1;

function GoogleMap() {
	// SETTINGS
	this.kmlurl = "/modules/googlemaps/markers.cfm?nlng=[nlng]&slng=[slng]&nlat=[nlat]&slat=[slat]&collection=" + collection;
	this.withList = withList;
	this.initialSearch = true;
	this.defaultAddress = defaultAddress;
	this.defaultCenterPoint = null;
	this.defaultZoom = defaultZoom;
	this.additionalSearchCriteria = null;
	this.onMouseOverShowInfoboxWithMarker = onMouseOverShowInfoboxWithMarker;
	this.debug = debugKML;
	// END OF SETTNGS
}

// initialize the map
GoogleMap.prototype.initializeMap = function() {
	if (GBrowserIsCompatible()) {
		// init map
		map = new GMap2(document.getElementById(canvasID));
		// moet eerst op map setCenter aanroepen. Anders krijg je of geen foutmelding (doet ie gewoon niets) of d is undefined oid
		map.setCenter(this.defaultCenterPoint, this.defaultZoom);
		
		// set map controls
		map.setUIToDefault();
		map.setMapType(defMaptype);
		// add mouseout event
		GEvent.addListener(map, "mouseout", function() {
			hideCustomInfobox();
		});
		// add event on moveend, new markers will be shown depending on the viewport
		GEvent.addListener(map, "movestart", function() {
			hideCustomInfobox();
		});
		// add event on moveend, new markers will be shown depending on the viewport
		GEvent.addListener(map, "moveend", function() {
			gm.initialSearch = false
			// extra search criteria
			if (gm.additionalSearchCriteria != additionalSearchCriteria) {
				// save search criteria
				gm.additionalSearchCriteria = additionalSearchCriteria;
			}
			// get markers based on the new map center or the changed search criteria
			if (searchOnMove == true) loadPointers();
		});
		// create marker manager
		mgr = new MarkerManager(map);
		// set default icons
		setIcon(defaultIconURL);
		setIcon(defaultHiliteIconURL);
		// create and add progressbar to indicate when all markers are loaded
		progressBar = new ProgressbarControl(map, {width:150, loadstring:'Loading... please wait'});
		// get markers based on the default map center
		if (onInitializeMapDisplayMarkers == true) {
			loadPointers();
		}
		if (disableScrollWheelZoom == true) {			
			map.disableScrollWheelZoom();
		}
	} else {
		alert('Sorry, your browser is incompatible with Google Maps');
	}
}

function setDefaultMapCenter() {
	geocoder.getLatLng(gm.defaultAddress, cbSetDefaultMapCenter);
}
function cbSetDefaultMapCenter(point) {
	if (point == null) {
		alert("Sorry, we cannot find the default address: " + gm.defaultAddress);
	} else {
		// set center of the map
		gm.defaultCenterPoint = point;
		// initialize map
		gm.initializeMap();
	}
}

// get the pointers as XML
function loadPointers() {
	// calculate viewport
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	// set url to retrieve markers, replace values with vieport boundaries
	var targetUrl = gm.kmlurl.replace("[slng]", southWest.lng());
	targetUrl = targetUrl.replace("[slat]", southWest.lat());
	targetUrl = targetUrl.replace("[nlng]", northEast.lng());
	targetUrl = targetUrl.replace("[nlat]", northEast.lat());
	// if 'Provincie ' is specified in default adress
	if (gm.initialSearch == true && gm.defaultAddress.indexOf("Provincie ") != -1) targetUrl += ( "&provincie=" + gm.defaultAddress.replace(/Provincie /, "").toLowerCase() )
	// save extra search criteria
	if (additionalSearchCriteria.length > 0 && gm.additionalSearchCriteria != additionalSearchCriteria) {
		// save search criteria
		gm.additionalSearchCriteria = additionalSearchCriteria;
	}
	// add extra search criteria to target url
	if (gm.additionalSearchCriteria != null) targetUrl += gm.additionalSearchCriteria;
	// for debug reasons
	if (gm.debug == true && document.getElementById(kmlDebugID)) document.getElementById(kmlDebugID).innerHTML = "targetUrl: " + targetUrl + "<br/>"
	// send request
	GDownloadUrl(targetUrl, function(data, responseCode) {
		if (parseInt(responseCode) == 200) {
			// for debug reasons
			if (gm.debug == true && document.getElementById(kmlDebugID)) document.getElementById(kmlDebugID).innerHTML += "<xmp>" + data + "</xmp>";
			// parse response, convert to xmlDoc
			var xmlDoc = GXml.parse(data);
			// process returned xml
			setMarkersXML(xmlDoc);
		}
	});
}

// put the markers on the map
function setMarkersXML(xmlDoc) {
	var iconUrl = null
	var hiliteIconUrl = defaultHiliteIconURL
	// find all placemarks in xmlDoc and save in array
	aXMLMarkers = xmlDoc.documentElement.getElementsByTagName("Placemark");
	// if placemarks found, show on map
	if (aXMLMarkers.length > 0) {
		// cleanup current marker array
		aMarkers = new Array();
		// cleanup markers on map array
		aMarkersOnMap = new Array;
		// create markers
		for (var i=0; i<aXMLMarkers.length; i++) {
			// try to get the url of the icon
			try {
				iconUrl = aXMLMarkers[i].getElementsByTagName("href")[0].childNodes[0].nodeValue;
			} catch(e) {
				iconUrl = defaultIconURL;
			}
			// remove white-space
			iconUrl = iconUrl.replace(/^\s+/, "").replace(/\s+$/, "");
			// create the marker
			var marker = createMarker(aXMLMarkers[i], iconUrl, hiliteIconUrl);
			// add marker to global markers array
			if (!checkInArray(marker)) { 
				aMarkers.push(marker);
			}
		}
		// set the progress bar
		progressBar.start(aMarkers.length);
		// if restore call markers loaded
		if (isRestore) {
			restoreMapMarkersLoaded()
		} else {	
			// if sidebar
			if (gm.withList == true) {
				// reset array
				aListStartPos = new Array();
				// reset index
				arrayIndex = 0;
				// save the start pos in the array
				aListStartPos.push(0);
				// cleanup sidebar			
				cleanupSideBarItems();
			}
			// display marker on map
			setMarkersHelper(0);
		}
	} else if ( map.getZoom() > maxZoomOut ) {
		// zoom out one level
		map.setZoom(map.getZoom() - 1)
	} else {
		// hide infobox
		hideCustomInfobox();
		// cleanup current marker array
		aMarkers = new Array();
		// cleanup markers on map array
		aMarkersOnMap = new Array();
		// cleanup sidebar
		if (gm.withList == true) {
			cleanupSideBarItems();
		}
		// cleanup markers displayed currently on map
		mgr.clearMarkers();
	}
	// need to trigger callback function which can be used to indicate searchresult is returned 
	if (callback != null) {
		eval(callback);
	}
}

function fitZoomToMarkers(){
	var viewport = new GLatLngBounds;
	for(i=0;i<aMarkers.length;i++){
		viewport.extend(aMarkers[i].getLatLng());
	}
	map.setCenter(viewport.getCenter(), map.getBoundsZoomLevel(viewport));
}

function showPreviousMarkers() {
	// update global index
	arrayIndex -= 1;
	// need to reset aListStartPos
	startPos = aListStartPos[arrayIndex];
	// set markers according to startPos
	setMarkers(startPos);
}

function showNextMarkers(startPos) {
	// update global index
	arrayIndex += 1;
	// save the start pos in the array
	if ((aListStartPos.length - 1) < arrayIndex) aListStartPos.push(startPos);
	// set markers according to startPos 
	setMarkers(startPos);
}

function setMarkers(startPos) {
	// hide infobox
	hideCustomInfobox();
	// cleanup markers on map array
	aMarkersOnMap = new Array();
	// cleanup sidebar contents
	cleanupSideBarItems();
	// add markers to array/map
	setMarkersHelper(startPos);
}

// function that continues the setMarkers function. Have to use the setTimeout function, otherwise the progressbar isn't updated!
function setMarkersHelper(arrayPos) {
	// if list is available, add item to list
	if (gm.withList) {
		// put the marker in the sidebar
		var returnedArrayPos = addSideBarItem(aMarkers[arrayPos], arrayPos);
		if (returnedArrayPos < arrayPos) {
			return showMarkersOnMap(returnedArrayPos);
		}
	}
	// also add to markers shown on the map array
	aMarkersOnMap.push(aMarkers[arrayPos]);
	// update the progressbar
	progressBar.updateLoader(1);
	// update counter
	arrayPos++;
	// check if all markers are shown on the map else continue
	if (aMarkers.length > arrayPos) {
		setTimeout("setMarkersHelper(" + arrayPos + ")", 5);
	} else {
		return showMarkersOnMap(arrayPos)
	}
}

function showMarkersOnMap(lastArrayPos) {
	// show used variables information
	//showDebugInfo(lastArrayPos);
	// need to display next previous
	if (gm.withList) {
		// set new start pos
		var startPos = lastArrayPos;
		// show previous / next
		showNextPreviousInSideBar(startPos);
	}
	// show markers and hide progressbar
	progressBar.remove();
	mgr.clearMarkers();
	mgr.addMarkers(aMarkersOnMap, 1);
	mgr.refresh();
	return true
}

// add the pointer as a clickable link to the sidebar
function addSideBarItem(marker, arrayPos) {
	var _sideBarDiv = document.getElementById(sidebarID);
	// determine sidebardiv height
	if ( IE6orLess &&  _sideBarDiv.style && _sideBarDiv.style.height && (parseInt(_sideBarDiv.style.height) > 0) ) {
		var _sideBarDivHeight = Math.min(_sideBarDiv.offsetHeight, parseInt(_sideBarDiv.style.height)); 
	} else {
		var _sideBarDivHeight = _sideBarDiv.offsetHeight;
	}
	// create container
	if ( !document.getElementById(sidebarID + "ItemContainer") ) {
		var _containerDiv = document.createElement("div")
		_containerDiv.id = sidebarID + "ItemContainer";
		_sideBarDiv.appendChild(_containerDiv);
	}
	var _itemContainer = document.getElementById(sidebarID + "ItemContainer");
	// need to append to container
	if ( _itemContainer.offsetHeight < _sideBarDivHeight ) {
		// create item
		var _itemDiv = document.createElement("div")
		_itemDiv.id = "markerSidebarItem_" + arrayPos;
		_itemDiv.className = "gMapSidebarItem";
		// set contents
		_itemDiv.innerHTML = marker.sidebar;
		// set visibility
		_itemDiv.style.visibility = "hidden";
		// add item to container
		_itemContainer.appendChild(_itemDiv);
		// check again if height is within parent height
		if ( _itemContainer.offsetHeight > _sideBarDiv.offsetHeight ) {
			// remove the last/current added child elements
			_itemContainer.removeChild(_itemContainer.childNodes[_itemContainer.childNodes.length-1]);
			// remove the previous added child element
			_itemContainer.removeChild(_itemContainer.childNodes[_itemContainer.childNodes.length-1]);
			aMarkersOnMap.pop();
			// return position minus 1
			return (arrayPos - 1)
		} else {
			// set sidebar item events
			if ( gm.onMouseOverShowInfoboxWithMarker ) {
				_itemDiv.onmouseover = function () {
					this.className = "gMapSidebarItemActive";
					try {
						aMarkers[arrayPos].setImage(aMarkers[arrayPos].hiliteIconUrl);							
					} catch(e) {
						// do nothing
					}
					GEvent.trigger(aMarkers[arrayPos], "click");
				};
				_itemDiv.onmouseout = function () {
					this.className = "gMapSidebarItem";
					try {
						aMarkers[arrayPos].setImage(aMarkers[arrayPos].orignalIconUrl);
					} catch(e) {
						// do nothing
					}	
					//hideCustomInfobox();
				};
			} else {
				_itemDiv.onclick = function () {
					GEvent.trigger(aMarkers[arrayPos], "click")
				};
				_itemDiv.onmouseover = function () {
					this.className = "gMapSidebarItemActive";
					try {
						aMarkers[arrayPos].setImage(aMarkers[arrayPos].hiliteIconUrl);
					} catch(e) {
						// do nothing
					}
					onMouseOverShowCustomInfobox(aMarkers[arrayPos], this);
				};
				_itemDiv.onmouseout = function () {
					this.className = "gMapSidebarItem";
					try {
						aMarkers[arrayPos].setImage(aMarkers[arrayPos].orignalIconUrl);
					} catch(e) {
						// do nothing
					}
					hideCustomInfobox();
				};
			}
			// attach marker events
			GEvent.addListener(marker, "mouseover", function() {
				if ( document.getElementById("markerSidebarItem_" + arrayPos) ) {
					document.getElementById("markerSidebarItem_" + arrayPos).className = "gMapSidebarItemActive";
				}
				return false 
			});
			GEvent.addListener(marker, "mouseout", function() { 
				if ( document.getElementById("markerSidebarItem_" + arrayPos) ) {
					document.getElementById("markerSidebarItem_" + arrayPos).className = "gMapSidebarItem";
				}
				return false 
			});
			// set visible
			_itemDiv.style.visibility = "visible";
			return arrayPos
		}
	} else {
		// remove the previous added child element
		_itemContainer.removeChild(_itemContainer.childNodes[_itemContainer.childNodes.length-1]);
		aMarkersOnMap.pop();
		// return position minus 1
		return (arrayPos - 1)
	}
}

// removes all pointers from the sidebar
function cleanupSideBarItems() {
	var _sideBarDiv = document.getElementById(sidebarID);
	if (document.getElementById(sidebarID + "ItemContainer")) {
		var _itemContainer = document.getElementById(sidebarID + "ItemContainer");
		while (_itemContainer.childNodes.length != 0) {
			_itemContainer.removeChild(_itemContainer.childNodes[0]);
		}	
	}
	if (document.getElementById(sidebarID + "ListControlContainer")) {
		_sideBarDiv.removeChild(document.getElementById(sidebarID + "ListControlContainer"));
	}
}

function showNextPreviousInSideBar(startPos) {	
	if (aMarkers.length > aMarkersOnMap.length){
		// create container
		if ( !document.getElementById(sidebarID + "ListControlContainer") ) {
			var _ListControlDiv = document.createElement("div");
			_ListControlDiv.id = sidebarID + "ListControlContainer";
			document.getElementById(sidebarID).appendChild(_ListControlDiv);
		}
		// create table
		var _str = '<table cellpadding="0" cellspacing="0" style="width:100%"><tr>'
		if ( aListStartPos.length > 1 && aListStartPos[arrayIndex] > 0 ) {
			_str +=	'<td style="text-align:left"><input type="button" class="' + sidebarID + 'ListControlPrevious" onclick="showPreviousMarkers()" value="&lt;&lt;"/></td>';
		}
		if ( (aMarkers.length - startPos) > 0  ) {
			_str +=	'<td style="text-align:right"><input type="button" class="' + sidebarID + 'ListControlNext" onclick="showNextMarkers(' + startPos + ')" value="&gt;&gt;"/></td>';
		}
		_str +=	'</tr></table>';
		// show previous / next table under the list
		document.getElementById(sidebarID + "ListControlContainer").innerHTML = _str;
	} else {
		// remove container
		if ( document.getElementById(sidebarID + "ListControlContainer") ) {
			document.getElementById(sidebarID).removeChild(document.getElementById(sidebarID + "ListControlContainer"));
		}
	}
}

// if a marker is already loaded, then do not load again... check here..
function checkInArray(marker) {
	var result = false
	for (var i=0; i<aMarkers.length; i++) {
		if (aMarkers[i].getLatLng().toString() == marker.getLatLng().toString()) {
			if (allowDuplicateMarkers == false) {
				result = true
			}
			break
		}
	}
	return result
}

// create the actual marker and open the info box on click
function createMarker(xmlMarker, iconUrl, hiliteIconUrl) {
	var coordinates = xmlMarker.getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;
	var aCoordinates = coordinates.split(",");
	var point = new GLatLng(aCoordinates[0], aCoordinates[1]);
	var icon = setOrGetIcon(iconUrl);
	var marker = new GMarker(point, icon);
	marker.value = xmlMarker.getElementsByTagName("name")[0].childNodes[0].nodeValue;
	marker.sidebar = xmlMarker.getElementsByTagName("sidebar")[0].childNodes[0].nodeValue;
	marker.description = xmlMarker.getElementsByTagName("description")[0].childNodes[0].nodeValue;
	marker.orignalIconUrl = iconUrl;
	marker.hiliteIconUrl = hiliteIconUrl;
	GEvent.addListener(marker, "click", function() {
		var markerPosOnPage = getMarkerPosOnPage(this)
		showCustomInfobox(this, markerPosOnPage.x, markerPosOnPage.y)
	});
	if (onMouseOverMarkerShowInfobox) {
		GEvent.addListener(marker, "mouseover", function(){
			var markerPosOnPage = getMarkerPosOnPage(this)
			delayedShowCustomInfobox(this, markerPosOnPage.x, markerPosOnPage.y)
		});
	}
	GEvent.addListener(marker, "mouseout", function() {
		if (infoboxTimeoutID != null) {
			clearTimeout(infoboxTimeoutID);
			infoboxTimeoutID = null;
		}
	});
	return marker
}

function getMarkerPosOnPage(oMarker) {
	var markerPosOnMap = map.fromLatLngToContainerPixel(oMarker.getLatLng())
	var obj = document.getElementById(canvasID)
	var posx = 0
	var posy = 0
	// get position of map on page
	if (obj.offsetParent) {
		posx = obj.offsetLeft
		posy = obj.offsetTop
		while (obj = obj.offsetParent) {
			posx += obj.offsetLeft
			posy += obj.offsetTop
		}
	}
	var oPosOnPage = new Object()
	oPosOnPage.x = (posx + markerPosOnMap.x)
	oPosOnPage.y = (posy + markerPosOnMap.y)
	// posx and posy contain the object position relative to the document
	return oPosOnPage
}

// set the icon for the current marker
function setOrGetIcon(iconUrl) {
	var icon = getIcon(iconUrl);
	if (getIcon(iconUrl) == null) {
		icon = setIcon(iconUrl)
	}
	return icon
}

function getIcon(iconUrl) {
	var icon = null
	for (var i=0; i<aIcons.length; i++) {
		if (aIcons[i].image == iconUrl) {
			icon = aIcons[i]
			break
		}
	}
	return icon
}

function setIcon(iconUrl) {
	var tmpImg = new Image();
	tmpImg.src = iconUrl;
	// set onload event
	tmpImg.onload = function() {
		// create icon
		var icon = new GIcon();
		icon.image = iconUrl;
		icon.iconSize = new GSize(this.width, this.height); 
		if(window.anchorPointY == undefined && window.anchorPointX == undefined){
			icon.iconAnchor = new GPoint(Math.round(this.width / 2), this.height);
		}else{
			icon.iconAnchor = new GPoint(window.anchorPointX, window.anchorPointY);
		}
		icon.infoWindowAnchor = new GPoint(5, 1);
		// overwrite icon
		for (var i=0; i<aIcons.length; i++) {
			if (aIcons[i].image == this.src) {
				aIcons[i] = icon
				break
			}
		}
	}
	// create icon
	var icon = new GIcon();
	icon.image = iconUrl;
	if(window.anchorPointY == undefined && window.anchorPointX == undefined){
		icon.iconAnchor = new GPoint(Math.round(tmpImg.width / 2), tmpImg.height);
	}else{
		icon.iconAnchor = new GPoint(window.anchorPointX, window.anchorPointY);
	}
	icon.infoWindowAnchor = new GPoint(5, 1); 
	
	if(tmpImg.width == 0 || tmpImg.height == 0){
		icon.iconSize = new GSize(defaultMarkerWidth,defaultMarkerHeight);
	}else{
		// the line below sometimes gives a size of 0 by 0
		icon.iconSize = new GSize(tmpImg.width, tmpImg.height);
	}
	
	// add icon to array
	aIcons.push(icon)
	// return icon
	return icon
}

// find geocode of the address that was entered
function getGeoByAddressAndLoadPointers(address) {
	gm.initialSearch = false
	// if sidebar
	if (gm.withList == true) {
		// cleanup sidebar			
		cleanupSideBarItems();
	}
	// if no address specified use current
	if (address.length == 0){
		geocoder.getLocations(gm.defaultAddress, setZoomAndLoadPointers);
	} else {
		geocoder.getLocations(address, setZoomAndLoadPointers);		
	}
}
// set the zoom level according to a given address at function 'getGeoByAddress()'
function setZoomAndLoadPointers(response) {
	if (!response || response.Status.code != 200) {
		alert("Sorry, we cannot find that address");
	} else {
		place = response.Placemark[0];
		var viewport = new GLatLngBounds;
		viewport.extend(new GLatLng(place.ExtendedData.LatLonBox.south, place.ExtendedData.LatLonBox.west));
		viewport.extend(new GLatLng(place.ExtendedData.LatLonBox.north, place.ExtendedData.LatLonBox.east));		
		// center on address
		map.setCenter(viewport.getCenter(), (map.getBoundsZoomLevel(viewport) + viewportZoom));
	}
}

function onClickMoreInfo(url) {
	// calculate current viewport
	var bounds = map.getBounds();
	// create url param to recreate last setting of viewport center|zoom|aListStartPos|arrayIndex|initialSearch|defaultAddress|additionalSearchCriteria
	var gmRef = bounds.getCenter().toUrlValue() + "|" + map.getZoom() + "|" + aListStartPos.toString() + "|" + arrayIndex + "|" + gm.initialSearch + "|" + gm.defaultAddress + "|" + additionalSearchCriteria;
	// redirect to details page
	document.location.href = (url.split("?").length > 1) ? (url + "&gmRef=" + gmRef) : (url + "?gmRef=" + gmRef);
}

function restoreMap() {
	// set isRestore to true
	isRestore = true
	// sVars is of format center|zoom|aListStartPos|arrayIndex|initialSearch|defaultAddress|additionalSearchCriteria
	var aVars = startupVars.split("|")
	// set zoom
	gm.defaultZoom = parseInt(aVars[1])
	// set initialSearch
	gm.initialSearch = (aVars[4] == "true") ? true : false
	// set defaultAddress
	gm.defaultAddress = aVars[5]
	// set extra search criteria
	if (aVars[6].length > 0 && gm.additionalSearchCriteria != aVars[6]) {
		// set search criteria
		gm.additionalSearchCriteria = aVars[6];
	}
	// set center of the map
	gm.defaultCenterPoint = GLatLng.fromUrlValue(aVars[0]);
	// initialize map
	gm.initializeMap();
}
function restoreMapMarkersLoaded() {
	// set isRestore to true
	isRestore = false
	// sVars is of format center|zoom|aListStartPos|arrayIndex|initialSearch|defaultAddress|additionalSearchCriteria
	var aVars = startupVars.split("|")
	// set aListStartPos
	aListStartPos = aVars[2].split(",")
	// set arrayIndex
	arrayIndex = parseInt(aVars[3])
	// display correct marker list
	setMarkers(aListStartPos[arrayIndex]);
}

function resetMap() {
	// hide infobox
	hideCustomInfobox();
	// cleanup current marker array
	aMarkers = new Array();
	// cleanup markers on map array
	aMarkersOnMap = new Array();
	// cleanup sidebar
	if (gm.withList == true) {
		cleanupSideBarItems();
	}
	// cleanup markers displayed currently on map
	mgr.clearMarkers();
	// restore map center
	setDefaultMapCenter();
}

function isIE6OrLess() {
	var aUserAgent = navigator.userAgent.toLowerCase().split(";");
	for (var i=0; i<aUserAgent.length; i++){
		if (aUserAgent[i].indexOf("msie") != -1) {
			var aVersion = aUserAgent[i].replace(/^\s+|\s+$/g,"").split(" ");
			for (var j=1; j<aVersion.length; j++) {
				if ( parseFloat(aVersion[j]) <= 6 ) {
					return true
				}
			}
			break
		}
	}
	return false
}

function onGPageLoaded() {
	// set IE6 or less
	IE6orLess = isIE6OrLess();
	// create geocoder
	geocoder = new GClientGeocoder();
	// create map
	gm = new GoogleMap();
	// need to restore map
	if (typeof(startupVars) != "undefined") {
		restoreMap();
	} else {
		// get default map center and initialize map
		setDefaultMapCenter();
	}
}

function showDebugInfo(lastArrayPos) {
	if (!document.getElementById("debugInfoContainer")) {
		var _debugInfoDiv = document.createElement("div")
		_debugInfoDiv.id = "debugInfoContainer"
		_debugInfoDiv.style.textAlign = "left"
		document.body.appendChild(_debugInfoDiv)
	}
	var oContainer = document.getElementById("debugInfoContainer")
	// reset content
	oContainer.innerHTML = "<strong>Variables</strong>"
	
	oContainer.innerHTML += "<br/>aMarkers.length: " + aMarkers.length
	oContainer.innerHTML += "<br/>aMarkersOnMap.length: " + aMarkersOnMap.length
	oContainer.innerHTML += "<br/>aListStartPos.length:" + aListStartPos.length
	oContainer.innerHTML += "<br/>lastArrayPos:" + lastArrayPos
	oContainer.innerHTML += "<br/>arrayIndex:" + arrayIndex
	
	oContainer.innerHTML += "<br/><br/><strong>aListStartPos</strong>"
	for (var i=0; i<aListStartPos.length; i++) {
		oContainer.innerHTML += "<br/>" + i + ": " + aListStartPos[i];
	}
	
	oContainer.innerHTML += "<br/><br/><strong>aMarkers</strong>"
	for (var j=0; j<aMarkers.length; j++) {
		oContainer.innerHTML += "<br/>" + j + ": " + aMarkers[j].value;	
	}
}

// add onload event
if( typeof(window.addEventListener) == "function" )	{ window.addEventListener("load", onGPageLoaded, false) } else if( typeof(window.attachEvent) == "object" ) { window.attachEvent("onload", onGPageLoaded) }
// add onunload event
if( typeof(window.addEventListener) == "function" )	{ window.addEventListener('unload', GUnload, false) } else if( typeof(window.attachEvent) == "object" ) { window.attachEvent("onunload", GUnload) }
