var map;

// Icons (really constants)
var BLUE_ICON   = gIcon('blue');
var RED_ICON    = gIcon('red');
var GREEN_ICON  = gIcon('green');
var YELLOW_ICON = gIcon('yellow');

// Constants
const LINE_COLOR = '#000077';

function gIcon(col) {
  var icon = new GIcon(G_DEFAULT_ICON);
  icon.image = 'http://labs.google.com/ridefinder/images/mm_20_' + col + '.png';
  icon.iconSize = new GSize(12,20);
  icon.iconAnchor = new GPoint(6,20); // default (9,24)
  return icon;
}

function showLine(points) {
  if (!points || points.length == 0) return;
  var firstPoint = points[0];
  var finalPoint = points[points.length-1];
  firstPoint.icon = GREEN_ICON;
  finalPoint.icon = BLUE_ICON;
	map.panTo(firstPoint);
  map.addOverlay(new GPolyline(points,LINE_COLOR));
}

function newGMarker(p,icon) {
  var m = new GMarker(p); //,icon ? icon : RED_ICON);
  return m;
}

/**
 * Returns an array of points from an XML doc with nodes named
 * <code>nodeName</code>, where each node contains attributes called
 * <code>lat</code> and <code>lng</code>.  If
 * <code>addPointsToMap</code> then we also add the points to the map
 * as we're collecting them.  
 *
 * Example:
 *
 * <transfers>
 * ... <transfer lat="123.4" lng="234.5" /> ...
 * </transfers>
 */
function getPoints(doc,nodeName,addPointsToMap) {
  var points = new Array();
  var ns = doc.getElementsByTagName(nodeName);
  if (!ns) return points;
  for (var i=0; i<ns.length; i++) {
    var n = ns[i];
    var p = new GLatLng(parseFloat(n.getAttribute('lat')),
                        parseFloat(n.getAttribute('lng')));
    points.push(p);
    if (addPointsToMap) {
      var icon;
      if (i == 0) {
        icon = GREEN_ICON;
      } else if (i == ns.length-1) {
        icon = RED_ICON;
      } else {
        icon = BLUE_ICON;
      }
      map.addOverlay(newGMarker(p,icon));
    }
  }
  return points;
}

function fillMap() {
  var ballId = param('ball');
  if (ballId) {
    var url = '/transfers.php';
    var prs = {'ball':ballId};
    var fun = function (doc) {
      var points = getPoints(doc,'transfer',true);
      if (points.length > 0) {
        showLine(points);
      } else {
        // If we only have one point, there won't be any transfers
        // In this case, just get the location of the single ball
        var url2 = '/ball.php';
        var prs2 = {'ball':ballId};
        var fun2 = function (d) {
          showLine(getPoints(d,'ball',true));
        }
        ajax(url2,prs2,fun2);
      }
    };
    ajax(url,prs,fun);
  }
}

function loadMap() {
	map = new GMap2(document.getElementById("map"));
  map.setCenter(new GLatLng(37.4419, -122.1419), 13);
  map.setUIToDefault();
  fillMap();
}
