//shape.js 24/04/2011

var COLORS = [["red", "#ff0000"], ["green","#008000"],["blue", "#000080"], ["purple", "#800080"], ["orange", "#ff8800"]];
var options = {};
var lineCounter_ = 0;
var shapeCounter_ = 0;
var markerCounter_ = 0;
var colorIndex_ = 0;
var featureTable_;
var map;
var outputFileMode = 'csv';
var geocoder = null;

var fillColor = "#0000ff"; // blue fill
var lineColor = "#ff00ff"; // black line
var opacity = .5;
var lineWeight = 3;
var currpoly = [];
var poly = [];

function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(51.2329101, -0.3297445), 13);
    map.setMapType(G_HYBRID_MAP);
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.clearOverlays();
    map.addOverlay(new GGeoXml("http://www.surreyflora.org.uk/Boundary/Surrey.kmz"));
    geocoder = new GClientGeocoder();
    featureTable_ = document.getElementById("featuretbody");
  }
}

function getColor(named) {
  return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
}

function startShape() {
  var color = getColor(false);
  var poly = new GPolygon([], color, 2, 0.7, "#0000FF", 0.2);
  startDrawing(poly, "Polygon " + (++shapeCounter_), function() {
    logCoordinates(poly);
    var cell = this;
    cell.innerHTML = " (" + poly.getVertexCount() + " points)";
  }, color);
}

function editShape() {
  var color = getColor(false);
  var points = [];
  var inputPolygon = document.getElementById("PointsBox");
  pointsLines=inputPolygon.value.split(/ |\n/);
  var poly = new GPolygon([], color, 2, 0.7, "#0000FF", 0.2);
  var k = pointsLines[0].search(",");
  var latx = pointsLines[0].substr(0,k);
  var longx = pointsLines[0].substr(k+1);
  map.setCenter(new GLatLng(latx, longx), 15);
  map.addOverlay(poly);
  //Read in coordinates
  for ( var i=0, len=pointsLines.length; i<len; ++i ){
    if (pointsLines[i].search(/,|\t/) != -1) {
      pointsCoords = pointsLines[i].split(/,|\t/);
      if (parseFloat(pointsCoords[0]) != 0 && parseFloat(pointsCoords[1]) != 0) {
	      poly.insertVertex(0, new GLatLng(parseFloat(pointsCoords[0]),parseFloat(pointsCoords[1])));
      }
    }
  }
  var name = "Polygon " + (++shapeCounter_);
  var cells = addFeatureEntry(name, color);
  poly.enableEditing({onEvent: "mouseover"});
  poly.disableEditing({onEvent: "mouseout"});
  poly.Nametag = name;
  currpoly = poly;
  logCoordinates(poly);
  cells.desc.innerHTML = " (" + poly.getVertexCount() + " points)";
  GEvent.bind(poly, "lineupdated", cells.desc, function() {
    logCoordinates(poly);
    var cell = this;
    cell.innerHTML = " (" + poly.getVertexCount() + " points)";
  });
  GEvent.addListener(poly, "click", function(latlng, index) {
    currpoly = poly;
    if (typeof index == "number") {
      poly.deleteVertex(index);
    } else {
      poly.setStrokeStyle({weight: 2});
      cells.desc.innerHTML = " (" + poly.getVertexCount() + " points)";
    }
  });
}

function addFeatureEntry(name, color) {
  currentRow_ = document.createElement("tr");
  var colorCell = document.createElement("td");
  currentRow_.appendChild(colorCell);
  colorCell.style.backgroundColor = color;
  colorCell.style.width = "1em";
  var nameCell = document.createElement("td");
  currentRow_.appendChild(nameCell);
  nameCell.innerHTML = name;
  var descriptionCell = document.createElement("td");
  currentRow_.appendChild(descriptionCell);
  featureTable_.appendChild(currentRow_);
  return {desc: descriptionCell, color: colorCell};
}

function startDrawing(poly, name, onUpdate, color) {
  poly.Nametag = name;
  map.addOverlay(poly);
  currpoly = poly;
  var cells = addFeatureEntry(name, color);
  poly.enableDrawing(options);
  poly.enableEditing({onEvent: "mouseover"});
  poly.disableEditing({onEvent: "mouseout"});
  GEvent.addListener(poly, "endline", function() {
    currpoly = poly;
    logCoordinates(poly);
    cells.desc.innerHTML = " (" + poly.getVertexCount() + " points)";
    GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
    GEvent.addListener(poly, "click", function(latlng, index) {
      currpoly = poly;
      if (typeof index == "number") {
        poly.deleteVertex(index);
      } else {
        poly.setStrokeStyle({weight: 2});
        cells.desc.innerHTML = " (" + poly.getVertexCount() + " points)";
      }
    });
  });
}

function logCoordinates(poly){
  //var currentPoly = document.getElementById("activepoly");
  //currentPoly.innerHTML = '<b>' + poly.Nametag + '</b>'; 
  var coordtext = "";
  //var header = name + "";
  //var footer = "";
  //coordtext =  header;
  // loop to print coords
  for (var i = 0; i<(poly.getVertexCount()); i++) {
    var vert = poly.getVertex(i);
    var lat = vert.lat();
    lat = lat.toFixed(6);
    var longi = vert.lng();
    longi = longi.toFixed(6);
    coordtext += lat + "," + longi + "*";
  }
  //coordtext +=  footer;
  var ourtag = document.getElementById("coords");
  /*if (ourtag.tagName == "PRE" && "outerHTML" in ourtag){
    ourtag.outerHTML = '<pre id="coords">' + coordtext + '</pre>';
  } else {*/
    ourtag.innerHTML = coordtext;
  //}
}

function autoSelect(el) {
  if(el && (el.tagName === "TEXTAREA" || (el.tagName === "INPUT" && el.type === "text"))) {
    el.select();
    return;
  }
  if (el && window.getSelection) { // FF, Safari, Opera
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(el);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (el) { // IE
    document.selection.empty();
    var range = document.body.createTextRange();
    range.moveToElementText(el);
    range.select();
  }
}

function showAddress() {
  var address = document.getElementById("address").value;
  if (geocoder) {
    geocoder.getLatLng(address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          clearMap();
          map.setCenter(point, 15);
          map.addOverlay(new GGeoXml("http://www.surreyflora.org.uk/Boundary/Surrey.kmz"));
        }
      }
    );
  }
}

// Clear current Map
function clearMap(){
  map.clearOverlays();
  map.addOverlay(new GGeoXml("http://www.surreyflora.org.uk/Boundary/Surrey.kmz"));
  shapeCounter_ = 0;
  // Clear featureTable_ tbody
  while (featureTable_.childNodes.length > 0) {
    featureTable_.removeChild(featureTable_.firstChild);
  }
  colorIndex_ = 0;
}

function closePolygon(){
  var closePoint = new GLatLng(poly.getVertex(0).lat(),poly.getVertex(0).lng());
  poly.insertVertex(poly.getVertexCount() + 1,  closePoint);
  logCoordinates(poly);
}

function removeLast(poly) {
  poly.deleteVertex(poly.getVertexCount() - 1);
  poly.enableDrawing(options);
  logCoordinates(poly);
}
