NMap = []; // Custom map namespace
NMap.map; // Global GMap object
NMap.initZoom = 4;
NMap.step = typeof(initStep) != "undefined" ? initStep : 'states'; // states, counties, places, neghborhoods
NMap.state = typeof(initState) != "undefined" ? initState : "";
NMap.county = typeof(initCounty) != "undefined" ? initCounty : "";
//NMap.place = typeof(initPlaces) != "undefined" ? initPlace : "";
NMap.neighborhood = typeof(initNeighborhood) != "undefined" ? initNeighborhood : "";
NMap.loading = false;
NMap.isBackStep = false;
NMap.overlay = false; // nighborhoods overlay
NMap.addrMarker = false; // address marker
NMap.hoverIndex = -1;
NMap.selectedIndex = -1;
NMap.init = function() {
  if (!GBrowserIsCompatible()) return;

  NMap.map = new GMap2($("map"));
  NMap.map.addControl(new GLargeMapControl());
  NMap.map.setCenter(new GLatLng(40.731711, -73.987715), NMap.initZoom); // NY
  //NMap.resize(); // ???
  //NMap.map.setCenter(new GLatLng(40.731711, -73.987715), NMap.initZoom); //
  NMap.overlay = new AreasOverlay(areas);
  NMap.abox = AddressBox;
  //NMap.map.addOverlay(quotesOverlay);
  NMap.map.addOverlay(NMap.overlay);
  NMap.map.addControl(NMap.abox);
  NMap.abox.hide();

  //adding listeners 
  GEvent.addListener(NMap.map, "mousemove", NMap.onMouseMove);
  GEvent.addListener(NMap.map, "click", NMap.onClick);
  GEvent.addListener(NMap.map, "zoomend", function() { NMap.overlay.redraw(true); });//alert(NMap.map.getZoom()); });
  
  NMap.setBackLink();
  /*
  if (window.addEventListener) 
    window.addEventListener("resize", NMap.resize, false);
  else if (window.attachEvent) 
    //window.attachEvent("onresize", NMap.resize);
  else
    window.onresize = NMap.resize;
	
  */
}
NMap.onMouseMove = function(point, a) {
  //if (!NMap.overlay.NYBounds.containsLatLng(point)) return false; // Not New York
  var mindist = Number.MAX_VALUE, idx = -1;
  for (var i=0, a; i < NMap.overlay.areas.length; i++) {
    a = NMap.overlay.areas[i].center;
    var distance = Math.sqrt(Math.pow((a.lat() - point.y)*1.314, 2) + Math.pow((a.lng() - point.x), 2));
    if (distance < mindist) {mindist = distance; idx = i;}
  }
  if (idx != NMap.hoverIndex) {
    if (NMap.hoverIndex != -1) {
	  if (NMap.selectedIndex == NMap.hoverIndex) { NMap.overlay.drawArea(NMap.selectedIndex,2); }
	  else { NMap.overlay.drawArea(NMap.hoverIndex,0); }
	}
	if (idx != NMap.selectedIndex) NMap.overlay.drawArea(idx, 1);
    NMap.hoverIndex = idx;
	var s = NMap.overlay.areas[idx].name;
	if (NMap.step == 'counties') s += ' / '+NMap.state;
	if (NMap.step == 'neighborhoods') s += " / "+NMap.county + " / " + NMap.state;
	$("mapItem").innerHTML = s;
    window.console.log("hoverIndex="+idx);
  }
}
NMap.onClick =  function(marker, point) {
  if (NMap.loading) { alert("Loading...Please wait!"); return false; };
  //if (!NMap.overlay.CityBounds.containsLatLng(point)) return false; // not New York

  var mindist = Number.MAX_VALUE, idx = -1;
  for (i=0; i < NMap.overlay.areas.length; i++) {
    a = NMap.overlay.areas[i].center;
    var distance = Math.sqrt(Math.pow((a.lat() - point.y)*1.314, 2) + Math.pow(a.lng() - point.x, 2));
    if (distance < mindist) { mindist = distance; idx = i; }
  }   
  if (NMap.selectedIndex != idx) {
    if (NMap.selectedIndex > -1) {
      NMap.overlay.drawArea(NMap.selectedIndex, 0);
	}
    NMap.selectedIndex = idx;
    NMap.overlay.drawArea(idx,0);
    NMap.overlay.drawArea(idx,2);
    NMap.onSelect(idx);
	// TODO: set marker
  }
}
NMap.onSelect = function(idx) {
  var a = this.overlay.areas[idx];

  if (NMap.step == 'states') {
    NMap.state = a.info.state_code;
    $("state").value = a.info.state_code;
	NMap.abox.hide();
  } else if (NMap.step == 'counties') {
    NMap.county = a.name;
	$("county").value = a.name;
	NMap.abox.hide();
	
  } else if (NMap.step == 'neighborhoods') {
    NMap.neighborhood = a.name;
    $("neighborhood").value = a.name;
    $("city").value = a.info.city_name;
	$("zip").value = a.info.zip;
	$("state").value = NMap.state;
    var center = a.bounds.getCenter();
    var zoom = NMap.overlay.map.getBoundsZoomLevel(a.bounds)+1;
    if (zoom > 14) zoom = 14;
    NMap.map.setCenter(center,zoom);
    NMap.abox.show();
  }
  copyAdv2Simple();
  searchAddress();
  NMap.nextStep();
}
NMap.nextStep = function() {
  if (NMap.step == '') {
    params = 'step=states';
  } else if (NMap.step == 'states') {
	params = 'step=counties&state='+NMap.state;
  } else if (NMap.step == 'counties') {
	params = 'step=neighborhoods&state='+NMap.state+'&county='+NMap.county;
  }
  NMap.setBackLink();
  if (NMap.step != 'neighborhoods') {
	  var url = "get_polygons.php?output=json&"+params;
	  //alert(url);
	  ajax(url, NMap.onLoadAreas); // load polygons
	  NMap.loading = true;
  }
  NMap.isBackStep = false;
}
NMap.prevStep = function() {
  if (NMap.step == 'neighborhoods') {
    params = 'step=counties&state='+NMap.state;
  } else if (NMap.step == 'counties') {
	params = 'step=states';
  }
  if (NMap.step != 'states') {
	  var url = "get_polygons.php?output=json&"+params;
	  ajax(url, NMap.onLoadAreas); // load polygons
	  NMap.loading = true;
	  NMap.isBackStep = true;
  }
  
}
NMap.setBackLink = function() {
  var s = '';
  if (NMap.step == 'counties') {
    s += '<a href="#" onclick="NMap.prevStep(); return false">Back to states</a>';
  } else if (NMap.step == 'neighborhoods') {
    s += '<a href="#" onclick="NMap.prevStep(); return false">Back to '+NMap.state+' counties</a>';
  }
  $('mapBackLink').innerHTML = '<b>'+s+'</b>';
}
NMap.onLoadAreas = function(obj) {
  NMap.loading = false;
  if (obj.length == 0) {
    alert("Sorry, we still not have info about the region...");
	return false;
  }
  NMap.selectedIndex = -1;
  NMap.hoverIndex = -1;

  if (NMap.step == 'states') {
   NMap.step = 'counties';
  } else if (NMap.step == 'counties') {
    NMap.step = NMap.isBackStep ? 'states' : 'neighborhoods';
  } else if (NMap.step == 'neighborhoods') {
    NMap.step = NMap.isBackStep ? 'counties' : '';
  }
  NMap.isBackStep = false;
  NMap.setBackLink();

  NMap.overlay.setAreas(obj);
  //NMap.overlay.redraw(true);
  var center = NMap.overlay.bounds.getCenter();
  var zoom = NMap.overlay.map.getBoundsZoomLevel(NMap.overlay.bounds)+1;
  if (zoom > 14) zoom = 14;
  window.console.log("moveto center="+center+" , zoom="+zoom);
  NMap.map.setCenter(center,zoom);
}

NMap.resize = function() {
  var width, height;

  // all except Explorer
  if (window.innerHeight) {
    width = window.innerWidth;
    height = window.innerHeight;
  }
  // Explorer 6 Strict Mode
  else {
    width = document.documentElement.clientWidth;
    height = document.documentElement.clientHeight;
  }

  NMap.map.checkResize();
}
NMap.cache = [];
NMap.cache.put = function(name, data) {
	if (NMap.cache.length == 10) NMap.cache = [];
	NMap.cache[NMap.cache.length] = [name, data];
}
NMap.cache.get = function(name) {
	for (var i = 0; i < NMap.cache.length; i++)
		if (NMap.cache[i][0] == name) return NMap.cache[i][1];
	return false;
}
NMap.searchAddress = function (str, callback) {
	if (NMap.searching) { return false; }
	NMap.searching = true;
	NMap.search_callback = callback;
	NMap.search_str = str;
	var r = NMap.cache.get(str);
	if (r) {
		NMap.onFinishSearch(r, true);
	} else {
		ajax("upload.php?address_ajax="+escape(str), NMap.onFinishSearch);
	}
}
// Proccess returned JSON object
NMap.onFinishSearch = function(result, fromCache) {
	NMap.searching = false;
	if (!fromCache) NMap.cache.put(NMap.search_str, result);
	if (result.Status.code == 200 && result.Placemark[0].AddressDetails.Accuracy > 4 && result.neighborhood != '') {
		var aa = result.Placemark[0].AddressDetails.Country.AdministrativeArea;
		var loc = typeof(aa.SubAdministrativeArea) != "undefined" ? aa.SubAdministrativeArea.Locality : aa.Locality;
		var coords_arr = result.Placemark[0].Point.coordinates;
		var data = {
			state: aa.AdministrativeAreaName,
			county: result.county,
			city: loc.LocalityName,					
			address: typeof(loc.Thoroughfare) != "undefined" ? loc.Thoroughfare.ThoroughfareName : '',
			address_full: result.Placemark[0].address,
			zip: loc.PostalCode.PostalCodeNumber,
			neighborhood: result.neighborhood,
			neighborhood_id: result.neighborhood_id,
			coords: new GLatLng(coords_arr[1], coords_arr[0]),
			accuracy: result.Placemark[0].AddressDetails.Accuracy
		};
		NMap.state = data.state;
		NMap.county = data.county;
		NMap.neighborhood = data.neighborhood;
		//NMap.step = 'counties';
		NMap.search_callback(data);
		if (!fromCache) {
			NMap.map.setCenter(data.coords);
            if (NMap.step != 'neighborhoods') {
              NMap.step = 'counties';
              NMap.nextStep();
			}
		}
		NMap.showAddrMarker(data.coords, data.address_full);
		NMap.abox.green();
		//NMap.nextStep();
	} else {
		NMap.search_callback(false);
		NMap.abox.red();
	}
}
// Show address Marker
NMap.showAddrMarker = function(point, address) {
  // Create a lettered icon for NMap point using our icon class
  if (NMap.addrMarker) NMap.map.removeOverlay(NMap.addrMarker);
  NMap.addrMarker = new GMarker(point, {title: address});
  NMap.map.addOverlay(NMap.addrMarker);
}

if(window.addEventListener) window.addEventListener('load',NMap.init,true);
else if(window.attachEvent) window.attachEvent('onload',NMap.init);
else window.onload = NMap.init;
