// google map embedded in gazetteer - December 2006

var map;
var poi_dataset = new Object;
var marker;
var places = new Object;   // cache for place markers
var markman;
var lastcentre = new GLatLng;

function $(id) {
    return document.getElementById(id);
}

function Update_Coordinates(pt) {
   var ts = $("latlongshow");
   if(ts)
     ts.value = pt.toUrlValue();
}

function Gaz_Map() {
    //    console.log();   // needed to overcome a bug
  if (!GBrowserIsCompatible())
    return;
  var mmp = $("map");
  map = new GMap2(mmp);
  map.setCenter(new GLatLng(cp_info.lat,cp_info.lng), cp_info.map_zoom);
  map.addControl(new GSmallMapControl());
  var startat = G_NORMAL_MAP;
  if(cp_info.map_start == 'Satellite')
    startat = G_SATELLITE_MAP;
  if(cp_info.map_start == 'Hybrid')
    startat = G_HYBRID_MAP;
  map.setMapType(startat);
  map.enableContinuousZoom();
  map.addControl(new GMapTypeControl());   // the overlay/map/hybrid buttons
	markman = new MarkerManager(map);
  // adverts (Feb 2009)
  var ads = new GAdsManager(map,cp_info.adaccount,cp_info.adoptions);
  ads.enable();
  // now create our point marker and it's label, which are joined by functions
  point = new GLatLng(cp_info.lat,cp_info.lng);
  marker = new GMarker(point,{draggable:true});
  var label = new ELabel(new GLatLng(cp_info.lat,cp_info.lng), cp_info.name,"maplabelstyle1",new GSize(7,10),70);
  map.addOverlay(label);
  places[cp_info.id] = true;  // already displayed
  GEvent.addListener(marker, "dragend", function() {
    map.panTo(marker.getPoint());
    var x = $('map_coord_form');
    if(x.style.display != 'block') {     // first call
       $('MoveButton').onclick = function() {
         Send_Changes(marker.getPoint());
       };
       $('ClearButton').onclick = function() {
  	 Restore_Marker(marker);
         label.setPoint(marker.getPoint());
       };
     }
     x.style.display = 'block';
     Update_Coordinates(marker.getPoint());
  });
  map.addOverlay(marker);
  poi_dataset.shown = false;
  poi_dataset.items = [];
  GEvent.addListener(map,"maptypechanged",function() {
	  Show_Or_Hide_Markers();
  });
  GEvent.addListener(marker,"drag", function() {  // move with marker
    label.setPoint(marker.getPoint());
  });
  var bnd = map.getBounds();
  Add_Points_In_Box(bnd.getSouthWest(),bnd.getNorthEast());
  GEvent.addListener(map,"movestart",function() {
    lastcentre = map.getCenter();
  });
  GEvent.addListener(map,"move",function() {
    var bnd = map.getBounds();
    // only send for points if we've moved 20% of the map
    // all points will be got when you stop moving anyway
    var sw = bnd.getSouthWest();
    var ne = bnd.getNorthEast();
    var diag = sw.distanceFrom(ne);
    var centre = map.getCenter();
    var moved = centre.distanceFrom(lastcentre);
    if(moved * 5 >= diag) {
	Add_Points_In_Box(bnd.getSouthWest(),bnd.getNorthEast());
	lastcentre = centre;
    }
  });
  GEvent.addListener(map,"moveend",function() {
    var bnd = map.getBounds();
    Add_Points_In_Box(bnd.getSouthWest(),bnd.getNorthEast());
  });
}

function Restore_Marker(marker) {
  marker.setPoint(new GLatLng(cp_info.lat,cp_info.lng));
  var x = $('map_coord_form');
  x.style.display = 'none';
  map.panTo(marker.getPoint());  
}

function Map_Reset(map,marker) {
  map.setCenter(new GLatLng(cp_info.lat,cp_info.lng), parseInt(cp_info.map_zoom));
  var startat = G_NORMAL_MAP;
  if(cp_info.map_start == 'satellite')
    startat = G_SATELLITE_MAP;
  if(cp_info.map_start == 'hybrid')
    startat = G_HYBRID_MAP;
  map.setMapType(startat);
  Restore_Marker(marker);
}	 

function Show_Or_Hide_Markers() {
  var shouldshow = false;
  var x = map.getCurrentMapType();
  if(x == G_NORMAL_MAP && cp_info.map_icon1)
    shouldshow = true;
  if(x == G_SATELLITE_MAP && cp_info.map_icon2)
    shouldshow = true;
  if(x == G_HYBRID_MAP && cp_info.map_icon3)
    shouldshow = true;
  if(poi_dataset.shown == shouldshow)     // no change
    return;
  if(shouldshow) {
    for(i in poi_dataset.items)
      map.addOverlay(poi_dataset.items[i]);
  } else {
    for(i in poi_dataset.items)
      map.removeOverlay(poi_dataset.items[i]);
  }
  poi_dataset.shown = shouldshow;
}

// always generate the markers, even if not shown yet
function Gaz_Map_Poi(poi_data) {
  var latest_icon;
  var icons = [];
  Gaz_Map_Add_POIs(poi_data,0);
  Show_Or_Hide_Markers();

  // this closely follows the structure of Do_Everything in the POI file
  function Gaz_Map_Add_POIs(pdat,level) {
    var topnum = 0;
    for(var i in pdat)
      if(i != 'icon')
        ++topnum;
      else
        if(pdat[i]!='**NONE**')
	  latest_icon = Create_Icon(pdat[i]);
    if(level == 0 && topnum ==0)
      return;
    if(level >= 2) {         // never more than 2 levels
      Gaz_Map_Several_POIs(pdat);
    } else {
      if(topnum > 1 || level == 0) {      // might need sub-tabs
        for(var i in pdat) {
          if(i != 'icon')
            Gaz_Map_Add_POIs(pdat[i],level+1);
          else
            if(pdat[i]!='**NONE**')
	      latest_icon = Create_Icon(pdat[i]);
         }
      } else {
        for(var i in pdat) {   // only single pass, but needed to skip over it
          if(i != 'icon')
            Gaz_Map_Add_POIs(pdat[i],level+1);
        }
      }
    }
  }

  function Poi_Marker(point,options,info,idx) {
    var marker = new GMarker(point,options);
    var popup = function() {
      var html = '<div id="map_info_box" class="map_info">';
      html += '<div style="text-align:center; font-style:italic;">'+info.name+'</div>';
      html += '<table>';
      if(info.phone)
        html += '<tr><td>Phone:</td><td>'+info.phone+'</td></tr>';
      if(info.email)
        html += '<tr><td>Email:</td><td>'+info.email+'</td></tr>';
      if(info.website)
        html += '<tr><td>Website:</td><td><a href="'+info.website+'">'+info.website+'</a></td></tr>';
      if(info.credit && typeof(info.credit) == 'string')
        html += '<tr><td><span style="font-size:80%">Information from:</span></td><td><span style="font-size:80%">'+info.credit+'</span></td></tr>';

      html += '</table>';
      if(info.text)
        html += '<div style="width:100%; font-size: 90%">'+info.text+'</div>';
      html += '<div onclick="Poi_Edit()" style="text-align: right; font-size:70%; color:red">Edit</div>';
      html += '</div>'
      marker.openInfoWindowHtml(html);
      poi_info.current_popup = info.index;
      poi_info.popup_frommap = true;
    };
    GEvent.addListener(marker, "click",popup);
    poi_info[idx] = info;
    poi_info[idx].callback = popup;
    poi_info[idx].index = idx;
    return marker;
  }

  function Gaz_Map_Several_POIs(pdat) {
    var ico;
    var point;
    for(i in pdat) {
      if(i == 'icon') {
        if(pdat[i]!='**NONE**')
	  latest_icon = Create_Icon(pdat[i]);
      } else {
        point = new GLatLng(pdat[i].latitude,pdat[i].longitude);
        smarker = Poi_Marker(point,{icon:latest_icon, title:pdat[i].name},pdat[i],i);
	poi_dataset.items.push(smarker);
      }
    }
  }

  function Create_Icon(ic) {
    if (icons[ic])
      return icons[ic];
    var ico = new GIcon();
    ico.image = '../images/icons/tabsymbols/'+ic+'.png';
    ico.iconSize = new GSize(22, 22);
    ico.iconAnchor = new GPoint(11, 11);
    ico.infoWindowAnchor = new GPoint(22, 22);
    icons[ic] = ico;
    return ico
  }
}

function Send_Changes(pt) {
    Send_Update('coordinates',pt.lat()+','+pt.lng(),'coordinate change');
    var x = $('map_coord_form');
    x.style.display = 'none';
}

function Add_Points_In_Box(sw,ne) {
  var txt = sw.toUrlValue()+';'+ne.toUrlValue();
	// NB - the reciprocal of this table is in Put_Points_On_Map - keep consistent
	// smallest places shown for zoom levels 1 upwards 
	//           0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18
	var zooms = [6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 4, 4, 3, 2, 2, 2, 1, 1, 1];
	txt += ':'+zooms[map.getZoom()];
        GDownloadUrl("../cgi-bin/poi_box.cgi?"+txt, function(data, responseCode) {
  	    if(data && data != '\n' && data != '\r') {
              var items = eval("("+data+")");
	      Put_Points_On_Map(items);
            }
        });
}

function Put_Points_On_Map(points) {
  var point,marker,label;
	var sess = "";
	// NB - the reciprocal of this table is in Add_Points_In_Box - keep consistent
	// which zoom levels should I show places at
	//           0  1  2  3  4  5  6  7  8   // sizes (8 is special, 7 dummy)
  var zooms = [0, 16,13,12,10,8, 0, 0, 0];
	if(cp_info.session)
			sess = "session="+cp_info.session+"&"
	for(i in points) {
				if(places[points[i].id]) {
				} else {
						point = new GLatLng(points[i].latitude,points[i].longitude);
						var stuff = '<div style="padding: 0px 0px 8px 8px; background: url(../images/icons/point_bottom_left.png) no-repeat bottom left; white-space:nowrap"><a href="../cgi-bin/gazetteer.cgi?'+sess+'id='+points[i].id+'" class="quiet" style="background-color: #f2efe9; padding: 2px; font-size:70%"><b> '+points[i].name+' <\/b><\/div><\/div>';
						label = new ELabel(point, stuff,null,null,65,true);
						//						console.log(map.getZoom()+' '+points[i].name+' '+points[i].type+' '+zooms[points[i].type]);
						markman.addMarker(label,zooms[points[i].type],17);
						places[points[i].id] = true;
				}
		}
}