// Init the Debug object
mapDebug = Object();
mapDebug['fail'] = Array();
mapDebug['success'] = Array();

// Simple (simplistic?) function to hide email addresses from spammers
function setLink(sDom, sUser) {
	document.write("<a href=\"");
	document.write("ma");
	document.write("ilt");
	document.write("o:" + sUser);
	document.write("@");
	document.write(sDom.replace(/%23/g, ".") + "\">");
	document.write(sUser);
	document.write("@");
	document.write(sDom.replace(/%23/g, "."));
	document.write("</a>");
  return;
}

function clearGeoCache(rvals) {
	alert("Cleared: "+rvals.cleared+" cached geo codes.");
}
// Sajax function for getting listings
function getListings(rvals) 
{
	var elapsed = new Date();
	if ( rvals.error ) {
		alert(rvals.error);
	} else if ( rvals.numrows ) {
		map.clearOverlays();

		var oMarker;
		var s = "";
		for ( var ID in rvals.listings ) {
			oMarker = getMarker(rvals.listings[ID]);
			markAddress(oMarker.point, oMarker.label);
		}
		writeMessage(rvals.mapped + " listings found");
	} else {
		map.clearOverlays();
		writeMessage('No matching listings found.');
	}

	var parms = parseQuery();
	if (parms['debug'] || rvals.debug) {
		elapsed = (new Date() - elapsed) / 1000;
		var total = (new Date() - startTime) / 1000;
		var rate = total / rvals.mapped;
		var sTiming = rvals.mapped + " listings mapped\n";
		
		sTiming += "\nQuery Time: " + rvals.qtime;
		sTiming += "\nLoop Time: " + rvals.ltime;
		
		sTiming += "\n- getgeodata: " + rvals.getgeodata;
		sTiming += "\n- savegeodata: " + rvals.savegeodata;
		sTiming += "\n- convertFmRecord2Obj: " + rvals.convertFmRecord2Obj;
		sTiming += "\n- saveFailedAddresses: " + rvals.saveFailedAddresses;
		
		sTiming += "\nTotal php Time: " + rvals.time;
		sTiming += "\nTotal javascript Time: " + elapsed;
		
		sTiming += "\nTotal Time to Map: " + total;
		sTiming += "\nTime/Listing: " + rate;
		if (rvals.mapped != rvals.numrows) {
			sTiming += "\n\nNote:\n  "+rvals.numrows+" records TOTAL";
			sTiming += "\n  "+rvals.unmapped+" addresses NOT FOUND by Google";
			sTiming += "\n  "+rvals.nulladdress+" records with NULL addresses.";
		}
		alert( sTiming );
	}
	return false;
}

// Display a popup window with location details
function showDetails(id, width) {
	var features = Array();
	if (!width) {
		width = 600;
	}
	features.push('width='+width);
	features.push('height=600');
	features.push('resizable=yes');
	features.push('location=no');
	features.push('menubar=no');
	features.push('status=yes');
	features.push('toolbar=no');
	features.push('scrollbars=yes');

	var query = Array();
	query.push("id=" + id);

	var parms = parseQuery();
	if (parms['debug']) {
		query.push('debug=' + parms['debug']);
	}
	if (memberSearch) {
		query.push('isMember=1');
	}
	var child = window.open(googleMapsRoot+"detail.php?" + query.join('&'), "listing"+id, features.join(","));
	child.focus();
}

// Get address and label for map marker
function getMarker(oLoc) {
	var oRet = Object();

	oRet.point = new GLatLng(oLoc.Latitude, oLoc.Longitude);

	oRet.label = '<div id="gmwidget_mapBubble">';
	//if ( oLoc.ImageName ) { oRet.label += '<img src="'+oLoc.ImageName+'" alt="" />'; }
	if ( oLoc.TourCancelled ) { oRet.label += "<p class=\"tourcanceled\">This location\'s tour has been canceled.</p>"; }
	if ( oLoc.Organization ) { oRet.label += "<p>" + oLoc.Organization + "</p>"; }
	if ( oLoc.Name ) {	oRet.label += "<p>" + oLoc.Name + "</p>"; }
	if ( oLoc.Address1 ) { oRet.label += "<p>" + oLoc.Address1 + "</p>"; }
	if ( oLoc.Address2 ) { oRet.label += "<p>" + oLoc.Address2 + "</p>"; }
	if ( oLoc.City + oLoc.State + oLoc.Zip ) {
		oRet.label += "<p>";
		if ( oLoc.City ) {	oRet.label += oLoc.City; }
		if ( oLoc.City && oLoc.State ) { oRet.label += ", "; }
		if ( oLoc.State ) { oRet.label += oLoc.State; }
		if ( (oLoc.City || oLoc.State) && oLoc.Zip ) { oRet.label += " "; }
		if ( oLoc.Zip ) { oRet.label += oLoc.Zip; }
		if ( oLoc.HomePhone ) { oRet.label += "<p>Phone: " + oLoc.HomePhone + "</p>"; }
		oRet.label += "</p>";
	}
	//if ( oLoc.Phone ) { oRet.label += "<p>" + oLoc.Phone + "</p>"; }
	oRet.label += '<p><a href="." onclick="showDetails(' + oLoc.ID + ');return false;">More</a></p>';
	oRet.label += "</div>";
	return oRet;
}
// Parse the query string
function parseQuery() {
	var oReturn = new Object();
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	var aParm;
	for (var i=0; i<parms.length; i++) {
		aParm = parms[i].split('=');
		oReturn[aParm[0]] = aParm[1];
	}
	return oReturn;
}

// Append text to debug message area
function debugMessage(cDebug) {
	if ( mapDebug[cDebug] ) {
		var cText = mapDebug[cDebug].join("\n");
		alert(mapDebug[cDebug].length + " entries\n\n" + cText);
	}
	return false;
}
														 
/************************************************************************************/
/* Google map functions                                                             */
/************************************************************************************/
var map;
var geocoder;

function markAddress(oPoint, cLabel) {
	if ( oPoint ) {
		var oMarker = new GMarker(oPoint);
		map.addOverlay(oMarker);
		GEvent.addListener(oMarker, "click", function() { oMarker.openInfoWindowHtml(cLabel);	});
	}
}

function moveCenter(cAddress, nScale) {
	geocoder.getLatLng(
		cAddress,
		function(point) {
			if (!point) {
				alert(cAddress + " not found");
			} else if ( nScale ) {
					map.setCenter(point, nScale);
			} else {
				map.setCenter(point);
			}
		}
	);
}

function load(cMap, cAddress, nScale) {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById(cMap));

		// for address to long/lat lookups
    geocoder = new GClientGeocoder();

    // add map controls
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());

		if ( cAddress ) {
			if ( !nScale ) { nScale = 14; }
			moveCenter(cAddress, nScale);
		}
  }
}

function writeMessage(sString) {
	var oMessage = document.getElementById('gmwidget_resultMessage');
	if ( oMessage && oMessage.innerHTML ) {
		oMessage.innerHTML = sString;
	}
}
