<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <!-- based on Google Gadget/Mapplet cross-API template by Sterling Udell (sterling@udell.name) -->

  <ModulePrefs title="USGS Real-time Earthquakes" 
                  description="USGS Earthquakes for the past 7 days"
                  author="Scott Haefner"
                  author_email="shaefner@usgs.gov"
                  author_location="San Francisco Bay Area"
                  author_affiliation="U.S. Geological Survey"
                  screenshot="http://earthquake.usgs.gov/earthquakes/mapplets/ss-earthquakes.png"
                  thumbnail="http://earthquake.usgs.gov/earthquakes/mapplets/tn-earthquakes.png"
                  height="360">
    <Require feature="sharedmap"/>
  </ModulePrefs>

  <Content type="html"><![CDATA[

    <!-- content to appear on both platforms should go here. -->

    <style type="text/css">
    h1 {
      font-size: 15px;
      color: #333;
      padding: 0;
      margin: 0;
    }
    h2 {
      font-size: 12px;
      color: #333;
      padding: 0;
      margin: 1em 0;
    }
    p.stamp {
      font-family: Georgia, serif;
      font-size: 12px;
      color: #666;
      padding: 0;
      margin: 0 0 5px 0;
    }
    ol {
      font-size: 12px;
      margin: 1em 1em 1em 2.5em;
      padding: 0;
    }
    li {
      margin: .4em 0;
      padding: 0;
    }
    img {
      padding-left: 0px;
    }
    .details p {
      font-size: .8em;
    }
    </style>
    <h1>M 4+ Earthquakes, Past 7 Days</h1>
    <div id="content">
    </div>

    <script type="text/javascript">

      // Global variables
      var map = null;
      var eqs = [];
      var icons = [];
      var markers = [];
      
      var points = {
        color: { // Marker: icon color
          'pasthour': 'red',
          'pastday': 'orange',
          'pastweek': 'yellow'
        },
        size: { // Marker: icon size in pixels
          'M1': 11,
          'M2': 15,
          'M3': 17,
          'M4': 21,
          'M5': 25,
          'M6': 31,
          'M7': 37,
          'M8': 45,
          'M9': 55
        }
      };
      
      var isMapplet = !!window.GMap2;   // Are we running as a mapplet or not?
      if (!isMapplet) { // Not running as a mapplet => a few additional HTML elements are required
        document.write('<script src="http://maps.google.com/maps?file=api&amp;v=2"><\/script>');
        document.write('<div id="map" style="height: 300px"></div>');
      }

      _IG_RegisterOnloadHandler(function () { // Note that, for cross-API compatibility, all map init needs to be in here
        
        createMap();   
        
        // add any other map options you need - they'll be ignored in the mapplet

        if (isMapplet) { // Any mapplet-specific init for your own functionality goes in here

        }
        else { // Gadget-specific init goes in here

          // First, do setup required by the Maps API that's n/a to mapplets.

          map.addMapType(G_PHYSICAL_MAP);
          map.addControl(new GHierarchicalMapTypeControl());
          map.addControl(new GSmallMapControl());

          // Second, do any setup specific to this gadget (put your own code in here)
        }

        // Other, non-API-specific initialization for this map/gadget
        
        readMarkers();

      });

      // Define any other functions you need here
      
      function createMap() {
        var map_center = new GLatLng(20, 180);
        var map_zoom = 1; if (isMapplet) map_zoom = 2;
        var map_type = G_PHYSICAL_MAP; //G_SATELLITE_MAP, G_NORMAL_MAP
        map = new GMap2(document.getElementById('map'), { logoPassive:true });
        map.setCenter(map_center, map_zoom, map_type);
      }
      
      function readMarkers() {
      
        // Fetch RSS feed
        var feed = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M4.xml";
        _IG_FetchXmlContent(feed, function(response) {  
          if (response == null || typeof(response) != "object" || response.firstChild == null) {
            _gel("content").innerHTML = "<i>Invalid data.</i>";
            return;
          }
      
          var pubDate = response.getElementsByTagName("pubDate");
          var feed_pubDate = pubDate.item(0).firstChild.nodeValue;
      
          eqs = response.getElementsByTagName("item");
          
          var html_mapstamp = '<p class="stamp">' + eqs.length + ' earthquakes on this map<br />Updated ' + feed_pubDate + '</p>';
          var html_legend_list = '<img src="http://earthquake.usgs.gov/earthquakes/mapplets/legend.png" alt="legend" />';
          html_legend_list += "<h2>10 Most Recent Earthquakes</h2>";
          html_legend_list += "<ol>";
          
          // Loop through eq list (<item> nodes)
          for (var i = 0; i < eqs.length; i++) {
        
            // For each eq, get child nodes
            var item_nodes = eqs.item(i).childNodes;
            
            dcsubject_count = 1;
            
            // Loop through child nodes
            for (var j = 0; j < item_nodes.length; j++) {
              
              var node = item_nodes.item(j);
                      
              if (node.nodeName == "title") {
                 var title = node.firstChild.nodeValue;
              }
              if (node.nodeName == "description") {
                 var description = node.firstChild.nodeValue;
              }
              if (node.nodeName == "link") {
                 var link = node.firstChild.nodeValue; 
              }
              if (node.nodeName == "geo:lat") {
                 var lat = parseFloat(node.firstChild.nodeValue);
              }
              if (node.nodeName == "geo:long") {
                 var long = parseFloat(node.firstChild.nodeValue); 
              }
              if (node.nodeName == "dc:subject" && dcsubject_count == 3) { //third dc:subject tag
                 var depth = node.firstChild.nodeValue;
              }
              if (node.nodeName == "dc:subject" && dcsubject_count == 2) { //second dc:subject tag
                 var age = node.firstChild.nodeValue;
                 dcsubject_count ++;
              }
              if (node.nodeName == "dc:subject" && dcsubject_count == 1) { //first dc:subject tag
                 var mag = node.firstChild.nodeValue;
                 dcsubject_count ++;
              }
      
            }
              
            if (i < 10) { // Show first 10 earthquakes in sidebar
              html_legend_list += '<li><a href="javascript:showBubble(' + i + ')">' + title + "</a></li>";
            }
            
            var bubble = '<div style="width:250px;" class="details"><p><strong>' + title + '</strong><br />' + description + '</p><p><a href="' + link + '" target="_new">Earthquake Details</a> &raquo;</p></div>';
            var titletip = title;
            var icon = getIcon(age, parseInt(mag));
      
            createMarker(lat, long, icon, titletip, bubble, i);
      
          }
      
          html_legend_list += "</ol>";
      
          // Display HTML in content <div>
          if (isMapplet) {
            _gel('content').innerHTML = html_mapstamp + html_legend_list;
          } else {
            _gel('content').innerHTML = html_mapstamp;
          }
                    
        }, { refreshInterval: (60 * 5) }); // Allow Google to cache feed for only 5-minutes
      }
      
      // Create marker object for earthquake overlay
      
      function createMarker(lat, long, icon, titletip, bubble, count) {
        var marker = new GMarker(new GLatLng(lat, long), {icon:icon, title:titletip});
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(bubble, {disableGoogleLinks:true});
        });
        map.addOverlay(marker);
        markers[count] = marker; // Save for use in sidebar link
      }
      
      // Set icon properties based on age, magnitude
      
      function getIcon(age, mag) {
        var ref = 'M' + mag + '-' + points.color[age];
        if (!icons[ref]) {
          var center_pt = parseInt(points.size['M'+mag]/2);
          var icon = new GIcon();
          icon.image = 'http://earthquake.usgs.gov/earthquakes/maps/images/' + ref + '.png';
          icon.iconSize = new GSize(points.size['M'+mag], points.size['M'+mag]);
          icon.iconAnchor = new GPoint(center_pt, center_pt);
          icon.infoWindowAnchor = new GPoint(center_pt, center_pt);
          icons[ref] = icon;
        }
        return icons[ref];
      }
       
      // Show bubble window when eq clicked from sidebar
      
      function showBubble(i) {
        GEvent.trigger(markers[i], "click");
      }
      
      _IG_Analytics("UA-2265247-1", "/earthquakes/mapplets/earthquakes.xml");
      
    </script>
  ]]></Content>
</Module>
