/*
	Google JSON

	A quick hack that takes items for Google Maps from a JSON file
*/

///////////////////////////////////////////////////////////////////////////

//
// Config
//
var datapath = "/data/";
var dataext = ".json";

var invalidchars = /[^A-Za-z0-9_-]/;	// allow only simple characters

///////////////////////////////////////////////////////////////////////////

//
// JSON Handling
//

// from: http://www.ietf.org/internet-drafts/draft-crockford-jsonorg-json-04.txt
String.prototype.parseJSON = function () {
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};


///////////////////////////////////////////////////////////////////////////

//
// Helper Functions
//

// Creates a marker at the given point with the given number label
function createMarker(point, name, info) {

  var marker = new GMarker(point, {title:name});
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowTabsHtml(info);
  });

  return marker;
}

// Highlight a marker on the map when textitem is clicked...
function hilite(idx) {
	markers[idx].openInfoWindowTabsHtml(info[idx]);
}

    

///////////////////////////////////////////////////////////////////////////

//
// Main Line
//

if (! GBrowserIsCompatible()) {
  document.writeln("This page is entirely too reliant on Google Maps, which does not appear to be supported by your browser.");
} 


var undefined;	// from: http://www.webreference.com/programming/javascript/gr/column9

var info = [];
var markers = [];
var texthtml = "";

var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addControl(new GOverviewMapControl());
map.addControl(new GScaleControl());

// GLog.write("Now debugging...");

if ( invalidchars.test(mapspec) ) {
  texthtml += "<h2>Sorry.</h2>We cannot understand the map specification.  This problem is almost certainly at our end. <p>We had problem reading '" + mapspec + "'.";
  document.getElementById("text").innerHTML = texthtml;
}
mapitemsfile = datapath + mapspec + dataext;


GDownloadUrl(mapitemsfile, function(data, responseCode) {
  var mapItems = data.parseJSON();

  if( mapItems == false ) {
    texthtml += "<h2>Sorry.</h2>We cannot parse the information to map for you.  This problem is almost certainly at our end. <p>We had problem reading '" + mapspec + "'.";
    document.getElementById("text").innerHTML = texthtml;
    return;
  }

  if( mapItems.center != undefined ) {
    map.setCenter(new GLatLng(mapItems.center.lat, mapItems.center.lng),
	  mapItems.center.mag,G_HYBRID_MAP);
  } else {
    texthtml = "<h2>Sorry.</h2>We cannot find any information to map for you.  This problem is almost certainly at our end. <p>We had problem reading '" + mapspec + "'.";
    document.getElementById("text").innerHTML = texthtml;
    return;
  }

  if( mapItems.text != undefined ) {
    if( mapItems.text.head != undefined ) {
      texthtml += '<h1>'+mapItems.text.head+'</h1>\n';
    }
    if( mapItems.text.top != undefined ) {
      texthtml += mapItems.text.top+'<p>\n';
    }
  }

  if( mapItems.markers != undefined ) {
    texthtml += '<ul>\n';

    for (var i = 0; i < mapItems.markers.length; i++) {
      var point = new GLatLng(mapItems.markers[i].lat, mapItems.markers[i].lng);

      var infoTabs = [];
      infoTabs.push(new GInfoWindowTab("What",
			      mapItems.markers[i].item + "<p>" +
			      mapItems.markers[i].desc));
      infoTabs.push(new GInfoWindowTab("More...",
		      "<A HREF=\"http://maps.google.com/maps?q="+
		      point.toUrlValue()+
		      "+%28"+escape(mapItems.markers[i].item)+"%29"+
		      "&t=h&hl=en\">Google from here</A>"+
		      "<P>Print, search, get driving directions, et al."));
      markers[i] = new createMarker(point, mapItems.markers[i].item, infoTabs);
      map.addOverlay(markers[i]);

      info[i] = infoTabs;
      texthtml += '<li><a href="javascript:hilite('+i+')">'+
          mapItems.markers[i].item+'</a></li>\n';
    }
    texthtml += '</ul>\n';
  }

  if( mapItems.text != undefined ) {
    if( mapItems.text.bottom != undefined ) {
      texthtml += '<p>'+mapItems.text.bottom+'</p>\n';
    }
  }
  document.getElementById("text").innerHTML = texthtml;

  if( mapItems.markers != undefined ) {
    for (var i = 0; i < mapItems.lines.length; i++) {
      var color = mapItems.lines[i].color;
      var width = mapItems.lines[i].width;
      var opaque = mapItems.lines[i].opaque;
      var poly = [];
      for (var j = 0; j < mapItems.lines[i].points.length; j++) {
        poly[j] = new GLatLng(mapItems.lines[i].points[j].lat,
                            mapItems.lines[i].points[j].lng);
      }
      map.addOverlay(new GPolyline(poly, color, width, opaque));
    }
  }
});

