var onemile = 1609; // metres
var dist1 = onemile * 10.0;
var dist2 = onemile * 10.0;
var deg2rad = 3.1415926535897932 / 180;
var rad2deg = 180 / 3.1415926535897932;
var map;
var bridgham = new google.maps.LatLng(52.585529, 0.574722);
var landfills = new Array();
var i = 0;
landfills[i++] = {'code': 'MK43 9LY', 'addr': 'Green Lane, Stewartby, Bedfordshire', 'area': 'Bedfordshire', 'site': 'Stewartby Landfill Site', 'long': -0.52288999999999997, 'lat': 52.07488};
landfills[i++] = {'code': 'MK18 2HF', 'addr': 'Brackley Lane, Calvert, Buckinghamshire', 'area': 'Buckinghamshire & Milton Keynes', 'site': 'Calvert Landfill Site', 'long': -0.99729999999999996, 'lat': 51.905479999999997};
landfills[i++] = {'code': 'MK3 5JU', 'addr': 'Bletchley Road, Newton Longville, Milton Keynes, Buckinghamshire', 'area': 'Buckinghamshire & Milton Keynes', 'site': 'Bletchley Landfill Site', 'long': -0.75166999999999995, 'lat': 51.982050000000001};
landfills[i++] = {'code': 'CB24 6DQ', 'addr': 'Butt Lane, Milton, Cambridgeshire', 'area': 'Cambridgeshire', 'site': 'Milton Landfill Site', 'long': 0.14582999999999999, 'lat': 52.248280000000001};
landfills[i++] = {'code': 'PE19 5UH', 'addr': 'Station Farm, Brampton Road, Buckden, Cambridgeshire', 'area': 'Cambridgeshire', 'site': 'Buckden Landfill Site', 'long': -0.21967, 'lat': 52.29965};
landfills[i++] = {'code': 'PE15 8QN', 'addr': 'Hundred Road, March, Cambridgeshire', 'area': 'Cambridgeshire', 'site': 'March Landfill Site', 'long': 0.079210000000000003, 'lat': 52.566609999999997};
landfills[i++] = {'code': 'PE1 3TD', 'addr': 'Welland Road, Dogsthorpe, Peterborough, Cambridgeshire', 'area': 'Cambridgeshire', 'site': 'Dogsthorpe Landfill Site', 'long': -0.22517000000000001, 'lat': 52.603250000000003};
landfills[i++] = {'code': 'SK11 9QP', 'addr': 'Gawsworth, Macclesfield, Cheshire', 'area': 'Cheshire', 'site': 'Danes Moss Landfill Site', 'long': -2.1472699999999998, 'lat': 53.240699999999997};
landfills[i++] = {'code': 'CH2 4JP', 'addr': 'Ince Lane, Wimbolds Trafford, Chester', 'area': 'Cheshire', 'site': 'Gowy Landfill Site', 'long': -2.8321100000000001, 'lat': 53.241579999999999};
landfills[i++] = {'code': 'CW1 1NG', 'addr': 'Maw Green Road, Coppenhall, Crewe, Cheshire', 'area': 'Cheshire', 'site': 'Maw Green Landfill Site', 'long': -2.4279600000000001, 'lat': 53.11553};
landfills[i++] = {'code': 'WA4 6YZ', 'addr': 'Off Liverpool Road, Sankey Bridges, Warrington', 'area': 'Cheshire', 'site': 'Arpley Landfill Site', 'long': -2.6183399999999999, 'lat': 53.376469999999998};
landfills[i++] = {'code': 'LL22 8HP', 'addr': 'Abergele, Clwyd', 'area': 'Conwy', 'site': 'Llanddulas Landfill Site', 'long': -3.6497700000000002, 'lat': 53.285559999999997};
landfills[i++] = {'code': 'LA14 4QH', 'addr': 'Thwaite Flat, Barrow-in-Furness, Cumbria', 'area': 'Cumbria', 'site': 'Bennett Bank Landfill Site', 'long': -3.2060499999999998, 'lat': 54.162230000000001};
landfills[i++] = {'code': 'CA14 4JH', 'addr': 'Joseph Noble Road, Lillyhall, Workington, Cumbria', 'area': 'Cumbria', 'site': 'Lillyhall Landfill Site', 'long': -3.51824, 'lat': 54.602890000000002};
landfills[i++] = {'code': 'YO43 4ED', 'addr': 'Market Weighton Road, Holme on Spalding Moor', 'area': 'Humber', 'site': 'Gallymoor Landfill Site', 'long': -0.72265999999999997, 'lat': 53.847209999999997};
landfills[i++] = {'code': 'DN40 1QR', 'addr': 'Queens Road, Immingham', 'area': 'Humber', 'site': 'Immingham Landfill Site', 'long': -0.19009000000000001, 'lat': 53.608690000000003};
landfills[i++] = {'code': 'DN15 9AP', 'addr': 'Coleby Road, West Halton, Winterton', 'area': 'Humber', 'site': 'Winterton Landfill Site', 'long': -0.62109999999999999, 'lat': 53.668700000000001};
landfills[i++] = {'code': 'PE21 7AA', 'addr': 'Slippery Gowt Lane, Wyberton, Boston, Lincs', 'area': 'Lincolnshire', 'site': 'Boston Landfill Site', 'long': -0.0024429999999999999, 'lat': 52.955179999999999};
landfills[i++] = {'code': 'NG33 5QT', 'addr': 'Off Crabtree Road, Stainby, Grantham, Lincs', 'area': 'Lincolnshire', 'site': 'Colsterworth Landfill Site', 'long': -0.65595000000000003, 'lat': 52.789279999999998};
landfills[i++] = {'code': 'DN21 1AF', 'addr': 'Lea Road, Gainsborough, Lincs', 'area': 'Lincolnshire', 'site': 'Gainsborough Landfill Site', 'long': -0.77159999999999995, 'lat': 53.373139999999999};
landfills[i++] = {'code': 'LN10 6YN', 'addr': 'Tattershall Road, Kirkby-on-Bain, Lincs', 'area': 'Lincolnshire', 'site': 'Kirkby on Bain Landfill Site', 'long': -0.15225, 'lat': 53.163910000000001};
landfills[i++] = {'code': 'LN5 OQF', 'addr': 'Pottergate, Leadenham, Lincs', 'area': 'Lincolnshire', 'site': 'Leadenham Landfill Site', 'long': -0.57027000000000005, 'lat': 53.058210000000003};
landfills[i++] = {'code': 'PE24 5AD', 'addr': 'Burgh Le Marsh, Lincolnshire', 'area': 'Lincolnshire', 'site': 'Middlemarsh Landfill Site', 'long': 0.29668, 'lat': 53.147620000000003};
landfills[i++] = {'code': 'LN6 3QZ', 'addr': 'Whisby Raod, North Hykeham, Lincolnshire', 'area': 'Lincolnshire', 'site': 'North Hykeham Landfill Site', 'long': -0.60558999999999996, 'lat': 53.199159999999999};
landfills[i++] = {'code': 'NR34 OBL', 'addr': 'Nr Beccles, Norfolk', 'area': 'Norfolk & Suffolk', 'site': 'Aldeby Landfill Site', 'long': 1.62904, 'lat': 52.475340000000003};
landfills[i++] = {'code': 'PE32 1SW', 'addr': 'Mill Drove, East Winch Road, Blackborough End, Kings Lynn, Norfolk', 'area': 'Norfolk & Suffolk', 'site': 'Blackborough End Landfill Site', 'long': 0.47345999999999999, 'lat': 52.704470000000001};
landfills[i++] = {'code': 'IP24 4DR', 'addr': 'The Oakery, Lodge Road, Feltwell, Thetford, Norfolk', 'area': 'Norfolk & Suffolk', 'site': 'Feltwell Landfill Site', 'long': 0.55900000000000005, 'lat': 52.498069999999998};
landfills[i++] = {'code': 'ML6 7TD', 'addr': 'Meikle Drumgray Road, Greengairs, Airdrie, Lanarkshire', 'area': 'Glasgow & North Lanarkshire', 'site': 'Greengairs Landfill Site', 'long': -3.9433500000000001, 'lat': 55.906140000000001};
landfills[i++] = {'code': 'NN17 3JG', 'addr': 'Kettering Road, Weldon, Northamptonshire', 'area': 'Northamptonshire', 'site': 'Weldon Landfill Site', 'long': -0.64754999999999996, 'lat': 52.484470000000002};
landfills[i++] = {'code': 'DN22 8RB', 'addr': 'Daneshill Road, Lound, Retford', 'area': 'Nottinghamshire', 'site': 'Daneshill Landfill Site', 'long': -0.98807999999999996, 'lat': 53.372860000000003};
landfills[i++] = {'code': 'NG5 8PU', 'addr': 'Woodborough Lane, Arnold', 'area': 'Nottinghamshire', 'site': 'Dorket Head Landfill Site', 'long': -1.11415, 'lat': 53.018610000000002};
landfills[i++] = {'code': 'NG24 3JJ', 'addr': 'Grange Lane, Grange Lane, Cotham, Nottinghamshire, , , ', 'area': 'Nottinghamshire', 'site': 'Staple Quarry Landfill Site', 'long': -0.80293999999999999, 'lat': 53.024909999999998};
landfills[i++] = {'code': 'OX29 5BB', 'addr': 'Linch Hill, Stanton Harcourt, Oxford', 'area': 'Oxfordshire', 'site': 'Dix Pit Landfill Site', 'long': -1.41011, 'lat': 51.736339999999998};
landfills[i++] = {'code': 'OX14 4PW', 'addr': 'Appleford Sidings, Abingdon, Oxfordshire', 'area': 'Oxfordshire', 'site': 'Sutton Courtenay Landfill Site', 'long': -1.2595099999999999, 'lat': 51.639539999999997};
landfills[i++] = {'code': 'CV8 3BN', 'addr': 'Weston Lane, Bubbenhall, Coventry', 'area': 'Warwickshire & West Midlands', 'site': 'Waverley Wood Landfill Site - Bubbenhall', 'long': -1.4691399999999999, 'lat': 52.339390000000002};
landfills[i++] = {'code': 'HG5 OSD', 'addr': 'Nr Knaresborough, North Yorkshire', 'area': 'North & West Yorkshire', 'site': 'Allerton Park Landfill Site', 'long': -1.3791500000000001, 'lat': 54.034179999999999};
landfills[i++] = {'code': 'WF6 2JA', 'addr': 'Boundary Lane, Normanton, Wakefield', 'area': 'North & West Yorkshire', 'site': 'Welbeck Landfill Site', 'long': -1.4317299999999999, 'lat': 53.690530000000003};
landfills[i++] = {'code': 'DN6 8LX', 'addr': 'Straight Lane, Skelbrooke, Doncaster, South Yorkshire', 'area': 'North & West Yorkshire', 'site': 'Skelbrooke Landfill Site', 'long': -1.2316199999999999, 'lat': 53.599760000000003};
landfills[i++] = {'code': 'DN7 4JT', 'addr': 'Dunscroft, Doncaster', 'area': 'North & West Yorkshire', 'site': 'Bootham Lane Landfill Site', 'long': -1.0092300000000001, 'lat': 53.587940000000003};
landfills[i++] = {'code': 'EH25 9QN', 'addr': 'Cleugh Road, Roslin, Penicuik, Midlothian', 'area': 'Edinburgh & Midlothian', 'site': 'Oatslie Landfill Site', 'long': -3.1812900000000002, 'lat': 55.850239999999999};
landfills[i++] = {'code': 'WA4 6YZ', 'addr': 'Off Liverpool Road, Sankey Bridges, Warrington, Cheshire', 'area': 'Halton & Warrington', 'site': 'Arpley Landfill Site', 'long': -2.6183399999999999, 'lat': 53.376469999999998};
landfills[i++] = {'code': 'DN7 4JT', 'addr': 'Dunscroft, Doncaster', 'area': 'South Yorkshire', 'site': 'Bootham Lane Landfill Site', 'long': -1.0092300000000001, 'lat': 53.587940000000003};
landfills[i++] = {'code': 'LL14 5AR', 'addr': 'Pen-Y-Bont Works, Chirk, Wrexham', 'area': 'Wrexham', 'site': 'Pen-Y-Bont Landfill Site (Chirk)', 'long': -3.0546099999999998, 'lat': 52.96472};
landfills[i++] = {'code': 'SA8 4RX', 'addr': 'Rhy Dy Fro, Pontardawe, Swansea, West Glamorgan', 'area': 'West Glamorgan', 'site': 'Pwllfawatkin Landfill Site', 'long': -3.8867099999999999, 'lat': 51.756399999999999};
var marker = null;
var circle1 = null;
var circle2 = null;

function initialize() {
  var myOptions = {
    zoom: 10,
    center: bridgham,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  zoomToArea('ALL');
  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.
  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('pin-yellow-L-bare.png',
      new google.maps.Size(34, 35),
      new google.maps.Point(0,0),
      new google.maps.Point(9, 33));
  var shadow = new google.maps.MarkerImage('pin-yellow-L-shadow.png',
      new google.maps.Size(34, 35),
      new google.maps.Point(0,0),
      new google.maps.Point(9, 33));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML <area> element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [9, 0, 18, 9, 9, 24, 0, 9],
      type: 'poly'
  };
  for (i = 0; i < landfills.length; i++) {
    var locn = new google.maps.LatLng(landfills[i]['lat'], landfills[i]['long']);
    landfills[i]['locn'] = locn;
    var landfillMarker = new google.maps.Marker({
        position: locn,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: landfills[i]['site']
    });
    var j = i + 1;
    attachMessage(landfillMarker, i);
  }

  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });
  google.maps.event.addDomListener(document.getElementById("areaSelect"), 'change', changeArea);
}

function attachMessage(landfillMarker, i) {
  // FOR SOME REASON THESE HAVE TO BE ADDED IN A FUNCTION, SO AS TO CREATE PERSISTENT VARIABLES
  var html = "<div class=\"info\"><strong>" + landfills[i]['site'] + "</strong>";
  html += "<table><tr><th>Address:</th><td>" + landfills[i]['addr'].replace(/, /g, "<br />") + "</td></tr>";
  html += "<tr><th>Postcode:</th><td>" + landfills[i]['code'] + "</td></tr>";
  // html += "<tr><th>Coords:</th><td>" + locnToString(landfills[i]['lat'], landfills[i]['long'], 10000) + "</td></tr>";
  html += "</table></div>";
  var infowindow = new google.maps.InfoWindow(
      { content: html,
        size: new google.maps.Size(50,50)
      });
  google.maps.event.addListener(landfillMarker, 'click', function() {
    infowindow.open(map, landfillMarker);
  });
}
  
function placeMarker(location) {
  // locnStr = locnToString(location.lat(), location.lng(), 10000)
  // document.getElementById('markerLocn').innerHTML = "Project Location: " + locnStr;
  document.getElementById('latinput').value = Math.round(location.lat() * 1000000) / 1000000;
  document.getElementById('longinput').value = Math.round(location.lng() * 1000000) / 1000000;
	wgs84 = new GT_WGS84();
	wgs84.setDegrees(location.lat(), location.lng());
	//convert to OSGB
	osgb = wgs84.getOSGB();
	//get a grid reference with 3 digits of precision
  document.getElementById('gridrefinput').value = osgb.getGridRef(5);
  if (marker) {
    marker.setMap(null);
    marker = null;
  }
  if (circle1) {
    circle1.setMap(null);
    circle1 = null;
  }
  if (circle2) {
    circle2.setMap(null);
    circle2 = null;
  }
  var image = new google.maps.MarkerImage('pin-red-P-bare.png',
      new google.maps.Size(34, 35),
      new google.maps.Point(0,0),
      new google.maps.Point(9, 33));
  var shadow = new google.maps.MarkerImage('pin-red-P-shadow.png',
      new google.maps.Size(34, 35),
      new google.maps.Point(0,0),
      new google.maps.Point(9, 33));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML <area> element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [9, 0, 18, 9, 9, 24, 0, 9],
      type: 'poly'
  };
  marker = new google.maps.Marker({
      position: location,
      map: map,
      shadow: shadow,
      icon: image,
      shape: shape,
      title: 'Project Location'
  });
  map.setCenter(location);
  map.setZoom(10);
  circle1 = new google.maps.Circle({
    map: map,
    radius: dist1, // 10 miles
    options: {strokeColor : '#465215',
              fillOpacity: 0,
              strokeWeight: 1}
  });
  circle1.bindTo('center', marker, 'position');
  circle2 = new google.maps.Circle({
    map: map,
    radius: dist2, // 11.5 miles
    options: {strokeColor : '#AF7300',
              fillOpacity: 0.1,
              strokeWeight: 1}
  });
  circle2.bindTo('center', marker, 'position');
  google.maps.event.addListener(circle2, 'click', function(event) {
    placeMarker(event.latLng);
  });
  clearDists(10);
  j = 0;
  for (i = 0; i < landfills.length; i++) {
    distFrom = landfills[i]['locn'].distanceFrom(location);
    if (distFrom < dist2) {
      miles = Math.round(distFrom / onemile * 100) / 100;
      document.getElementById('name' + j).innerHTML = landfills[i]['site'];
      document.getElementById('dist' + j).innerHTML = miles + ' miles';
      elig = 'Maybe';
      if (distFrom <= dist1) { elig = 'Yes'; }
      document.getElementById('elig' + j).innerHTML = elig;
      // document.getElementById('coords' + j).innerHTML =  locnToString(landfills[i]['lat'], landfills[i]['long'], 10000);
      document.getElementById('row' + j).className = 'vis';
      j++;
    }
  }
  if (j == 0) {
    document.getElementById('row0').className = 'vis';
    document.getElementById('name0').innerHTML = 'No Landfill sites within range';
    // document.getElementById('noSites').innerHTML = 'No Landfill sites within range';
  } else {
    document.getElementById('colHeaders').className = 'vis';
  }
}

function clearDists(numRows) {
    // document.getElementById('noSites').innerHTML = '';
  for (j = 0; j < numRows; j++) {
    document.getElementById('name' + j).innerHTML = '';
    document.getElementById('dist' + j).innerHTML = '';
    document.getElementById('elig' + j).innerHTML = '';
    // document.getElementById('coords' + j).innerHTML = '';
    document.getElementById('row' + j).className = 'invis';
  }
  document.getElementById('colHeaders').className = 'invis';
}

function locnToString(lat, long, precision) {
  ret = ''
  if (lat < 0) {
    ret = Math.round(-lat * precision) / precision + "&deg;S";
  } else {
    ret = Math.round(lat * precision) / precision + "&deg;N";
  }
  if (long < 0) {
    ret += " " + Math.round(-long * precision) / precision + "&deg;W";
  } else {
    ret += " " + Math.round(long * precision) / precision + "&deg;E";
  }
	wgs84 = new GT_WGS84();
	wgs84.setDegrees(lat, long);
	//convert to OSGB
	osgb = wgs84.getOSGB();
	//get a grid reference with 3 digits of precision
	var gridref = osgb.getGridRef(3);
  ret += " (" + gridref + ")";
  return ret;
}

function changeArea() {
  clearDists(10);
  area = this.options[this.selectedIndex].text;
  zoomToArea(area);
}

function zoomToArea(area) {
  minlat = 999;
  maxlat = -999;
  minlong = 999;
  maxlong = -999;
  for (i = 0; i < landfills.length; i++) {
    if ((landfills[i]['area'] == area) || (area == 'ALL')) {
      if (landfills[i]['lat'] < minlat) { minlat = landfills[i]['lat']; }
      if (landfills[i]['lat'] > maxlat) { maxlat = landfills[i]['lat']; }
      if (landfills[i]['long'] < minlong) { minlong = landfills[i]['long']; }
      if (landfills[i]['long'] > maxlong) { maxlong = landfills[i]['long']; }
    }
  }
  if (maxlat > -999) {
    var bound1 = new google.maps.LatLng(minlat, minlong);
    var bound2 = new google.maps.LatLng(maxlat, maxlong);
    var bounds = new google.maps.LatLngBounds(bound1, bound2);
    map.fitBounds(bounds);
    if (map.getZoom() > 10) {
      map.setZoom(10);
    }
  }
}

function latlongPlaceMarker() {
  var latinput = parseFloat(document.getElementById('latinput').value);
  var longinput = parseFloat(document.getElementById('longinput').value);
	if (isNaN(latinput) || isNaN(longinput)) {
		alert('Sorry: Latitude and Longitude values not recognised\n\nExamples:\n52.134, 0.9\n53.998, -1.3' );
	} else {
		var location = new google.maps.LatLng(latinput, longinput);
		placeMarker(location);
	}
}

function gridrefPlaceMarker() {
  var gridrefinput = document.getElementById('gridrefinput').value;
	var osgb2 = new GT_OSGB();
	if (osgb2.parseGridRef(gridrefinput)) {
		var wgs842 = osgb2.getWGS84();
		var location = new google.maps.LatLng(wgs842.latitude, wgs842.longitude);
		placeMarker(location);
	} else {
		alert('Sorry: Grid Ref not recognised.\n\nExamples:\nTL 590 860\nNN1201\nSX3451298342' );
	}
}

function latlongGridrefPlaceMarker() {
  var latinput = document.getElementById('latinput').value;
  var longinput = document.getElementById('longinput').value;
  var gridrefinput = document.getElementById('gridrefinput').value;
  var latlongEntered = (latinput != '') || (longinput != '');
  var gridrefEntered = (gridrefinput != '');
  if (latlongEntered && !gridrefEntered) {
		latlongPlaceMarker();
	} else if (!latlongEntered && gridrefEntered) {
		gridrefPlaceMarker();
	} else {
		alert('Sorry: Please enter either a lat/long pair OR a Grid Ref' );
	}
}

google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
  //var R = 6371; // km (change this constant to get miles)
  var R = 6371000; // meters
  var lat1 = this.lat();
  var lon1 = this.lng();
  var lat2 = newLatLng.lat();
  var lon2 = newLatLng.lng();
  var dLat = (lat2-lat1) * Math.PI / 180;
  var dLon = (lon2-lon1) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 )
*
    Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d;
}

google.maps.event.addDomListener(window, 'load', initialize);


