
var map = null;
var geocoder = null;
var bikeMarkerOptions = null;
var tooltip = document.createElement("div");
tooltip.style.visibility = "hidden";
var gmarkers = [];
var htmls = [];
var j = 0;

var countryName = "";
var countryCode = "";
var areaName = "";
var subAreaName = "";
var localityName = "";
var point;

//A function to create the marker and set up the event window
function createMarker(point, name, html) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

// == creates a Tour marker
function createTourMarker(point, name, html) {
	var marker = new GMarker(point, bikeMarkerOptions);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

// A function to create the marker and set up the event window
function createTourMarkerWithTooltip(point, name, html) {
  var marker = new GMarker(point, bikeMarkerOptions);
  // === store the name so that the tooltip function can use it ===
  marker.tooltip = '<div class="tooltip"><nobr>'+name+'<\/nobr><br>Click for more...<\/div>';
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
  });

  //  ======  The new marker "mouseover" and "mouseout" listeners  ======
  GEvent.addListener(marker,"mouseover", function() {
    showTooltip(marker);
  });        
  GEvent.addListener(marker,"mouseout", function() {
	tooltip.style.visibility="hidden"
  });
  return marker;
}

// ====== This function displays the tooltip ======
// it can be called from an icon mousover
function showTooltip(marker) {
	tooltip.innerHTML = marker.tooltip;
	var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0, 0), true), map.getZoom());
	var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(), map.getZoom());
	var anchor = marker.getIcon().iconAnchor;
	var width = marker.getIcon().iconSize.width;
	var height = tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y - anchor.y - height));
	pos.apply(tooltip);
	tooltip.style.visibility = "visible";
}

function processHomeMap(doc, status) {
	if (status == "200") {
		/*
		 * The Home map is stored like:
		 * {"name":"home","title":"Bicycle Tours Around the World", "tours":[
		 * {"days":0,"image":"","lat":0,"link":"/tours/areamap.htm?name=vt-usa","lon":0,"longDescription":"","rentalAvailable":false,"shortDescription":"There are 3 tours.","tags":[],"title":"VT,USA","tourLevel":""},
		 * {"days":0,"image":"","lat":0,"link":"/tours/areamap.htm?name=tuscany-italy","lon":0,"longDescription":"","rentalAvailable":false,"shortDescription":"There are 1 tours.","tags":[],"title":"Tuscany,Italy","tourLevel":""}
		 * ]}
		 */
		var json = eval('(' + doc + ')');
		var latlngbounds = new GLatLngBounds();
		for ( var i = 0; i < json.tours.length; i++) {
			var point = new GLatLng(json.tours[i].lat, json.tours[i].lon);
			var hover = json.tours[i].title + "<br>" + json.tours[i].shortDescription;
			var html = "<p>" + json.tours[i].title + "<br>" + json.tours[i].shortDescription + "<br><a class='bodylink' href='" + json.tours[i].link + "'>See map...</a></p>";
			// var marker = createTourMarker(point, json.tours[i].title, html);
			var marker = createTourMarkerWithTooltip(point, hover, html);
			latlngbounds.extend(point);
			map.addOverlay(marker);
			// marker.openInfoWindowHtml(html);
		}
		map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));		
	} else {
		alert("We couldn't find any tours recorded there. Sorry.");
		map.setCenter(new GLatLng(30, 8), 2); // the whole world
	}
}

function processMap(doc, status) {
	if (status == "200") {
		/*
		 * A map is stored like:
		 * {"name":"vt-usa","title":"VT,USA", "tours":[
		 *   {"days":0,"image":"","lat":0,"link":"/xxx","lon":0,"rentalAvailable":false,"shortDescription":"There are 3 tours.","tags":[],"title":"VT,USA","tourLevel":""},
		 * ]}
		 */
		var json = eval('(' + doc + ')');
		var latlngbounds = new GLatLngBounds();
		for ( var i = 0; i < json.tours.length; i++) {
			var point = new GLatLng(json.tours[i].lat, json.tours[i].lon);
			var hover = json.tours[i].title + "<br>" + json.tours[i].shortDescription;
			var tourhref = "/tour/"+json.tours[i].operatorLinkName+"/"+json.tours[i].linkName+".htm";
			var ophref = "/operators/"+json.tours[i].operatorLinkName+".htm";
			var html = "<div class='infowindow'><table border=0 class='iwtable'>" + 
			"<tr><td class='iwdef'>Tour:</td><td><a href='"+tourhref+"'>"+json.tours[i].title+"</a></td></tr>" +
			"<tr><td class='iwdef'>From:</td><td><a href='"+ophref+"'>"+json.tours[i].operatorName+"</a></td></tr>" +
			"<tr><td class='iwdef'>Days:</td><td>" + json.tours[i].days + "</td></tr>" +  
			"<tr><td class='iwdef'>Summary:</td><td>" + json.tours[i].shortDescription + "</td></tr>" + 
			"<tr><td></td><td><a href='"+ tourhref + "'>Details...</a></td></tr>" + 
			"</table></div>";

			// var marker = createTourMarker(point, json.tours[i].title, html);
			var marker = createTourMarkerWithTooltip(point, hover, html);
			latlngbounds.extend(point);
			map.addOverlay(marker);
			// marker.openInfoWindowHtml(html);
		}
		map.setCenter(latlngbounds.getCenter(), Math.min(6,map.getBoundsZoomLevel(latlngbounds)));		
	} else {
		notours();
	}
}

function uninitialize() {
	GUnload();
}

function showAddress(address) {
	if (geocoder) {
		// geocodeToPoint(address);
		geocodeToLocations(address)
	}
}

function geocodeToPoint(address) {
	geocoder.getLatLng(address, function(point) {
		if (!point) {
			alert(address + " not found");
		} else {
			map.setCenter(point, 6);			
		} // if
		} // function
	);
}

function geocodeToLocations(address) {
	var reasons = [];
	reasons[G_GEO_SUCCESS] = "Success";
	reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address: No corresponding geographic location could be found for the specified address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS] = "Unavailable Address: The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be successfully processed.";
	geocoder.getLocations(address, function(result) {
				if (result.Status.code == G_GEO_SUCCESS) {
					var place = result.Placemark[0];
					var p = place.Point.coordinates;
					// ===== Get the bounding box of the first result =====
					var N = place.ExtendedData.LatLonBox.north;
					var S = place.ExtendedData.LatLonBox.south;
					var E = place.ExtendedData.LatLonBox.east;
					var W = place.ExtendedData.LatLonBox.west;
					var bounds = new GLatLngBounds(new GLatLng(S, W), new GLatLng(N, E));
					// Choose a zoom level that fits
					var zoom = map.getBoundsZoomLevel(bounds);

					countryName = place.AddressDetails.Country.CountryName;
					countryCode = place.AddressDetails.Country.CountryNameCode;
					areaName = "";
					subAreaName = "";
					localityName = "";
					try {
						var area = place.AddressDetails.Country.AdministrativeArea;
						if (String(area) != "undefined") {
							areaName = area.AdministrativeAreaName;
							var subarea = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea;
							if (String(subarea) == "undefined") {
								// note: it's possible for there to be an area but no locality (e.g. Tuscany)
								localityName = area.Locality.LocalityName;
							} else {
								subAreaName = subarea.SubAdministrativeAreaName;
								localityName = subarea.Locality.LocalityName;
							}
						}
					} catch (x) {
					}
					// alert("lat:"+p[1]+" lon:"+p[0]);
					// map.setCenter(p, 11);
					map.setCenter(bounds.getCenter(), zoom);
					point = new GLatLng(p[1], p[0]);
					// window.open('/tours/areamap.htm?name='+getAreaName(areaName, countryName),'_self');
					window.open('/tours/'+getAreaName(areaName, countryName)+'.htm','_self');
					// alert(getAreaName(areaName, countryName));
				} else {
					// ====== Decode the error status ======
					var reason = "Code " + result.Status.code;
					if (reasons[result.Status.code]) {
						reason = reasons[result.Status.code]
					}
					alert('Could not find "' + address + '" ' + reason);
				}
			});
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function addUnLoadEvent(func) {
	var oldunload = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = func;
	} else {
		window.onunload = function() {
			oldunload();
			func();
		}
	}
}

addUnLoadEvent(uninitialize);

function getAreaName(areaName, countryName) {
	if (areaName != null && areaName.length > 0 ) {
		areaName = areaName.toLowerCase().replace(/ /gi, "-");
		areaName += "-";
	} else {
		areaName = "";
	}
	countryName = countryName.toLowerCase().replace(/ /gi, "-");
	return areaName + countryName;
}

function getParameter(parameterName) {
	var queryString = location.search;
	// alert("query=" + queryString);
	// Add "=" to the parameter name (i.e. parameterName=value)
	var parameterName = parameterName + "=";
	if (queryString.length > 0) {
		var begin = queryString.indexOf(parameterName);
		// If the parameter name is not found, skip it, otherwise return the value
		if (begin != -1) {
			begin += parameterName.length;
			// look for end or next "&" sign
			var end = queryString.indexOf("&", begin);
			if (end == -1) {
				end = queryString.length
			}
			// Return the string
			return unescape(queryString.substring(begin, end));
		}
		// Return "" if no parameter has been found
	}
	return "";
}
