
var map;
var edfFeed;
var geocoder = new GClientGeocoder();
var httpRequest;
var bounds = new GLatLngBounds();

function remove_phantom_nodes(xml){
	if(xml.nodeType != 8){
		for(var i = xml.childNodes.length-1; i >= 0; i--){
			var obj = xml.childNodes[i];
			//not valid xml if contains both text and non-text nodes, remove text nodes (Gecko-based browsers will have this)
			if(obj.nodeType == 3 && containsOnlyWhitespace(escape(obj.nodeValue)))
				xml.removeChild(obj);
			else{
				remove_phantom_nodes(obj);}
		}
	}
}

function containsOnlyWhitespace(string){
	var re1 = new RegExp(/%0A/);
	var re2 = new RegExp(/%09/);
	var re3 = new RegExp(/%20/);
	var m;
	while(m = re1.exec(string))
		string = string.replace(string.substring(m.index,m.index+3),'');
	while(m = re2.exec(string))
		string = string.replace(string.substring(m.index,m.index+3),'');
	while(m = re3.exec(string))
		string = string.replace(string.substring(m.index,m.index+3),'');
	return string.length == 0;
}

function loadmap(edfID){
    // set up the map
    var lat = 41.941356;
	var long2 = -83.405082;
	var zoom = 10;
    map = new GMap2(document.getElementById("map"));
    var locale = new GLatLng(lat, long2);
    map.addControl(new GSmallMapControl());
    map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 20)));
    map.setCenter(locale, zoom);

    // load properties from edf
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    httpRequest.onreadystatechange = function(){
        loadEDFMap();
    };
    //httpRequest.open('GET', 'http://www.emerciv.com/em/edfrequest/init/'+edfID+'.html', true); LIVE VERSION
    httpRequest.open('GET', 'loadedf.php?q='+edfID, true);
    httpRequest.send(null);

}

function loadEDFMap(){
    if (httpRequest.readyState == 4) {
        edfFeed = httpRequest.responseXML;
        // get the local data root
        var xml = edfFeed.getElementsByTagName('xml')[0];
		remove_phantom_nodes(xml);
        for(var i = 0; i < xml.childNodes.length; i++){
			try{
				if(xml.childNodes[i].tagName == 'item'){
					if(xml.childNodes[i].childNodes[0].childNodes[0].tagName == "image"){
						var image = xml.childNodes[i].childNodes[0].childNodes[0].childNodes[0].firstChild.nodeValue;
					}else{
						image = null;
					}
					var textNodes = xml.childNodes[i].getElementsByTagName('text');
					var address = textNodes[0].firstChild.nodeValue;
					var desc = textNodes[1].firstChild.nodeValue;
					addToMap(address, image, desc);
				}
			} catch(e){}
        }
    }
}

function addToMap(address, imgsrc, desc){
    // create markers
	var icon = new GIcon();
	icon.image = "images/house_icon_sm.png";
	icon.shadow = "images/houseshadow.png";
	icon.iconSize = new GSize(24, 24);
	icon.shadowSize = new GSize(48, 24);
	icon.iconAnchor = new GPoint(12, 24);
	icon.infoWindowAnchor = new GPoint(12, 0);
	
    // add a location to the map
    var address2 = address;
    geocoder.getLatLng(
    address2,
    function(point) {
      if (point) {
        var marker = new GMarker(point, icon);
        bounds.extend(point);
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml("<div class='mapdetail'><img src='"+imgsrc+"' style='float:left;padding-right: 5px; width:120px;'/><strong>"+address+'</strong><br/>'+desc+'<br /><a href="#directionsform" onclick="showDirections(\''+address+'\'); fade(\'directionsform\', 0, 100, 1000); return false;">Get Directions to this Property</a></div>');
        });
        map.addOverlay(marker);
        resetMapView();
      }
    }
  );
}

function resetMapView(){
    var center = bounds.getCenter();
    var newZoom = map.getBoundsZoomLevel(bounds) - 1;
      if (map.getZoom() != newZoom) {

            map.setCenter(center, newZoom);
      } else {
            map.panTo(center);
      } 
    
}

function showDirections(address){
	if(document.getElementById('directionsform').className == "hide"){
		document.getElementById('directionsform').className = "";
	}
	document.requestdirections.toaddress.value = address;
}

//This redraws the map with directions when somebody requests them
function getDirections(toAddress, fromAddress){
	var directionsPanel = document.getElementById("directions");
	directionsPanel.innerHTML = '<a href="index.php" onclick="closeDirections(\'69643d323837\'); return false;" style="float:right;"><img src="images/X.png" alt="Close Directions" title="Close Directions" /></a><br />';
	directionsPanel.className = '';
	var directions = new GDirections(map, directionsPanel);
	var addresses = fromAddress+" to "+toAddress;
 	directions.load(addresses);
	map.addControl(new GSmallMapControl());
	map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 20)));
	document.getElementById('directionsform').className = "hide";
}


function closeDirections(edfId){
	loadmap(edfId);
	document.getElementById('directions').className = 'hide';
}