// The main initialization function. Here we load the configuration file
// and process it.

var gmarkers = new Array();

function init(conffile) {
  if (!document.getElementById("map")) {
    alert("Template is missing a tag with id 'map'");
  } else {
    if(GBrowserIsCompatible()){
      var request = GXmlHttp.create();
      request.open("GET", conffile, true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          var xmlDoc = request.responseXML;
          var general = xmlDoc.documentElement.getElementsByTagName("general");
          // Set width and height even before creating the map,
          // To avoid problems.
          if (general.length == 1) {
            general = general[0];
            if (general.getAttribute("width")) {
              document.getElementById("map").style.width = general.getAttribute("width");
            }
            if (general.getAttribute("height")) {
              document.getElementById("map").style.height = general.getAttribute("height");
            }
          }
          var map = new GMap(document.getElementById("map"));
          document.theMap = map;
          // General Configuration
          if (general) {
            if (general.getAttribute("latitude") && general.getAttribute("longitude")) {
              var centerLatLng = new GPoint(parseFloat(general.getAttribute("longitude")),
                                            parseFloat(general.getAttribute("latitude")));
              map.centerAtLatLng(centerLatLng);
            }
            else {
                map.centerAtLatLng(new GPoint(-122.1419, 37.4419));
            }
            if (general.getAttribute("controls")) {
              var controlType = general.getAttribute("controls").toLowerCase();
              if (controlType == "small" || controlType == "default") {
                map.addControl(new GSmallMapControl());
              } else if (controlType == "large") {
                map.addControl(new GLargeMapControl());
              } else if (controlType == "full") {
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
              }
            } else {
              map.addControl(new GSmallMapControl());
            }
            if (general.getAttribute("zoom")) {
              map.zoomTo(parseInt(general.getAttribute("zoom")));
            }
            else {
              map.zoomTo(5);
            }
            var directions = 0;
            var labelkey = '';
            if (general.getAttribute("directions")) {
                directions = toBoolean(general.getAttribute("directions"));
                if (general.getAttribute("labelkey")) {
                    labelkey = general.getAttribute("labelkey");
                }
            }
            var infowindow = 0;
            if (general.getAttribute("infowindow")) {
                infowindow = toBoolean(general.getAttribute("infowindow"));
            }
            if (general.getAttribute("maptype")) {
                var maptype = general.getAttribute("maptype").toLowerCase();
                if (maptype == 'satellite') {
                    map.setMapType(G_SATELLITE_TYPE);
                }
                else if (maptype == 'hybrid') {
                    map.setMapType(G_HYBRID_TYPE);
                }
                else if (maptype == 'map' || maptype == 'default') {
                    map.setMapType(G_NORMAL_MAP);
                }
            }
          }
          // HTML Snippet
          var snippettag = xmlDoc.documentElement.getElementsByTagName("snippet");
          var snippet = ''
          if (snippettag.length == 1) {
            for (var i = 0; i < snippettag[0].childNodes.length; i++) {
              if (snippettag[0].childNodes[i].nodeType == 8) {
                snippet = snippettag[0].childNodes[i].nodeValue;
              }
            }
          }
          // Icons
          var icontags = xmlDoc.documentElement.getElementsByTagName("markers");
          if (icontags.length == 1) {
            icontags = icontags[0];
            var iconfield = icontags.getAttribute("field");
            var icons = new Array();
            var defaulticon = 0;
            icontags = icontags.childNodes;
            for (var i = 0; i < icontags.length; i++) {
              if (icontags[i].tagName == 'defaultmarker') {
                defaulticon = createIcon(icontags[i]);
              } else if (icontags[i].tagName == 'marker') {
                var icon = createIcon(icontags[i]);
                icons[icontags[i].getAttribute("key")] = icon;
              }
            }        
          }
          // Locations
          gmarkers = new Array();
          var points = xmlDoc.documentElement.getElementsByTagName("location");
          for (var i = 0; i < points.length; i++) {
            var point = new GPoint(parseFloat(points[i].getAttribute("longitude")),
                                   parseFloat(points[i].getAttribute("latitude")));
            var icon = defaulticon;
            if (points[i].getAttribute(iconfield)) {
              if (icons[points[i].getAttribute(iconfield)]) {
                icon = icons[points[i].getAttribute(iconfield)];
              }
            }
            var marker = createMarker(point, i, icon, snippet, points[i], directions, labelkey, (infowindow && i == 0));
            gmarkers[i] = marker;
            map.addOverlay(marker);
          }
        }
      }
      request.send(null);
    } else {
      // Browser isn't supported, output some polite message.
      document.getElementById("map").innerHTML =
       'Your browser is not officially supported. We '
      +'currently support the following browsers:</p><ul><li>'
      +'<a href="http://www.mozilla.org/products/firefox/">Firefox</a>'
      +' 0.8+ (Linux, Mac, Windows)</li><li>'
      +'<a href="http://www.microsoft.com/windows/ie/downloads/default.asp">'
      +'IE</a> 5.5+ (Windows)</li><li>'
      +'<a href="http://www.mozilla.org/products/mozilla1.x/">'
      +'Mozilla</a> 1.4+ (Linux, Mac, Windows)</li><li>'
      +'<a href="http://channels.netscape.com/ns/browsers/download.jsp">'
      +'Netscape</a> 7.1+ (Linux, Mac, Windows)</li><li>'
      +'<a href="http://www.apple.com/safari/download">'
      +'Safari</a> 1.2.4+ (Mac)</li>'
      +'<li><a href="http://www.opera.com/download/">'
      +'Opera</a> 7.5+ (Linux, Mac, Windows)</li></ul>'
      +'<p>We recommend you download one of the browsers above';
    }
  }
  return;
}

function toBoolean(arg) {
// Auxiliar for configuration file parsing, converts a string to a boolean value
    var str = arg.toLowerCase();
    if (str == 'true' || str == 'on' || str == 'yes' || str == '1') {
        return 1;
    }
    return 0;
}

// Auxiliar for createMarker, used for regular expression replacement
var current_row;
function replace_field(name) {
    field = name.substring(2, name.length - 2);
    return current_row.getAttribute(field);
}

function createMarker(point, i, icon, snippet, row, with_directions, labelkey, open_immediately) {
// Creates a marker overlay for the map
    var marker;
    if (icon == 0) {
        marker = new GMarker(point);
    } else {
        marker = new GMarker(point, icon);
    }
    current_row = row;
    var msg = snippet.replace(/##[^#]*##/g, replace_field);
    if (with_directions) {
        var label = ''
        if (labelkey.length > 0) {
            label = '(' + row.getAttribute(labelkey) + ')';
        }
        marker.to_html = msg + '<span style="font-size: 12px"><br>Directions: <b>To here</b> - ' +
                '<a href="javascript:from_here(' + i + ')">From here</a>' +
                '<br>Start address:<form action="http://maps.google.com/maps"' +
                ' method="get" target="_blank"><input type="text" size="23"' +
                ' maxlength="40" name="saddr" id="saddr" value="" /> ' +
                '<input value="Get Directions" type="submit">' +
                '<input type="hidden" name="daddr" value="' +
                point.y + ',' + point.x + label + '"/></span>';
        marker.from_html = msg + '<span style="font-size: 12px"><br>Directions: <a href="javascript:to_here(' +
                i + ')">To here</a> - <b>From here</b><br>End address:' +
                '<form action="http://maps.google.com/maps" method="get" ' +
                'target="_blank"><input type="text" size="23" maxlength="40"' +
                ' name="daddr" id="daddr" value="" /> <input ' +
                'value="Get Directions" TYPE="submit"><input type="hidden" ' +
                'name="saddr" value="' + point.y + ',' + point.x + label +'"/></span>';
        msg = msg + '<span style="font-size: 12px"><br>Directions: <a href="javascript:to_here(' +
                i + ')">To here</a> - <a href="javascript:from_here(' + i +
                ')">From here</a></span>';
    }
	marker.msg = msg;
    GEvent.addListener(marker, 'click', function() {
	   marker.openInfoWindowHtml(msg);
    });
    if (open_immediately) {
        document.theMap.openInfoWindowHtml(point, msg,
            new GSize(icon.infoWindowAnchor.x - icon.iconAnchor.x, icon.infoWindowAnchor.y - icon.iconAnchor.y));
    }
    return marker;
}

function createIcon(markertag) {
// Creates a GIcon and configures it according to the xml node provided
    var icon = new GIcon();
    if (markertag.getAttribute("image")) {
        icon.image = markertag.getAttribute("image");
    }
    if (markertag.getAttribute("shadow")) {
        icon.shadow = markertag.getAttribute("shadow");
    }
    if (markertag.getAttribute("iconw") && markertag.getAttribute("iconh")) {
        icon.iconSize = new GSize(parseInt(markertag.getAttribute("iconw")),
                                  parseInt(markertag.getAttribute("iconh")));
    }
    if (markertag.getAttribute("shadoww") && markertag.getAttribute("shadowh")) {
        icon.shadowSize = new GSize(parseInt(markertag.getAttribute("shadoww")),
                                  parseInt(markertag.getAttribute("shadowh")));
    }
    if (markertag.getAttribute("iconx") && markertag.getAttribute("icony")) {
        icon.iconAnchor = new GPoint(parseInt(markertag.getAttribute("iconx")),
                                  parseInt(markertag.getAttribute("icony")));
    }
    if (markertag.getAttribute("winfox") && markertag.getAttribute("winfoy")) {
        icon.infoWindowAnchor = new GPoint(parseInt(markertag.getAttribute("winfox")),
                                  parseInt(markertag.getAttribute("winfoy")));
    }
    return icon;
}

function from_here(i) {
    gmarkers[i].openInfoWindowHtml(gmarkers[i].from_html);
}

function to_here(i) {
    gmarkers[i].openInfoWindowHtml(gmarkers[i].to_html);
}

function show_info(i) {
    gmarkers[i].openInfoWindowHtml(gmarkers[i].msg);
}
