﻿function LoadIncentiveMap()
{
  map.setCenter(new GLatLng(40.0, -98.0), 4);
  LoadIncentiveXML('http://maps.coolerplanet.com/Resources/MapFiles/CPRating.xml');
}

function LoadIncentiveXML(url)
{
  // download the file
  GDownloadUrl(url,
    function(data)
    {
      // get the xml document
      var xml = GXml.parse(data);
      if (xml.documentElement == null)
        return;
      
      // get all the polys
      var polys = xml.documentElement.getElementsByTagName("Poly");
      if (polys == null)
        return;

      // get all the state information
      var stateInfo = xml.documentElement.getElementsByTagName("State");

      for (var i = 0; i < polys.length; i++)
      {
        // add the polygon
        var poly = CreatePolygon(polys[i]);
        
        // see if there is any info for that state
        for (var j = 0; j < stateInfo.length; j++)
        {
          if (stateInfo[j].getAttribute("StateCode") == polys[i].getAttribute("StateCode"))
          {
            LinkPolyInformation(poly, stateInfo[j]);
            break;
          }
        }
      }
    }
  );
}

function CreatePolygon(polyNode)
{
  var pointsArray = [];
  var points = polyNode.getElementsByTagName("Point");
  for (var j = 0; j < points.length; j++)
  {
    // push on each point to the array
    pointsArray.push(new GLatLng(
      parseFloat(GXml.value(points[j].getElementsByTagName("Latitude")[0])),
      parseFloat(GXml.value(points[j].getElementsByTagName("Longitude")[0]))));
  }
  
  // figure out the poly settings
  var outlineWidth = polyNode.getAttribute("LineWidth");
  var outlineColor = polyNode.getAttribute("LineColor");
  var outlineOpacity = polyNode.getAttribute("LineOpacity");
  var fillColor = polyNode.getAttribute("FillColor");
  var fillOpacity = polyNode.getAttribute("FillOpacity");
  
  var polygon = new GPolygon(pointsArray, outlineColor, outlineWidth, outlineOpacity, fillColor, fillOpacity);
  map.addOverlay(polygon);
  
  return polygon;
}

function LinkPolyInformation(poly, infoNode)
{
  // see if there are info windows
  var tabs = infoNode.getElementsByTagName("Tab");
  if (tabs.length == 0)
  {
    return;
  }
  else
  {
    // multiple tabs, fun!
    GEvent.addListener(poly, "click",
      function(point)
      {
        var tabCollection = [];
        for (var i = 0; i < tabs.length; i++)
        {
          tabCollection.push(new GInfoWindowTab(tabs[i].getAttribute("Title"), GXml.value(tabs[i])));
        }
        map.openInfoWindowTabsHtml(point, tabCollection);
      }
    );
  }
}
