var maps = new Array(10);
var geos = new Array(10);

function clearMaps()
{
	for(var i = 0; i < 10; i++) {
		maps[i] = null;
		geos[i] = null;
	}
}

var isGBCompatible = GBrowserIsCompatible();
if (isGBCompatible) {

	clearMaps();
	var reasons=[];

    // ===== list of words to be standardized =====
    var standards = [   ["road","rd"],
                        ["street","st"],
                        ["avenue","ave"],
                        ["av","ave"],
                        ["drive","dr"],
                        ["saint","st"],
                        ["north","n"],
                        ["south","s"],
                        ["east","e"],
                        ["west","w"],
                        ["expressway","expy"],
                        ["parkway","pkwy"],
                        ["terrace","ter"],
                        ["turnpike","tpke"],
                        ["highway","hwy"],
                        ["lane","ln"]
                     ];

}

// ===== convert words to standard versions =====
function standardize(a) {
	for (var i=0; i<standards.length; i++) {
        if (a == standards[i][0])  {a = standards[i][1];}
    }
    return a;
}

// ===== check if two addresses are sufficiently different =====
function different(a,b) {
// only interested in the bit before the first comma in the reply
	var c = b.split(",");
	b = c[0];
	// convert to lower case
	a = a.toLowerCase();
	b = b.toLowerCase();
	// remove apostrophies
	a = a.replace(/'/g , "");
	b = b.replace(/'/g , "");
	// replace all other punctuation with spaces
	a = a.replace(/\W/g, " ");
	b = b.replace(/\W/g, " ");
	// replace all multiple spaces with a single space
	a = a.replace(/\s+/g, " ");
	b = b.replace(/\s+/g, " ");
	// split into words
	awords = a.split(" ");
	bwords = b.split(" ");
	// perform the comparison
	var reply = false;
	for (var i=0; i<bwords.length; i++) {
		//GLog.write (standardize(awords[i])+"  "+standardize(bwords[i]))
		if (standardize(awords[i]) != standardize(bwords[i])) {reply = true}
	}
	//GLog.write(reply);
	return (reply);
}

function load() {
	// ====== Array for decoding the failure codes ======
	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.";
}

function loadMap(id, type) {
	maps[id] = new GMap2(document.getElementById("map" + id));
	if (type == 0) {
		maps[id].addControl(new GSmallZoomControl());
	} else {
		maps[id].addControl(new GLargeMapControl());
		maps[id].addControl(new GMapTypeControl());
	}
	maps[id].setCenter(new GLatLng(20,0),2);
	// ====== Create a Client Geocoder ======
	geos[id] = new GClientGeocoder();
	// ====== Array for decoding the failure codes ======
}

// ====== Plot a marker after positive reponse to "did you mean" ======
function place(id, point, scale, markerI, onClick, onOver, onOut) {
    var blueIcon = new GIcon(G_DEFAULT_ICON);
	if (scale > 0) {
		maps[id].setCenter(point, scale);
	}
	switch(markerI) {
		case 0:
		break;
		case 1:
			marker = new GMarker(point);
			maps[id].addOverlay(marker);
			//return marker.getId();
		break;
		case 2:
		    blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
			markerOptions = { icon:blueIcon };
			var marker = new BpMarkerLight(point, markerOptions);
			maps[id].addOverlay(marker);
			return marker.getId();
		break;
		default:
		    blueIcon.shadowSize = new GSize(0,0);

		    blueIcon.image = markerI;
			markerOptions = { icon:blueIcon };
			var marker = new BpMarkerLight(point, markerOptions);
			maps[id].addOverlay(marker);
		    var target = marker.getEventTarget();
    	    GEvent.bindDom(target,'click',marker, onClick);
		    GEvent.bindDom(target,'mouseover',marker, onOver);
    		GEvent.bindDom(target,'mouseout', marker, onOut);
    		marker.setTooltip(label);
			return marker.getId();
		break;
	}
	return -1;
}

// ====== Geocoding ======
function showAddress(id, search, scale, marker) {
	//alert(search);
// ====== Perform the Geocoding ======
	geos[id].getLocations(search, function (result)
	{
		if (scale > 0) {
		  	maps[id].clearOverlays();
		}
		if (result.Status.code == G_GEO_SUCCESS) {
			// ===== If there was more than one result, "ask did you mean" on them all =====
			if (result.Placemark.length > 1) {
				if (scale > 0 && defaultMap != '') {
					document.getElementById("map" + id).innerHTML = defaultMap;
				}
			} else { // ===== If there was a single marker, is the returned address significantly different =====
				var p = result.Placemark[0].Point.coordinates;
                place(id, new GLatLng(p[1], p[0]), scale, marker, null, null);
            }
		} else { // ====== Decode the error status ======
			var reason="Code "+result.Status.code;
			if (reasons[result.Status.code]) {
            	reason = reasons[result.Status.code]
			}
			if (scale > 0 && defaultMap != '') {
				document.getElementById("map" + id).innerHTML = defaultMap;
			}
		}
	});
}

function showPolygon(t)
{
	d = [];
	var min1 = t[0], min2 = t[1], max1 = t[0], max2 = t[1];
	for (var i = 0; i < t.length / 2; i++)
	{
		d.push(new GLatLng(t[i * 2], t[i * 2 + 1]));
		if (min1 > t[i * 2])
			min1 = t[i * 2];
		if (max1 < t[i * 2])
			max1 = t[i * 2];
		if (min2 < t[i * 2 + 1])
			min2 = t[i * 2 + 1];
		if (max2 > t[i * 2 + 1])
			max2 = t[i * 2 + 1];
	}
	d.push(new GLatLng(t[0], t[1]));
	place(0, new GLatLng((parseFloat(min1) + parseFloat(max1)) / 2, (parseFloat(min2) + parseFloat(max2)) / 2),
			maps[0].getBoundsZoomLevel(new GLatLngBounds(new GLatLng(min1, min2), new GLatLng(max1, max2))),
			0, null, null, null);
	var polygon = new GPolygon(d, null, 2, 0.4, "#aaaaff", 0.2 );
	maps[0].addOverlay(polygon);
}

