#! /usr/bin/perl

use strict;

$#ARGV and die "Usage: $0 <lbrexport.xml>\n";

my ($lbr_export) = $ARGV[0];

my ($symlinkname) = "map.html";

my ($outfile) = "map.html";
$lbr_export =~ m,lbrexp-(\d+).xml, and $outfile = "map-$1.html";


my ($min_lat, $max_lat) = (0, 0);
my ($min_lng, $max_lng) = (0, 0);

my ($lat, $lng);

open(LBREXP, "<$lbr_export") or die "$0: Failed to open '$lbr_export': $!\n";
while(<LBREXP>)	{
	chomp;
	m,<marker, or next;
	m,lat="([^"]+)", and $lat = $1;
	m,lng="([^"]+)", and $lng = $1;

	($lat == 0.0 or $lng == 0.0) and next;
	
	($min_lat == 0 or $min_lat > $lat) and $min_lat = $lat;
	$max_lat < $lat and $max_lat = $lat;

	($min_lng == 0 or $min_lng > $lng) and $min_lng = $lng;
	$max_lng < $lng and $max_lng = $lng;
}


close(LBREXP);

open(MAP, ">$outfile") or die "$0: Failed to create map-file '$outfile': $!\n";

-l $symlinkname and unlink($symlinkname);
symlink($outfile, $symlinkname);

my($middle_lat, $middle_lng) = (($max_lat+$min_lat)/2.0, ($max_lng+$min_lng)/2.0);

print MAP <<_BODY;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps JavaScript API Example</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2"
            type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"), {size:new GSize(1450, 990)});
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng($middle_lat, $middle_lng), 13);

	GDownloadUrl("$lbr_export", function(data, responseCode) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < markers.length; i++) {
			if(parseFloat(markers[i].getAttribute("lat")) == 0.0 || parseFloat(markers[i].getAttribute("lng")) == 0.0)	{
				continue;
			}
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
			var title = markers[i].getAttribute("cell");
			if(markers[i].getAttribute("upd"))	{
				title += " [" + markers[i].getAttribute("upd") + "]";
			}
			if(markers[i].getAttribute("name"))	{
				title += " (" + markers[i].getAttribute("name") + ")";
			}
			map.addOverlay(new GMarker(point, {title:title}));
		}
	});
      }
    }

    //]]>
    </script>
  </head>
  <body onload="load()" onunload="GUnload()">
    <div id="map" style="width: 500px; height: 300px"></div>
  </body>
</html>
_BODY

__END__
