/* Google Maps code for the Plan / Polygon shape type */

function draw(centre) {
  drawShapes(centre, points);
}

function drawShapes(centre, polygons) {
  if (drawnPolygons) {
    for (index in drawnPolygons) {
      drawnPolygon = drawnPolygons[index];
      drawnPolygon.setMap(null);
      drawnPolygon = null;
    }
  }

  // find centroid of polygons
  polygon_centre = new Array(0, 0);

  var points = 0;

  for (index in polygons) {
    polygon = polygons[index];
    for (point in polygons[index]) {
      // TODO fix weighting bug with looped point(s) 
      polygon_centre[0] = polygon_centre[0] + Number(polygon[point][0]);
      polygon_centre[1] = polygon_centre[1] + Number(polygon[point][1]);

      points += 1;
    }
  }
  polygon_centre[0] = polygon_centre[0]/points;
  polygon_centre[1] = polygon_centre[1]/points;

  // for each polygon, draw it
  for (index in polygons) {
    polygon = polygons[index];
    // get offset (in pixels) from polygon centre to point 0
    db = getDistanceBearingPixels(polygon[0], polygon_centre, scale_factor);

    mapPolygon = new Array();
    mapPolygon[0] = getNewDestPoint(centre, -db[0], db[1]);
    
    // then find d and b pairs for all the new points and calculate the
    // mapPolygon vertices
    for (i=1; i<polygon.length; i++) {
      db = getDistanceBearingPixels(polygon[i-1], polygon[i], scale_factor);
      destpoint = getNewDestPoint(mapPolygon[i-1], db[0], db[1]);
      mapPolygon[i] = destpoint;
    }

    // plot on map
    drawnPolygon = new google.maps.Polygon({
      paths: mapPolygon,
      strokeColor: "#000000",
      strokeOpacity: 0.9,
      strokeWeight: 6,
      fillColor: "#cccccc",
      fillOpacity: 0.5,
      map: map
    });

    drawnPolygons.push(drawnPolygon);

    drawnPolygon = new google.maps.Polygon({
      paths: mapPolygon,
      strokeColor: "#f8c705",
      strokeOpacity: 0.9,
      strokeWeight: 3,
      fillColor: "#cccccc",
      fillOpacity: 0.5,
      map: map
    });

    drawnPolygons.push(drawnPolygon);
  }
}

