//==============================================================================
// JavaScript functions for Google Map pages
//==============================================================================
var gMapCenter;
gMapCenter=new GLatLng(50.550144247614575, -4.144881963729858);
// Tavistock center is 50.550144247614575, -4.144881963729858
// Okehampton center is 50.73898440169782, -4.0034544467926025
var gmap;
var gmgr;
var dirPanel;
var startLoc;
var endLoc;
var oldLevel;
var newLevel;
var fileRoute = '/subfiles/includes/';
var imgRoute = '/subfiles/graphics/';
var endLocName;
var dirReq;
var regReq='TAV';
var gEarthButton ='';

//==============================================================================
function AppUnload() { 
  GUnload();
  }
//==============================================================================
function AppInitialise() {
  var map = document.getElementById("gMapCanvas");
  if (GBrowserIsCompatible()) {
    gmap = new GMap2(map);
    gmap.addControl( new GLargeMapControl3D() );
    gmap.addControl( new GMapTypeControl() );
    gmap.addControl( new GOverviewMapControl(new GSize(125,75)) );
    gmap.addControl( new GScaleControl() );
    gmap.setCenter( gMapCenter, 10 );
    gmap.addMapType(G_PHYSICAL_MAP);

    //Options:
    //gmap.enableGoogleBar();
    gmap.addMapType( G_SATELLITE_3D_MAP );
    
    gmgr = new MarkerManager(gmap, {maxZoom:20});
    gmgr.refresh();
    dirPanel = new GDirections(gmap, document.getElementById("gMapDirections"));
    loadAllMarkers('initialise');
    GEvent.addDomListener(document.getElementById("selReset"),"click", function() { loadAllMarkers('initialise'); });

    GEvent.addDomListener(document.getElementById("selWDBC"),"click", function() { zoomDetails('WDBC'); });
    GEvent.addDomListener(document.getElementById("selLeisure"),"click", function() { zoomDetails('Leisure'); });
    GEvent.addDomListener(document.getElementById("selTourism"),"click", function() { zoomDetails('Tourism'); });
    GEvent.addDomListener(document.getElementById("selCarPark"),"click", function() { zoomDetails('CarPark'); });
    GEvent.addDomListener(document.getElementById("selRecycling"),"click", function() { zoomDetails('Recycling'); });
    GEvent.addDomListener(document.getElementById("selBusiness"),"click", function() { zoomDetails('Business'); });
    
    GEvent.addDomListener(document.getElementById("selReset"),"mouseover", function() { hoverDetails('Reset'); });
    GEvent.addDomListener(document.getElementById("selWDBC"),"mouseover", function() { hoverDetails('WDBC'); });
    GEvent.addDomListener(document.getElementById("selLeisure"),"mouseover", function() { hoverDetails('Leisure'); });
    GEvent.addDomListener(document.getElementById("selTourism"),"mouseover", function() { hoverDetails('Tourism'); });
    GEvent.addDomListener(document.getElementById("selCarPark"),"mouseover", function() { hoverDetails('CarPark'); });
    GEvent.addDomListener(document.getElementById("selRecycling"),"mouseover", function() { hoverDetails('Recycling'); });
    GEvent.addDomListener(document.getElementById("selBusiness"),"mouseover", function() { hoverDetails('Business'); });
    
    GEvent.addDomListener(document.getElementById("selReset"),"mouseout", function() { hoverOutDetails(); });
    GEvent.addDomListener(document.getElementById("selWDBC"),"mouseout", function() { hoverOutDetails(); });
    GEvent.addDomListener(document.getElementById("selLeisure"),"mouseout", function() { hoverOutDetails(); });
    GEvent.addDomListener(document.getElementById("selTourism"),"mouseout", function() { hoverOutDetails(); });
    GEvent.addDomListener(document.getElementById("selCarPark"),"mouseout", function() { hoverOutDetails(); });
    GEvent.addDomListener(document.getElementById("selRecycling"),"mouseout", function() { hoverOutDetails(); });
    GEvent.addDomListener(document.getElementById("selBusiness"),"mouseout", function() { hoverOutDetails(); });
    
    GEvent.addDomListener(document.getElementById("selTAV"),"click", function() { regionChange('Tavistock'); });
    GEvent.addDomListener(document.getElementById("selOKE"),"click", function() { regionChange('Okehampton'); });
    
    endLoc = gmap.getCenter();
    startLoc = new GLatLng(50.552283,-4.144453) ;
    GEvent.addDomListener(document.getElementById("gMapGetDirFrom"),"click", function() { showDirections(endLoc, 'from'); });
    GEvent.addDomListener(document.getElementById("gMapGetDirTo"),"click", function() { showDirections(endLoc, 'to'); });
    GEvent.addListener(dirPanel, "error", function(error) { dirPanelOnError(error); });
    GEvent.addListener(gmap, "zoomend", function(oldLevel, newLevel) { showZoom(oldLevel, newLevel) });
    
    document.getElementById("gMapInstructions").innerHTML= setInstructions();
    document.getElementById("DirectionRequest").style.display = 'none';
    document.getElementById("gMapButtons").style.display = 'block';
    } else {
    alert("Sorry, your browser cannot handle the true power of Google Maps");
    }
  }
//==============================================================================


//==============================================================================
//Map initialisation
//==============================================================================
function loadAllMarkers (category) {
  GDownloadUrl("http://www.westdevon.gov.uk/subfiles/Includes/App14366MapData.asp", function(jsonData, responseCode) {parseData(jsonData, category);} );
  
  if (gEarthButton == 'EARTH') { 
    gmap.addMapType( G_SATELLITE_3D_MAP ); 
    gEarthButton = 'Business';
    } else {
    gmap.removeMapType( G_SATELLITE_3D_MAP ); 
    gEarthButton = 'Business';
    }
  document.getElementById("gMapInstructions").innerHTML= setInstructions();
  document.getElementById("DirectionRequest").style.display = 'none';
  dirPanel.clear();
  }  
//==============================================================================

//==============================================================================
//Map manipulation
//==============================================================================
function centerOnPoint (input) {
  endLocName = input.Location;
  gMapCenter=new GLatLng(50.550144247614575, -4.144881963729858);
  regReq = "TAV";
  if(input.MapType == 'WDBCOFFICEOKE') {
    gMapCenter=new GLatLng(50.73898440169782, -4.0034544467926025);
    regReq="OKE";
    }
  gmap.setMapType( G_HYBRID_MAP );
  gmap.setZoom(reCenterMapSize());
  gmap.panTo(input.Point);
  var dest = gmap.getCenter();
  document.getElementById("gMapInstructions").innerHTML = '<p>Enter a postcode or placename and click on \"Get Directions\" to obtain driving directions to or from '  + endLocName + '.</p>';
  endLocName =input.Location;
  endLoc = input.Point;
  if(input.roadPoint != null) { endLoc = input.roadPoint; }
  dirReq = "NO";
  document.getElementById("DirectionRequest").style.display = 'block';
  }
//==============================================================================
function reCenterMapSize (Point) {
  var gmaptype = gmap.getCurrentMapType();
  if(gmaptype.getName() == 'Terrain') {
    return 15; 
    } else {
    if(gmaptype.getName() == 'Earth') {
      return 13; 
      } else {
      return 17; 
      }
    }
  }
//==============================================================================
function showZoom(oldlev, newlev) {
  var HTML = '<span class=\"showZoom\">';
  HTML += 'mag ' + newlev;
  HTML += '</span>';
  document.getElementById("gMapZoomLevel").innerHTML = HTML;
  if (newlev > 14) {
    HTML = '';
    HTML += '<input type=\"text\" id=\"gMapSetPostCode\" value=\"Post Code or Address\" />';
    if(endLocName !=null) {
      document.getElementById("gMapDirForm").innerHTML = HTML;
      document.getElementById("gMapGetDirStr").innerHTML = 'Get Directions: ';
      document.getElementById("gMapGetDirFrom").innerHTML = '<u>FROM</u> this location <u>to</u> the icon,'; // To ' + endLocName ;
      document.getElementById("gMapGetDirTo").innerHTML = '<u>TO</u> this location <u>from</u> the icon.'; // To ' + endLocName ;
      }
    } else {
      document.getElementById("gMapGetDirStr").innerHTML = '';
      document.getElementById("gMapGetDirFrom").innerHTML = '';
      document.getElementById("gMapGetDirTo").innerHTML = '';
      document.getElementById("gMapDirForm").innerHTML = '';
      endLocName = null;
    }
  }
//==============================================================================

//==============================================================================
//Marker Management
//==============================================================================
function parseData (jsonData, category) {
  gmgr.clearMarkers();
  gmap.clearOverlays();
  gmap.setCenter( gMapCenter, 10 );
  
  var NewData = eval("(" + jsonData + ")");
  for (var i in NewData.Levels) {
    var level = NewData.Levels[i];
    var minZoom = level["Zoom"][0];
    var maxZoom = level["Zoom"][1];
    var markers = [];
    for (var j in level["Markers"]) {
      var place = level["Markers"][j];
      markers.push(createMarker(place, category));
      }
    gmgr.addMarkers(markers, minZoom, maxZoom);
    }
  gmgr.refresh();
  if(category == 'initialise') {
    gmap.setMapType( G_NORMAL_MAP );
    document.getElementById("gMapDirections").innerHTML='<p>&nbsp;</p>';
    }
  }
//==============================================================================
function createMarker(input, category) {
  var newMarker = testMarker(input, category);
  if(newMarker != null) {
    var marker = new GMarker(input.Point, {icon: makeIcon(newMarker), title:input.Location + ' ' + input.Type } );
    GEvent.addListener(marker, "click", function() {centerOnPoint(input); });
    GEvent.addListener(marker, "mouseover", function() { marker.openInfoWindowHtml(formatWindow(input)); });
    } 
  return marker;
  }
//==============================================================================
function testMarker(input, category) {
  return input.Marker;
  //if(category == 'initialise') { return input.Marker; }
  //if(category == 'WDBC') { if(input.Type == 'Council Offices') { return  input.Marker; } }
  //if(category == 'Tourism') { if(input.Type == 'TIC') { return  input.Marker; } }
  //if(category == 'Leisure') { if(input.Type == 'Leisure Center')   { return  input.Marker; } }
  //if(category == 'CarPark') { if(input.Type == 'Car Parks')   { return  input.Marker; } }
  //if(category == 'Recycling') { if(input.Type == 'Recycling Center')   { return  input.Marker; } }
  //if(category == 'Business') { if(input.Type == 'Business Center')   { return  input.Marker; } }
  //return null;
  }
//==============================================================================
function makeIcon(image) {
  var icon = new GIcon();
  icon.image = imgRoute + image;
  if( image == 'mapIconDarkGreenWDBC.png') {
    icon.shadow = imgRoute + 'mapIconShadowWDBC.png';
    icon.iconSize = new GSize(40,60);
    icon.iconAnchor = new GPoint(20,60);
    icon.infoWindowAnchor = new GPoint(20,15);
    icon.shadowSize = new GSize(80,60);
    } else {
    icon.shadow = imgRoute + 'mapIconShadow.png';
    icon.iconSize = new GSize(20,34);
    icon.iconAnchor = new GPoint(10,34);
    icon.infoWindowAnchor = new GPoint(10,0);
    }
  return icon
  }
//==============================================================================
function formatWindow (input) {
  var html = "<div class=\"gMapBubble\">";
  html += "<p>";
  if(input.Location != null) { html +=  "<strong>" + input.Location + "</strong>, ";  }
  if(input.Address != null) { html += input.Address; }
  if(input.Description != null) { html += "<br />" + input.Description; }
  if(input.Details != '') { html += "<br />" + input.Details ; }
  html += "</p>";
  html += "</div>";
  return html;
  }
//==============================================================================

//==============================================================================
//Directions
//==============================================================================
function showDirections(Destination, startDir) {
  document.getElementById("gMapInstructions").innerHTML = '';
  var startLoc = document.getElementById("gMapSetPostCode").value;
  dirReq = "NO";
  if(startLoc == 'Post Code or Address') {
    alert('You must enter a starting location. (' + startDir +')' );
    } else {
    if(startLoc != '') {
      startLoc = startLoc + ', UK';
        if(startDir == 'from') {
          setDirections(startLoc, Destination.lat() + ', ' + Destination.lng(), 'en_UK');
          } else {
          setDirections(Destination.lat() + ', ' + Destination.lng(), startLoc, 'en_UK');
          }
      gmap.setMapType( G_PHYSICAL_MAP );
      var Instructions = '<h3>Directions</h3><p>Directions ' + startDir + ' ' + startLoc + ' are listed below. Click on markers \"A\" (start) or \"B\" (destination), or on a route element below, to view detail at that location.</p>';
      document.getElementById("gMapInstructions").innerHTML =  Instructions;
      dirReq = "YES";
      document.getElementById("DirectionRequest").style.display = 'none';
      //DirectionRequest
      } else {
      alert('You must enter a starting location..');
      }
    }
  }
//==============================================================================
function setDirections(fromAddress, toAddress, locale ) {
  //alert('From: ' + fromAddress + ' To: ' + toAddress );
  dirPanel.load('from: ' + fromAddress + ' to: ' + toAddress, {"locale": locale } );
  }
//==============================================================================
function dirPanelOnError() {
  if(dirPanel.getStatus().code == G_GEO_BAD_REQUEST)
    alert('ERROR: A directions request could not be successfully parsed.')
  else
  if(dirPanel.getStatus().code == G_GEO_SERVER_ERROR)
   alert('ERROR: A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known')
  else
  if(dirPanel.getStatus().code == G_GEO_MISSING_ADDRESS)
   alert('ERROR: The directions could not be computed between the Points specified because the start address is not valid. (or that no query was specified in the input)')
  else
  if(dirPanel.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert('ERROR: The directions could not be computed between the Points specified because no corresponding geographic location could be found for the specified address. This may be due to the fact that the address is relatively new, or it may be incorrect.')
  else
  if(dirPanel.getStatus().code == G_GEO_UNAVAILABLE_ADDRESS)
    alert('ERROR: The directions could not be computed between the Points specified due to legal or contractual reasons.')
  else
  if(dirPanel.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS)
    alert('ERROR: The directions could not be computed between the Points specified. This is usually because there is no route available between the two Points, or because there is no data for routing in that region.')
  else
    alert('ERROR: An unknown error has occurred.') ;
    }
//==============================================================================
function hoverDetails(category) {
  if(category == 'Reset') { 
    document.getElementById("selInstructions").innerHTML= 'Press this to reset the map.'; 
    if (gEarthButton == 'Tourism') { gEarthButton = 'EARTH'; }
    }
  if(category == 'WDBC') { 
    document.getElementById("selInstructions").innerHTML= 'These markers indicate West Devon Borough Council Offices. Click to zoom into ones in the selected area.'; 
    if (gEarthButton == 'Business') { gEarthButton = 'WDBC';}
    }
  if(category == 'Leisure') { 
    document.getElementById("selInstructions").innerHTML= 'These markers indicate leisure facilities. Click to zoom into ones in the selected area.'; 
    if (gEarthButton == 'Recycling') { gEarthButton = 'Leisure';}
    }
  if(category == 'Tourism') { 
    document.getElementById("selInstructions").innerHTML= 'These markers indicate Tourist Information Centers. Click to zoom into ones in the selected area.'; 
    if (gEarthButton == 'Carpark') { gEarthButton = 'Tourism';}
    }
  if(category == 'CarPark') { 
    document.getElementById("selInstructions").innerHTML= 'These markers indicate Car Parks. Click to zoom into ones in the selected area.'; 
    if (gEarthButton == 'Leisure') { gEarthButton = 'Carpark';}
    }
  if(category == 'Recycling') { 
    document.getElementById("selInstructions").innerHTML= 'These markers indicate recycling centers. Click to zoom into ones in the selected area.'; 
    if (gEarthButton == 'WDBC') { gEarthButton = 'Recycling';}
    }
  if(category == 'Business') { 
    document.getElementById("selInstructions").innerHTML= 'These markers indicate business centers. Click to zoom into ones in the selected area.'; 
    gEarthButton = 'Business';
    }
  }
//==============================================================================
function zoomDetails(category) {
  document.getElementById("gMapInstructions").innerHTML= setInstructions();
  document.getElementById("DirectionRequest").style.display = 'none';
  dirPanel.clear();
  if(category == 'Recycling') { 
    if (regReq == "TAV") {
      gmap.setZoom(15); 
      gmap.panTo(new GLatLng(50.53058184, -4.15871143)); 
      //The above replaces:
      //gmap.setCenter(new GLatLng(50.53058184, -4.15871143), 15); 
      } else {
      gmap.setZoom(15); 
      gmap.PanTo(new GLatLng(50.74312768, -3.97911608)); 
      }
    return true;
    }
  if(category == 'Business') { 
    if (regReq == "TAV") {
      gmap.setZoom(15); 
      gmap.panTo(new GLatLng(50.56563192, -4.12138849)); 
      } else {
      gmap.setZoom(15); 
      gmap.panTo(new GLatLng(50.7419107, -3.97133499)); 
      }
    return true;
    }
  gmap.setZoom(15);
  gmap.panTo(gMapCenter);
  }
//==============================================================================
function hoverOutDetails() {
  document.getElementById("selInstructions").innerHTML= 'Place mouse over icons for more information.';
  }
//==============================================================================
function regionChange(selRegionValue) {
  if(selRegionValue == 'Tavistock') {
    gMapCenter=new GLatLng(50.550144247614575, -4.144881963729858);
    regReq="TAV";
    } else {
    gMapCenter=new GLatLng(50.73898440169782, -4.0034544467926025);
    regReq="OKE";
    }
  loadAllMarkers('initialise');
  }
//==============================================================================
function setInstructions() {
  var Instructions='';
  Instructions += '<p>'
  Instructions += 'Moving the mouse pointer over a map marker will display details about that location. '
  Instructions += 'Click on a map marker to zoom in on that location. ';
  Instructions += '<br />'
  Instructions += 'Selecting the '
  Instructions += '\"<b>Map</b>\", '
  Instructions += '\"<b>Satellite</b>\", '
  Instructions += '\"<b>Hybrid</b>\" or '
  Instructions += '\"<b>Terrain</b>\" '
  Instructions += 'view will change the map type. ';
  Instructions += 'Double clicking on the surface of the map will increase the magnification. '
  Instructions += 'The \"Satellite\" map type will allow the greatest magnification. ';
  Instructions += 'Click and drag the surface of the map to change the location. '
  Instructions += 'These controls can also be found in the top left of the map. <br>';
  Instructions += 'Click on an icon to magnify map before requesting directions.';
  Instructions += '</p>';
  return Instructions;
  }
