var map=null;

var SHOW_BUTTONS         = true;
var SHOW_BRANCHES        = true;
var SHOW_DISTANCE        = true;
var SHOW_STATIONS        = true;
var SHOWING_BUTTONS      = true;
var SHOWING_BRANCHES     = true;
var SHOWING_DISTANCE     = true;
var SHOWING_STATIONS     = true;
var DO_NOT_SHOW_BUTTONS  = false;
var DO_NOT_SHOW_BRANCHES = false;
var DO_NOT_SHOW_DISTANCE = false;
var DO_NOT_SHOW_STATIONS = false;

var distanceActive   = false;
var distanceStation1 = false;
var distanceStation2 = false;
var savedDistanceStation1 = false;
var savedDistanceStation2 = false;
var distanceMarker1  = false;
var distanceMarker2  = false;
var infoMarker       = false;
var distanceLine     = false;
var plottedLine      = false;

var current_mapview = "markers";    // values are: 'line', 'markers' and 'both'
var current_line = 0;
var current_branch = 0;
var current_station = false;
var backColour;
var fontColour;

//var labels_on = 0;
var background_colour = "#EEA";
var foreground_colour = "#900";
var stationSortOrder = "down";
var fullMapText = "All London Stations";
var distanceTable = "<table border='0' width='250' cellpadding='0' cellspacing='0' style='margin:auto;background-color:#F3F06B'><tr><td class='dist4' style='text-align:center;padding:2px 0 1px 0'><a href='javascript:processDistance(0,0,0)'>";

var TurnOnDistanceCheck  = distanceTable + "Distance check between stations</a>";
var TurnOffDistanceCheck = distanceTable + "Turn off distance check</a>";

var london_lat = 51.5002;
var london_lng = -0.1262;
var london_zoom = 9;
var zoom_level = london_zoom;

var lines=[];
var stations=[];
var branches=[];
var platforms=[];
var connections=[];
var selectedStations=[];

//var bounds;

/*
var green_icon = new GIcon();
green_icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
green_icon.iconSize   = new GSize(20, 34);
green_icon.shadowSize = new GSize(37, 34);
green_icon.iconAnchor = new GPoint(9, 34);
green_icon.infoWindowAnchor = new GPoint(9, 2);
green_icon.infoShadowAnchor = new GPoint(18, 25);
//green_icon.image = "http://www.google.com/mapfiles/marker.png";
green_icon.image = "images/green.png";
*/

var small_icon = new GIcon();
//small_icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
//small_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
small_icon.shadow = "images/small_icon_shadow.png";
small_icon.iconSize = new GSize(12, 20);
small_icon.shadowSize = new GSize(22, 20);
small_icon.iconAnchor = new GPoint(6, 20);
small_icon.infoWindowAnchor = new GPoint(5, 1);      

smallRedMarker    = new GIcon(small_icon,"images/small_red_icon.png"); 
smallBlueMarker   = new GIcon(small_icon,"images/small_blue_icon.png"); 
smallGreenMarker  = new GIcon(small_icon,"images/small_green_icon.png"); 
smallYellowMarker = new GIcon(small_icon,"images/small_yellow_icon.png"); 
//smallRedMarker = new GIcon(small_icon,"http://labs.google.com/ridefinder/images/mm_20_red.png"); 
//smallBlueMarker = new GIcon(small_icon,"http://labs.google.com/ridefinder/images/mm_20_blue.png"); 
//smallGreenMarker = new GIcon(small_icon,"http://labs.google.com/ridefinder/images/mm_20_green.png"); 
//smallYellowMarker = new GIcon(small_icon,"http://labs.google.com/ridefinder/images/mm_20_yellow.png"); 

var large_icon = new GIcon();
//large_icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
large_icon.shadow = "images/large_icon_shadow.png";
large_icon.iconSize   = new GSize(20, 34);
large_icon.shadowSize = new GSize(37, 34);
large_icon.iconAnchor = new GPoint(9, 34);
large_icon.infoWindowAnchor = new GPoint(9, 2);
//large_icon.infoShadowAnchor = new GPoint(18, 25);
//red_icon.image = "http://www.google.com/mapfiles/marker.png";
//large_icon.image = "images/red-dot.png";

//largeRedMarker   = new GIcon(large_icon,"images/large_red_dot.png"); 
largeRedMarker   = new GIcon(large_icon,"images/large_red012.png"); 
//largeGreenMarker = new GIcon(large_icon,"images/large_green_arrow.png"); 
largeGreenMarker = new GIcon(large_icon,"images/large_green070.png"); 

var loadingText = "<span class='loadingText'>Loading Station data takes about 5 seconds...</span>";
var introText = "<div class='introText'>View Londons Tube Stations line by line, station by station. The map shows most London Tube and some National Rail Stations.<br><br>To visit the stations individually select from the Stations dropdown above.<br><br>To see the layout of a line including its different branches, then choose from the Lines dropdown above.<br><br>Lines can be viewed as markers, coloured lines or both.<br><br>Use the distance check tool to see the distance between any 2 stations in both miles and kilometres.</div>";
var introHeader = "<span class='introHeader'>London Stations</span><br>";

var default_marker = smallYellowMarker;

window.onload = onPageLoad;

// -------------------------------------------------------------------------------
function onPageLoad() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(london_zoom));
    //map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(zoom_level));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    $('mapheader').innerHTML = loadingText;

    loadData();

    $('nav_header').innerHTML = introHeader;
    $('nav_stations').innerHTML = introText;
  }
}

// -------------------------------------------------------------------------------
function loadData() {

  // Start with this one as it takes the longest to load
  GDownloadUrl("load/generateStationsXML.php", function(data) {
    var xml = GXml.parse(data);
    var row = xml.documentElement.getElementsByTagName("row");
    // create null object at element 0, so all station ids are the same element number in the array
    stations[0]        = new createStationObject(0,"",0,0,0);
    stations[0].marker = new createMarkerObject(default_marker,0,"",0,0);
    //stations[0].green_marker = new createMarkerObject("green",0,"",0,0);
    for (var i=1;i<row.length+1;i++) {
      stations[i] = new createStationObject(
                           row[i-1].getAttribute("id"),
                           row[i-1].getAttribute("station_name"),
                           parseFloat(row[i-1].getAttribute("lat")),
                           parseFloat(row[i-1].getAttribute("lng")),
                           row[i-1].getAttribute("zoom")
                       );
      stations[i].marker = new createMarkerObject(default_marker,i,stations[i].station_name,stations[i].lat,stations[i].lng);
    }
    //$('debug').innerHTML += "stations: "+stations.length+"<br>";

    showAllStations();
  });

  GDownloadUrl("load/generateLinesXML.php", function(data) {
    var xml = GXml.parse(data);
    var row = xml.documentElement.getElementsByTagName("row");
    var i=0;
    lines[i++] = new createLineObject(0,"","","",0,0,0);
    for (;i<row.length+1;i++) {
      lines[i] = new createLineObject(
                           row[i-1].getAttribute("id"),
                           row[i-1].getAttribute("line_name"),
                           row[i-1].getAttribute("line_colour"),
                           row[i-1].getAttribute("name_colour"),
                           parseFloat(row[i-1].getAttribute("lat")),
                           parseFloat(row[i-1].getAttribute("lng")),
                           row[i-1].getAttribute("zoom")
                       );
    }
    //$('debug').innerHTML += "lines: "+lines.length+"<br>";
  });

  GDownloadUrl("load/generateBranchesXML.php", function(data) {
    var xml = GXml.parse(data);
    var row = xml.documentElement.getElementsByTagName("row");
    var i=0;
    branches[i++] = new createBranchObject(0,0,"");
    for (;i<row.length+1;i++) {
      branches[i] = new createBranchObject(
                           row[i-1].getAttribute("id"),
                           row[i-1].getAttribute("line_id"),
                           row[i-1].getAttribute("name")
                       );
    //$('debug').innerHTML += "branches["+i+"]: "+branches[i].id+", "+branches[i].name+"<br>";
    }
    //$('debug').innerHTML += "branches: "+branches.length+"<br>";
  });

  GDownloadUrl("load/generatePlatformsXML.php", function(data) {
    var xml = GXml.parse(data);
    var row = xml.documentElement.getElementsByTagName("row");
    for (var i=0;i<row.length;i++) {
      platforms[i] = new createPlatformObject(
                           row[i].getAttribute("branch_id"),
                           row[i].getAttribute("station_id"),
                           row[i].getAttribute("position")
                       );
    }
    //$('debug').innerHTML += "platforms: "+platforms.length+"<br>";
  });

  GDownloadUrl("load/generateConnectionsXML.php", function(data) {
    var xml = GXml.parse(data);
    var row = xml.documentElement.getElementsByTagName("row");
    for (var i=0;i<row.length;i++) {
      connections[i] = new createConnectionObject(
                           row[i].getAttribute("id"),
                           row[i].getAttribute("branch_id"),
                           row[i].getAttribute("station1_id"),
                           row[i].getAttribute("station2_id")
                       );
    }
    //$('debug').innerHTML += "connections: "+connections.length+"<br>";
  });

}

// -------------------------------------------------------------------------------
function showAllStations() {
  for (var i=0;i<stations.length;i++) {
    map.addOverlay(stations[i].marker);
  }
  document.getElementById("mapheader").style.backgroundColor = background_colour;
  $('mapheader').innerHTML = "<p class='p14' style='color:"+foreground_colour+";padding-left:10px;'>The map shows <span class='p24' style='color:"+foreground_colour+"'>"+fullMapText+"</span></p>";
}

// -------------------------------------------------------------------------------
function createBranchObject(id,line_id,name) {
  this.id      = id;
  this.line_id = line_id;
  this.name    = name;
}

// -------------------------------------------------------------------------------
function createPlatformObject(branch_id,station_id,position) {
  this.branch_id  = branch_id;
  this.station_id = station_id;
  this.position   = position;
}

// -------------------------------------------------------------------------------
function createConnectionObject(id,branch_id,station1_id,station2_id) {
  this.id          = id;
  this.branch_id   = branch_id;
  this.station1_id = station1_id;
  this.station2_id = station2_id;
}

// -------------------------------------------------------------------------------
function createLineObject(id,line_name,line_colour,name_colour,lat,lng,zoom) {
  this.id          = id;
  this.line_name   = line_name;
  this.line_colour = line_colour;
  this.name_colour = name_colour;
  this.lat         = lat;
  this.lng         = lng;
  this.zoom        = zoom;
}

// -------------------------------------------------------------------------------
function createStationObject(id,station_name,lat,lng,zoom) {
  this.id   = id; 
  this.station_name = station_name; 
  this.lat  = lat; 
  this.lng  = lng; 
  this.zoom = zoom;
  this.marker = null;
  //this.green_marker = null;
  //this.isSelected = false;
}

// -------------------------------------------------------------------------------
function createMarkerObject(icon,station_id,station_name,station_lat,station_lng) {

  var point = new GLatLng(station_lat,station_lng);
  //if (colour.toLowerCase() == "green") {
    //var marker = new PdMarker(point,green_icon);
  //} else if (colour.toLowerCase() == "red") {
    //var marker = new PdMarker(point,smallRedMarker);
  //} else {
    //var marker = new PdMarker(point,smallRedMarker);    // red is the default
  //}

  var marker = new PdMarker(point,icon);

  // Uppercase each word in the station name
  var station_name_cc = camelCase(station_name);
  marker.setTooltip(station_name_cc);

  //var html = "<table><tr><td class='p16'>" + station_name + "</td></tr><tr><td class='p14'>"+line_name+"</td></tr></table>";

  //marker.setHoverImage("images/green.png");

  GEvent.addListener(marker, "click", function() {
    //var station_info = "<table style='background-color:#DE3'><tr><td style='text-align:left;font:16px arial;color:#900;'>"+camelCase(station_name)+" station on the</td></tr><tr><td style='text-align:left;font:14px arial;color:#900;'>"+camelCase(line_name)+" line.</td></tr></table>";
    //var point = new GLatLng(station_lat,station_lng);
    //map.openInfoWindowHtml(point, station_info);

    //showStationMap(station_id);

    //updateStationSelect(station_id);

    //if (marker.getMouseOutEnabled()) {
      //// don't hide on hover, disable setImage, restoreImage
      //marker.setMouseOutEnabled(false);
      //marker.setOpacity(100); // not transparent
      //marker.setTooltipClass("markerTooltipAlternate"); // change css class
    //} else {
      //marker.setMouseOutEnabled(true); // hide after hover
      //marker.setOpacity(70); // 30% transparent
      //marker.resetTooltipClass(); // restore default css class
    //}

    //toggleSelected(station_id);

    //marker.isSelected = true;
  });

  // change marker appearance when hovering
  //GEvent.addListener(marker, "mouseover", function() {
    //if (! selectedStation(this)) {
      //if (colour.toLowerCase() == "green") {
        //marker.setImage("images/red-dot.png");
      //} else {
        //marker.setImage("images/green.png");
      //}
      //marker.topMarkerZIndex(); // bring marker to top
    //}
  //}); 

  //GEvent.addListener(marker, "mouseout", function() {
    //marker.restoreImage();
    //if (! selectedStation(this)) {
      //if (colour.toLowerCase() == "green") {
        //marker.setImage("images/green.png");
      //} else {
        //marker.setImage("images/red-dot.png");
      //}
      //marker.restoreMarkerZIndex();
    //}
  //});

  return(marker);
}

// -------------------------------------------------------------------------------
function createDistanceObject(station_id) {

  var point = new GLatLng(station_lat,station_lng);
  if (colour.toLowerCase() == "green") {
    //var marker = new PdMarker(point,green_icon);
  } else if (colour.toLowerCase() == "red") {
    var marker = new PdMarker(point,red_icon);
  } else {
    var marker = new PdMarker(point,red_icon);    // red is the default
  }

  // Uppercase each word in the station name
  var station_name_cc = camelCase(station_name);
  marker.setTooltip(station_name_cc);

  //var html = "<table><tr><td class='p16'>" + station_name + "</td></tr><tr><td class='p14'>"+line_name+"</td></tr></table>";

  //marker.setHoverImage("images/green.png");

  GEvent.addListener(marker, "click", function() {
    //var station_info = "<table style='background-color:#DE3'><tr><td style='text-align:left;font:16px arial;color:#900;'>"+camelCase(station_name)+" station on the</td></tr><tr><td style='text-align:left;font:14px arial;color:#900;'>"+camelCase(line_name)+" line.</td></tr></table>";
    //var point = new GLatLng(station_lat,station_lng);
    //map.openInfoWindowHtml(point, station_info);

    //showStationMap(station_id);

    //updateStationSelect(station_id);

    //if (marker.getMouseOutEnabled()) {
      //// don't hide on hover, disable setImage, restoreImage
      //marker.setMouseOutEnabled(false);
      //marker.setOpacity(100); // not transparent
      //marker.setTooltipClass("markerTooltipAlternate"); // change css class
    //} else {
      //marker.setMouseOutEnabled(true); // hide after hover
      //marker.setOpacity(70); // 30% transparent
      //marker.resetTooltipClass(); // restore default css class
    //}

    //toggleSelected(station_id);

    //marker.isSelected = true;
  });

  // change marker appearance when hovering
  //GEvent.addListener(marker, "mouseover", function() {
    //if (! selectedStation(this)) {
      //if (colour.toLowerCase() == "green") {
        //marker.setImage("images/red-dot.png");
      //} else {
        //marker.setImage("images/green.png");
      //}
      //marker.topMarkerZIndex(); // bring marker to top
    //}
  //}); 

  //GEvent.addListener(marker, "mouseout", function() {
    //marker.restoreImage();
    //if (! selectedStation(this)) {
      //if (colour.toLowerCase() == "green") {
        //marker.setImage("images/green.png");
      //} else {
        //marker.setImage("images/red-dot.png");
      //}
      //marker.restoreMarkerZIndex();
    //}
  //});

  return(marker);
}

// -------------------------------------------------------------------------------
function resetLineSelect() {
  document.lineform.line.options[0].selected = true;
}

// -------------------------------------------------------------------------------
function resetStationSelect() {
  document.stationform.station.options[0].selected = true;
}

// -------------------------------------------------------------------------------
function updateStationSelect(station_id) {
  var i=0;
  var found = false;
  while ((i < document.stationform.station.length) && !found) {
    this_station_id = document.stationform.station.options[i].value;
    if (this_station_id == station_id) {
      document.stationform.station.options[i].selected = true;
      found = true;
    } 
    i++;
  }
}

// -------------------------------------------------------------------------------
function camelCase(str) {
  var words = [];
  var ccStr = "";
  words = str.split(' ');
  for(i=0;i<words.length;i++) {
    if (words[i].length == 1) {
      ccStr += words[i]+" ";
    } else {
      ccStr += words[i].substr(0, 1).toUpperCase() + words[i].substr(1)+" ";
    }
  }
  ccStr = ccStr.replace(/^\s+|\s+$/g, '') ;
  return(ccStr);
}

// -------------------------------------------------------------------------------
function clearMap() {
  map.clearOverlays();
  //for (var i=0;i<stations.length;i++) {
    //if (! stations[i].marker.isHidden()) {
      //stations[i].marker.hide();
    //}
  //}
}

// -------------------------------------------------------------------------------
function createBranchLinks(line_id) {
  var branchtable="";
  if (! hasBranches(line_id)) {
    return(branchtable);
  }  

  var j=0;
  var branch=[];
  for(var i=0;i<branches.length;i++) {
    if (branches[i].line_id == line_id) {
      branch[j++] = branches[i];
    }
  }

  //clearSelectedStations();

  if (branch.length > 0) {
    branchtable = "<table border='0' width='244' cellspacing='0' cellpadding='0'>";
    //branchtable += "<tr><td class='branchlistitem'>";
    //branchtable += "<a href=\"javascript:toggleLabels()\">";
    //branchtable += "Turn Labels ";
    //branchtable += "<div id='labelindicator' style='display:inline'>On</div>";
    //branchtable += "</a>";
    //branchtable += "</td></tr>";
    i=0;
    while(i < branch.length) {
      branchtable += "<tr><td class='branchlistitem'>";
      if (branch[i].id == current_branch) {
        branchtable += "<span style='background-color:#F3F06B'>";
      } else {
        branchtable += "<a href=\"javascript:checkDistance(0,"+branch[i].line_id+","+branch[i].id+","+SHOW_BRANCHES+","+SHOW_BUTTONS+","+SHOWING_DISTANCE+","+SHOW_STATIONS+")\">";
      }

      branchname = "";
      if (branch[i].name == "allstations") {
        branchtable += "All ("+numberOfStations(branch[i].id)+" stations)";
      } else {
        firstStation = stations[firstStationOnBranch(branch[i].id)].station_name;
        lastStation  = stations[lastStationOnBranch(branch[i].id)].station_name;
        if (lines[line_id].line_name.toLowerCase() == "northern") {
          if (branch[i].name.substr(0,12).toLowerCase() == "edgware-bank") {
            branchname = "Edgware - Bank - Morden";
          } else if (branch[i].name.substr(0,12).toLowerCase() == "edgware-char") {
            branchname = "Edgware - ChrngX - Morden";
          } else if (branch[i].name.substr(0,15).toLowerCase() == "highbarnet-bank") {
            branchname = "HighBarnet - Bank - Morden";
          } else if (branch[i].name.substr(0,15).toLowerCase() == "highbarnet-char") {
            branchname = "HighBarnet - ChgX - Morden";
          } else {
            branchname = camelCase(firstStation)+" to "+camelCase(lastStation);
          }
        } else {
          if (lastStation.substr(0,8).toLowerCase() == "heathrow") {
            branchname = camelCase(firstStation)+" to Heathrow";
          } else if (firstStation.substr(0,12).toLowerCase() == "edgware road") {
            branchname = "Edgware Rd to "+camelCase(lastStation);
            if (lastStation.substr(0,15).toLowerCase() == "ealing broadway") {
              branchname = camelCase(firstStation)+" to Ealing Bwy";
            }
          } else {
            branchname = camelCase(firstStation)+" to "+camelCase(lastStation);
          }
        }
        branchtable += branchname + " ("+numberOfStations(branch[i].id)+" stations)";
      }

      if (branch[i].id == current_branch) {
        branchtable += "</span>";
      } else {
        branchtable += "</a>";
      }
      branchtable += "</td></tr>";

      i++;
    }
    branchtable += "</table>";
  }

  return(branchtable);
}

// -------------------------------------------------------------------------------
function checkDistance(source,line_id,branch_id,showBranches,showButtons,showDistance,showStations) {
  clearDistanceCheck();
  if (source == 0) {
    var j=0;
    rows=[];
    for(i=0;i<branches.length;i++) {
      if (branches[i].line_id == line_id) {
        rows[j++] = branches[i].id;
      }
    }
    var j=0;
    selectedStations=[];
    selectedStations.length=0;
    for(i=0;i<rows.length;i++) {
      s1 = firstStationOnBranch(rows[i]);
      s2 = lastStationOnBranch(rows[i]);
      if (!stationSelected(s1)) {
        selectedStations[j++] = s1;
      }
      if (!stationSelected(s2)) {
        selectedStations[j++] = s2;
      }
    }
  }
  showMap(line_id,branch_id,showBranches,showButtons,showDistance,showStations);
}

// -------------------------------------------------------------------------------
function toggleLabels() {
  if (labels_on == 1) {
    labels_on = 0;
    $('labelindicator').innerHTML = "On";
    hideLabels();
  } else {
    labels_on = 1;
    $('labelindicator').innerHTML = "Off";
    showLabels();
  }
}

// -------------------------------------------------------------------------------
function showLabels() {
  var branch = current_branch;
  for(var i=0;i<platforms.length;i++) {
    if (platforms[i].branch_id == branch) {
      stations[platforms[i].station_id].marker.showTooltip();
    }
  }
}

// -------------------------------------------------------------------------------
function hideLabels() {
  var branch = current_branch;
  for(var i=0;i<platforms.length;i++) {
    if (platforms[i].branch_id == branch) {
      stations[platforms[i].station_id].marker.hideTooltip();
    }
  }
}

// -------------------------------------------------------------------------------
function numberOfStations(branch_id) {
  var count=0;
  for(var i=0;i<platforms.length;i++) {
    if (platforms[i].branch_id == branch_id) {
      count++;
    }
  }
  return(count);
}

// -------------------------------------------------------------------------------
function showPlatformMarkers(line_id,branch_id) {
  // line_id not currently used
  var rows=[];
  for(var i=0;i<platforms.length;i++) {
    if (platforms[i].branch_id == branch_id) {
      map.addOverlay(stations[platforms[i].station_id].marker);
      //var point = new GLatLng(stations[platforms[i].station_id].lat,stations[platforms[i].station_id].lng);
      //bounds.extend(point);
    }
  }
  showSelectedStations(branch_id);
}

// -------------------------------------------------------------------------------
function plotLineOnly(line_id,branch_id) {
  rows=[];
  j=0;
  for (var i=0;i<connections.length;i++) {
    if (connections[i].branch_id == branch_id) {
      rows[j++] = connections[i];
    }
  }
  //var colour = lines[line_id].line_colour;
  colour = "900";
  opacity   = 1;  // set between 0 and 1
  thickness = 8;  // pixels wide
  //if (lines[line_id].line_name.toLowerCase() == "circle") {
    //thickness = 4;
  //}
  for(var i=0;i<rows.length;i++) {
//$('debug').innerHTML += "sid: "+rows[i].station1_id+", "+rows[i].station2_id+"<br>";
    drawLine(stations[rows[i].station1_id].lat,
             stations[rows[i].station1_id].lng,
             stations[rows[i].station2_id].lat,
             stations[rows[i].station2_id].lng,
	     //lines[line_id].line_colour,
             "900",
	     thickness,
             opacity
            );
    //var point = new GLatLng(stations[rows[i].station1_id].lat,stations[rows[i].station1_id].lng);
    //bounds.extend(point);
  }
  showSelectedStations(branch_id);
}

// -------------------------------------------------------------------------------
function drawLine(lat1,lng1,lat2,lng2,colour,thickness,opacity) {
  plottedLine = new GPolyline([
  new GLatLng(lat1,lng1),
  new GLatLng(lat2,lng2)
  ], "#"+colour, thickness, opacity);
  map.addOverlay(plottedLine);
}

// -------------------------------------------------------------------------------
function showStationMap(station_id) {
  if (station_id == 0) {
    var station_id = $('station').value;
  }

  $('nav_stations').innerHTML = "";
  $('nav_branches').innerHTML = "";
  $('nav_header').innerHTML = "";

  hideBranches();
  hideViewButtons();
  hideDistanceCheck();
  if (current_station) {
    stations[current_station].marker = new createMarkerObject(default_marker,current_station,stations[current_station].station_name,stations[current_station].lat,stations[current_station].lng);
  }
  clearSelectedStations();
  clearMap();

  if (station_id == "All Stations") {

    map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(london_zoom));
    //map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(zoom_level));
    resetLineSelect();
    $('nav_header').innerHTML = introHeader;
    $('nav_stations').innerHTML = introText;
    showAllStations();

  } else if (station_id == "Select the Station") {

    map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(london_zoom));
    //map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(zoom_level));
    resetLineSelect();
    $('nav_header').innerHTML = introHeader;
    $('nav_stations').innerHTML = introText;
    showAllStations();

  } else {

    map.setCenter(new GLatLng(parseFloat(stations[station_id].lat),parseFloat(stations[station_id].lng)),parseFloat(stations[station_id].zoom));

    //map.setCenter(new GLatLng(parseFloat(stations[station_id].lat),parseFloat(stations[station_id].lng)),parseFloat(zoom_level));

    //map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(stations[station_id].zoom));
    //if (line_id == lineId("metropolitan")) {
      //map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(london_zoom));
    //}
    //else
    //{
      //map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(stations[station_id].zoom));
    //}
    //map.addOverlay(stations[station_id].marker);
    //var thispoint = new GLatLng(stations[station_id].lat,stations[station_id].lng);
    //var station_info = "<table style='background-color:#DE3'><tr><td style='text-align:left;font:16px arial;color:#900;'>"+camelCase(stations[station_id].station_name)+" station on the</td></tr><tr><td style='text-align:left;font:14px arial;color:#900;'>"+camelCase(line_name)+" line.</td></tr></table>";
    //var station_info = "<table style='background-color:#DE3'><tr><td style='text-align:left;font:16px arial;color:#900;'>"+camelCase(stations[station_id].station_name)+" station</td></tr></table>";
    //map.openInfoWindowHtml(thispoint, station_info);
    //stations[station_id].marker.showTooltip();

    document.lineform.line.options[0].selected = true;
    document.getElementById("mapheader").style.backgroundColor = background_colour;
    //$('mapheader').setStyle('backgroundColor',background_colour);

    $('nav_header').innerHTML = "<p class='p19'>" + camelCase(stations[station_id].station_name) + "</p>";
    $('nav_stations').innerHTML = createLineRows(station_id);

    $('mapheader').innerHTML = "<p class='p14' style='color:"+foreground_colour+";padding-left:10px;'>The map shows <span class='p24' style='color:"+foreground_colour+"'>"+camelCase(stations[station_id].station_name)+" station</span></p>";

    // Create a large red marker
    current_station = station_id;
    stations[station_id].marker = new createMarkerObject(largeRedMarker,station_id,stations[station_id].station_name,stations[station_id].lat,stations[station_id].lng);
//$('debug').innerHTML += "marker<br>";
    // Add the station to the selected list
    selectStation(station_id);
  }
}

// -------------------------------------------------------------------------------
function createLineRows(station_id) {
  var str = "<div style='padding:0 0 4px 6px;text-align:left;font:normal 14px arial;color:#900'>";
  if (stations[station_id].station_name == "Heathrow Terminals 1 2 3") {
    str = str + "are ";
  } else {
    str = str + "station is ";
  }
  str = str + "on the following lines</div>";

  var rows = getAllLinesByStationId(station_id);
  for(var i=0;i<rows.length;i++) {
    str = str + "<a href=\"javascript:showMap("+rows[i]+","+getAllStationsBranchId(rows[i])+","+DO_NOT_SHOW_BRANCHES+","+SHOW_BUTTONS+","+DO_NOT_SHOW_DISTANCE+","+DO_NOT_SHOW_STATIONS+")\"><div style='width:240px;margin:2px;font:16px arial;padding:2px 4px;background-color:#"+lines[rows[i]].line_colour+";color:#"+lines[rows[i]].name_colour+"'>" + camelCase(lines[rows[i]].line_name) + "</div></a>";
    //current_mapview = "line";
    current_mapview = "both";
    showPlatformMarkers(rows[i],getAllStationsBranchId(rows[i]));
    plotLineOnly(rows[i],getAllStationsBranchId(rows[i]));
  }
  //if (i > 1) {
    //str = str + "<a href=\"javascript:showMap(999,"+getAllStationsBranchId(rows[i])+","+DO_NOT_SHOW_BRANCHES+","+SHOW_BUTTONS+","+DO_NOT_SHOW_DISTANCE+","+DO_NOT_SHOW_STATIONS+")\"><div style='width:240px;margin:2px;font:16px arial;padding:2px 4px;background-color:#"+lines[rows[i]].line_colour+";color:#"+lines[rows[i]].name_colour+"'>" + camelCase(lines[rows[i]].line_name) + "</div></a>";
  //}
  str = str + "<br>";
  return(str);
}

// -------------------------------------------------------------------------------
// Marker selection functions ------------------------------------------------------------
function selectStation(station_id) {

  //if (current_mapview == "line") {
    map.addOverlay(stations[station_id].marker);
  //}
  stations[station_id].marker.setTooltipHiding(false); // never hide tooltip
  stations[station_id].marker.showTooltip();
  stations[station_id].marker.setImage("images/small_red_icon.png");
  stations[station_id].marker.topMarkerZIndex();
//$('debug').innerHTML += "bfadd: "+selectedStations.length+"<br>";
  selectedStations[selectedStations.length] = station_id;
//$('debug').innerHTML += "afadd: "+selectedStations.length+"<br>";
}

// -------------------------------------------------------------------------------
function deSelectStation(i,station_id) {
  stations[station_id].marker.setTooltipHiding(true); // allow to hide tooltip
  stations[station_id].marker.hideTooltip();
  //stations[station_id].marker.restoreMarkerZIndex();
  //stations[station_id].marker.restoreImage();
//$('debug').innerHTML += "current_mapview: "+current_mapview+"<br>";
  //if (current_mapview == "line") {
    //map.removeOverlay(stations[station_id].marker);
  //}
  selectedStations.splice(i,1);
}

// -------------------------------------------------------------------------------
function hideAllMarkers() {
  for (var i=0;i<selectedStations.length;i++) {
    stations[i].marker.hide();
  }
}

// -------------------------------------------------------------------------------
function hideAllToolTips() {
  for (var i=0;i<selectedStations.length;i++) {
    stations[i].marker.setTooltipHiding(true); // allow to hide tooltip
    stations[i].marker.hideTooltip();
  }
}

// -------------------------------------------------------------------------------
function clearSelectedStations() {
  for (var i=0;i<selectedStations.length;i++) {
    deSelectStation(i,selectedStations[i]);
  }
  selectedStations.length = 0;
}

// -------------------------------------------------------------------------------
function getAllLinesByStationId(station_id) {
  var j=0;
  var allrows=[];
  for(var i=0;i<platforms.length;i++) {
    if (platforms[i].station_id == station_id) {
      allrows[j++] = platforms[i];
    }
  }
  j=0;
  var rows=[];
  for(i=0;i<allrows.length;i++) {
    if (branches[allrows[i].branch_id].name == "allstations") {
      rows[j++] = branches[allrows[i].branch_id].line_id;
    }
  }
  return(rows);
}

// -------------------------------------------------------------------------------
function showLineMap() {
  var i=0;
  var line_id = $('line').value;

  hideBranches();
  hideViewButtons();
  hideDistanceCheck();
  clearSelectedStations();
  clearMap();
  current_mapview = "both";

  if (line_id == "Select the Line") {
    //the_name = "The city of London";
    name_colour = "900";

    current_branch = 0;

    map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(london_zoom));
    //map.setCenter(new GLatLng(parseFloat(london_lat),parseFloat(london_lng)),parseFloat(zoom_level));
    showAllStations();

    $('nav_header').innerHTML = introHeader;
    $('nav_stations').innerHTML = introText;

  } else {

    line_name = camelCase(lines[line_id].line_name);

    // Get the branch id for this line - allstations branch
    current_branch = getAllStationsBranchId(line_id);
    if (! stationOnBranch(document.stationform.station.value,current_branch)) {
      resetStationSelect();
    }
    //else { $('debug').innerHTML += "true<br>"; }
      
    //document.stationform.station.options[i].selected = true;
    //clearSelectedStations();

    // Draw the markers
    showMap(line_id,current_branch,SHOW_BRANCHES,SHOW_BUTTONS,SHOW_DISTANCE,SHOW_STATIONS);

    // Draw the selected stations
    showSelectedStations(current_branch);

    // Show the line name
    $('nav_header').innerHTML = "<p class='p16b'>The " + line_name + " line</p>";
  }
}

// -------------------------------------------------------------------------------
function showSelectedStations(branch_id) {
  var rows=[];
  var j=0;
  for (var i=0;i<platforms.length;i++) {
    if (platforms[i].branch_id == branch_id) {
      rows[j++] = platforms[i].station_id;
    }
  }
  for (i=0;i<rows.length;i++) {
    for (j=0;j<selectedStations.length;j++) {
      if (selectedStations[j] == rows[i]) {
        //selectStation(selectedStations[j]);
        if (current_mapview == "line") {
          map.addOverlay(stations[selectedStations[j]].marker);
        }
        stations[selectedStations[j]].marker.setTooltipHiding(false); // never hide tooltip
        stations[selectedStations[j]].marker.showTooltip();
        stations[selectedStations[j]].marker.setImage("images/large_red012.png");
        stations[selectedStations[j]].marker.topMarkerZIndex();
      }
    }
  }
}

// -------------------------------------------------------------------------------
function hasBranches(line_id) {
  var i=0;
  while (i < branches.length) {
    if ((branches[i].line_id == line_id) && (branches[i].name != "allstations")) {
      return(true);
    }
    i++
  }
  return(false);
}

// -------------------------------------------------------------------------------
function changeMap(radiobutton) {
  current_mapview = radiobutton.value;
  checkDistance(1,document.whatmap.theline.value,document.whatmap.thebranch.value,SHOWING_BRANCHES,SHOWING_BUTTONS,SHOWING_DISTANCE,SHOWING_STATIONS);
} 

// -------------------------------------------------------------------------------
function createStationList(line_id,branch_id) {
  var j=0;
  var rows=[];

  if (stationSortOrder == "up") {
    for(var i=0;i<platforms.length;i++) {
      if (platforms[i].branch_id == branch_id) {
        rows[j++] = platforms[i];
      }
    }
  } else {
    for(var i=platforms.length;i;i--) {
      if (platforms[i-1].branch_id == branch_id) {
        rows[j++] = platforms[i-1];
      }
    }
  }
  var size=11;
  var thetable = "<table border='0' width='240' style='margin:auto'><tr>";
  for(i=0;i<rows.length;i++) {

    if      (line_id == lineId("metropolitan")) { size=11; if ((i % 2) == 0) { thewidth='120'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("circle"))       { size=11; if ((i % 2) == 0) { thewidth='120'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("jubilee"))      { size=11; if ((i % 2) == 0) { thewidth='120'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("bakerloo"))     { size=11; if ((i % 2) == 0) { thewidth='120'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("victoria"))     { size=11; if ((i % 2) == 0) { thewidth='120'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("hammersmith & city")) { size=11; if ((i % 2) == 0) { thewidth='120'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("northern"))     { size=9; if ((i % 3) == 0) { thewidth='80'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("district"))     { size=9; if ((i % 3) == 0) { thewidth='80'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("piccadilly"))   { size=9; if ((i % 3) == 0) { thewidth='80'; thetable += "</tr><tr>"; } }
    else if (line_id == lineId("central"))      { size=10; if ((i % 3) == 0) { thewidth='80'; thetable += "</tr><tr>"; } }

    if (stationSelected(rows[i].station_id)) {
      bgcolour = "FFFF33";
      fgcolour = "FF0000";
    } else {
      bgcolour = "EEEECC";
      fgcolour = "990000";
    }
    thetable += "<td width='"+thewidth+"' id='tdsbgc"+rows[i].station_id+"' style='background-color:#"+bgcolour+";vertical-align:top;padding-left:2px'>";
    //if (distanceActive) {
      //thetable += "<a id='asbgc"+rows[i].station_id+"' href=\"javascript:processDistance("+line_id+","+branch_id+","+rows[i].station_id+")\" style='color:#"+fgcolour+";font:"+size+"px arial;text-decoration:none;' onmouseover=\"stationHover("+rows[i].station_id+")\" onmouseout=\"stationUnHover("+rows[i].station_id+")\"><div width='100%'>"+camelCase(stations[rows[i].station_id].station_name)+"</div></a>";
    //} else {
      thetable += "<a id='asbgc"+rows[i].station_id+"' href=\"javascript:processDistance("+line_id+","+branch_id+","+rows[i].station_id+")\" style='color:#"+fgcolour+";font:"+size+"px arial;text-decoration:none;' onmouseover=\"stationHover("+rows[i].station_id+")\" onmouseout=\"stationUnHover("+rows[i].station_id+")\"><div width='100%'>"+camelCase(stations[rows[i].station_id].station_name)+"</div></a>";
    //}
    thetable += "</td>";
  }
  thetable += "</tr></table>";
  return(thetable);
}

// -------------------------------------------------------------------------------
function stationHover(station_id) {
  thistdid = "tdsbgc"+station_id;
  thisaid  = "asbgc"+station_id;
  backColour = document.getElementById(thistdid).style.backgroundColor;
  fontColour = document.getElementById(thisaid).style.color;
  document.getElementById(thistdid).style.backgroundColor = '#c0c0c0'; 
  document.getElementById(thisaid).style.color = '#990000'; 
  notfound = true;
  for(i=0;i<selectedStations.length;i++) {
    if (selectedStations[i] == station_id) {
      notfound = false;
    }
  }
  if (notfound) {
    stations[station_id].marker.setImage("images/small_red_icon.png");
    stations[station_id].marker.showTooltip();
    stations[station_id].marker.topMarkerZIndex();
  }
}

// -------------------------------------------------------------------------------
function stationUnHover(station_id) {
  thistdid = "tdsbgc"+station_id;
  thisaid  = "asbgc"+station_id;
  document.getElementById(thistdid).style.backgroundColor = backColour;
  document.getElementById(thisaid).style.color = fontColour;
  notfound = true;
  for(i=0;i<selectedStations.length;i++) {
    if (selectedStations[i] == station_id) {
      notfound = false;
    }
  }
  if (notfound) {
    stations[station_id].marker.hideTooltip();
    stations[station_id].marker.restoreImage();
    stations[station_id].marker.restoreMarkerZIndex();
  }
}

// -------------------------------------------------------------------------------
function stationSelected(station_id) {
  for(var i=0;i<selectedStations.length;i++) {
    if (selectedStations[i] == station_id) {
      return(true);
    }
  }
  return(false);
}

// -------------------------------------------------------------------------------
function toggleSelected(station_id) {

  if (station_id > 0) {
    // If marker is already selected, then remove it
    var found = false;
    for(var i=0;i<selectedStations.length;i++) {
      if (selectedStations[i] == station_id) {
        deSelectStation(i,station_id);
        thistdid = "tdsbgc"+station_id;
        thisaid  = "asbgc"+station_id;
        document.getElementById(thisaid).style.color = "#900";
        fontColour = document.getElementById(thisaid).style.color;
        document.getElementById(thistdid).style.backgroundColor = "#EEC"; 
        backColour = document.getElementById(thistdid).style.backgroundColor;
        found = true;
      }
    }

    // If the marker was not already selected, then select it now
    if (!found) {
      selectStation(station_id);
    }
    //$('nav_stations').innerHTML = createStationList(line_id,branch_id);
  }
}

// -------------------------------------------------------------------------------
function promoteDistance(line_id,station1,station2,dists) {

    t  = "<table style='background-color:#DE3'>";
    t += "<tr><td style='text-align:center;font:12px arial;color:#900;'>the distance between</td></tr>";
    t += "<tr><td style='text-align:center;font:14px arial;color:#900;'>"+camelCase(stations[station1].station_name)+"</td></tr>";
    t += "<tr><td style='text-align:center;font:12px arial;color:#900;'>and</td></tr>";
    t += "<tr><td style='text-align:center;font:14px arial;color:#900;'>"+camelCase(stations[station2].station_name)+"</td></tr>";
    t += "<tr><td style='text-align:center;font:12px arial;color:#900;'>is</td></tr>";
    t += "<tr><td style='text-align:center;font:14px arial;color:#900;'><span style='font-weight:bold'>"+dists[0]+"</span> miles, <span style='font-weight:bold'>"+dists[1]+"</span> kms</td></tr>";
    t += "</table>";
    distance_info = t;
    if (stations[station1].lat > stations[station2].lat) {
      x = stations[station1].lat - ((stations[station1].lat - stations[station2].lat) / 2);
    } else {
      x = stations[station2].lat - ((stations[station2].lat - stations[station1].lat) / 2);
    }
    if (stations[station1].lng > stations[station2].lng) {
      y = stations[station1].lng - ((stations[station1].lng - stations[station2].lng) / 2);
    } else {
      y = stations[station2].lng - ((stations[station2].lng - stations[station1].lng) / 2);
    }

    point = new GLatLng(x,y);
    infoMarker = new PdMarker(point,default_marker);
    //infoMarker.setTooltip(distanceInfo);
    //infoMarker.showTooltip();
    //infoMarker.topMarkerZIndex();
    //map.openInfoWindowHtml(point, distance_info);
    //infoMarker.openInfoWindowHtml(point, distance_info);
    //infoMarker.openInfoWindowHtml(distance_info, { maxWidth: 500 });
    //infoMarker.openInfoWindow("testing", { maxWidth: 500 });
    map.addOverlay(infoMarker);
    //infoMarker.openInfoWindowHtml(distance_info, { maxWidth: 200 });
    infoMarker.openInfoWindowHtml(distance_info);
}

// -------------------------------------------------------------------------------
//function showStationDetails(line_id,station_id) {
function showStationDetails(station_id) {
  if (!selectedStation(station_id)) {
    if (current_mapview == "line") {
      map.addOverlay(stations[station_id].marker);
    } else {
      stations[station_id].marker.setImage("images/small_green_icon.png");
    }
    stations[station_id].marker.showTooltip();
    stations[station_id].marker.topMarkerZIndex();
  }
}

// -------------------------------------------------------------------------------
function selectedStation(station_id) {
  for (var i=0;i<selectedStations.length;i++) {
    if (selectedStations[i] == station_id) {
      return(true);
    }
  }
  return(false);
}

// -------------------------------------------------------------------------------
function hideStationDetails(station_id) {
  if (!selectedStation(station_id)) {
    stations[station_id].marker.restoreMarkerZIndex();
    stations[station_id].marker.hideTooltip();
    if (current_mapview == "line") {
      //map.removeOverlay(stations[station_id].marker);
      if (! stations[station_id].marker.isHidden()) {
        stations[station_id].marker.hide();
      } 
    } else {
      stations[station_id].marker.restoreImage();
    }
  }
}

// -------------------------------------------------------------------------------
//
//function showStationInfo(line_id,station_id) {
  //var point = new GLatLng(stations[station_id].lat,stations[station_id].lng);
  //var marker = new PdMarker(point);
  //var station_info = "<table style='background-color:#DE3'><tr><td style='text-align:left;font:16px arial;color:#900;'>"+camelCase(stations[station_id].station_name)+" station on the</td></tr><tr><td style='text-align:left;font:14px arial;color:#900;'>"+camelCase(lines[line_id].line_name)+" line.</td></tr></table>";
  //map.openInfoWindowHtml(point, station_info);
//}

// -------------------------------------------------------------------------------
function getAllStationsBranchId(line_id) {
  for(var i=0;i<branches.length;i++) {
    if ((branches[i].line_id == line_id) && (branches[i].name == "allstations")) {
      return(branches[i].id);
    }
  }
  return(0);
}

// -------------------------------------------------------------------------------
function lineId(line_name) {
  for(var i=1;i<lines.length+1;i++) {
    if (line_name == lines[i].line_name.toLowerCase()) {
      return(lines[i].id);
    }
  }
  return(0);
}

// -------------------------------------------------------------------------------
function createViewButtons(line_id,branch_id) {
  var tableData = "";
  tableData = "<form name='whatmap' action=''>";
  tableData += "<input type='hidden' name='theline' value='"+line_id+"'>";
  tableData += "<input type='hidden' name='thebranch' value='"+branch_id+"'>";
  tableData += "<table border='0' cellpadding='0' cellspacing='0' style='width:258px;margin-bottom:4px'><tr>";
  tableData += "<td class='linelink'>";
  tableData += "Show Markers<input type='radio' name='mapview' value='markers'";
  if (current_mapview == "markers") { tableData += " CHECKED"; }
  tableData += " onclick='changeMap(this)'>";
  tableData += "</td>";
  tableData += "<td class='linelink'>";
  tableData += "Show Line<input type='radio' name='mapview' value='line'";
  if (current_mapview == "line") { tableData += " CHECKED"; }
  tableData += " onclick='changeMap(this)'>";
  tableData += "</td>";
  tableData += "<td class='linelink'>";
  tableData += "Show Both<input type='radio' name='mapview' value='both'";
  if (current_mapview == "both") { tableData += " CHECKED"; }
  tableData += " onclick='changeMap(this)'>";
  tableData += "</td></tr></table>";
  tableData += "</form>";

  return(tableData);
}

// -------------------------------------------------------------------------------
function showMap(line_id,branch_id,showBranches,showButtons,showDistance,showStations) {

  current_branch   = branch_id;
  SHOWING_BRANCHES = showBranches;
  SHOWING_BUTTONS  = showButtons;
  SHOWING_DISTANCE = showDistance;
  SHOWING_STATIONS = showStations;

  if (SHOWING_BRANCHES) {
    $('nav_branches').innerHTML = createBranchLinks(line_id);
  }

  if (SHOWING_BUTTONS) {
    $('nav_buttons').innerHTML = createViewButtons(line_id,branch_id);
  }

  if (SHOWING_DISTANCE) {
    $('nav_distance').innerHTML = showDistanceCheck();
  } else {
    hideDistanceCheck();
  }

  if (SHOWING_STATIONS) {
    $('nav_stations').innerHTML = createStationList(line_id,branch_id);
  }

  document.getElementById("mapheader").style.backgroundColor = "#"+lines[line_id].line_colour;
  $('mapheader').innerHTML = "<p class='p14' style='color:#"+lines[line_id].name_colour+";padding-left:10px;'>The map shows <span class='p24' style='color:#"+lines[line_id].name_colour+"'>The "+camelCase(lines[line_id].line_name) + " line</span></p>";

  if (document.stationform.station.value.length < 4) {
    //zoom_level = stations[document.stationform.station.value].zoom;
    zoom_level = lines[line_id].zoom;
    //map_lat    = stations[document.stationform.station.value].lat;
    //map_lng    = stations[document.stationform.station.value].lng;
    map_lat    = map.getCenter().lat(); 
    map_lng    = map.getCenter().lng(); 
  } else {
    zoom_level = lines[line_id].zoom;
    //zoom_level = map.getZoomLevel();
    map_lat    = lines[line_id].lat;
    map_lng    = lines[line_id].lng;
  }
//alert("robin");
  //map_lat    = map.getCenter().lat(); 
  //map_lng    = map.getCenter().lng(); 
  //zoom_level = map.getZoomLevel();

  //map.setCenter(new GLatLng(parseFloat(lines[line_id].lat),parseFloat(lines[line_id].lng)),parseFloat(lines[line_id].zoom));
  //map.setCenter(new GLatLng(parseFloat(lines[line_id].lat),parseFloat(lines[line_id].lng)),parseFloat(lines[line_id].zoom));
  //map.setCenter(new GLatLng(parseFloat(map_lat),parseFloat(map_lng)),parseFloat(zoom_level));
  //map.setCenter(new GLatLng(0,0),0);
  map.setCenter(new GLatLng(parseFloat(map_lat),parseFloat(map_lng)),parseFloat(zoom_level));
  clearMap();
//$('debug').innerHTML = "zoom: "+map.getZoomLevel()+"<br>"; 

  //bounds = new GLatLngBounds();
  //bounds = new GLatLngBounds(new GLatLng(parseFloat(map_lat),parseFloat(map_lng)));
  //bounds = new GLatLngBounds(new GLatLng(map_lat,map_lng));
  //map.setCenter(bounds.getCenter());
  //map.setZoom(map.getBoundsZoomLevel(bounds));
  
  if (current_mapview == "line") {
    plotLineOnly(line_id,branch_id);
  } else if (current_mapview == "markers") {
    showPlatformMarkers(line_id,branch_id);
  } else {
    showPlatformMarkers(line_id,branch_id);
    plotLineOnly(line_id,branch_id);
  }

  //if (labels_on == 1) {
    //$('labelindicator').innerHTML = "Off";
    //showLabels();
  //}
}

// -------------------------------------------------------------------------------
function stationOnBranch(station_id,branch_id) {
  for(var i=0;i<platforms.length;i++) {
    if ((platforms[i].branch_id == branch_id) && (platforms[i].station_id == station_id)) {
      return(true);
    }
  }
  return(false);
}

// -------------------------------------------------------------------------------
function showDistanceCheck() {
  //clearSelectedStations();
  hideAllToolTips();
  var data = TurnOnDistanceCheck;
  data += "</td></tr></table>";
  return(data);
}

// -------------------------------------------------------------------------------
function processDistance(line_id,branch_id,station_id) {

  var distanceDivHeader;
  if (station_id == 0) {
    if (distanceActive) {
      distanceActive = false;
      distanceLine = false;
      distanceDivHeader = TurnOnDistanceCheck;
    } else {
      distanceActive = true;
      distanceDivHeader = TurnOffDistanceCheck;
    }
  } else {
    if (distanceActive) {
      distanceDivHeader = TurnOffDistanceCheck;
    } else {
      distanceDivHeader = TurnOnDistanceCheck;
    }
  }

  var data = distanceDivHeader;
  if (distanceActive) {
    if (! distanceStation1) {
      if (station_id > 0) {
        distanceStation1 = station_id;
        data += "<tr><td class='dist8'>1st station: <span style='font-weight:bold'>"+camelCase(fetchStationName(distanceStation1))+"</span></td></tr>";
        data += "<tr><td class='dist0'>Select 2nd station from below...</td></tr>";

        if (infoMarker) {
          map.removeOverlay(infoMarker);
          infoMarker = false;
        }
        if (distanceLine) {
          map.removeOverlay(distanceLine);
          distanceLine = false;
        }
        if (distanceMarker1) {
          map.removeOverlay(distanceMarker1);
          distanceMarker1 = false;
          if (savedDistanceStation1) {
            if (current_mapview != "line") {
              map.addOverlay(stations[savedDistanceStation1].marker);
            }
            savedDistanceStation1 = false;
          }
        }
        if (distanceMarker2) {
          map.removeOverlay(distanceMarker2);
          distanceMarker2 = false;
          if (savedDistanceStation2) {
            if (current_mapview != "line") {
              map.addOverlay(stations[savedDistanceStation2].marker);
            }
            savedDistanceStation2 = false;
          }
        }
        point  = new GLatLng(stations[distanceStation1].lat,stations[distanceStation1].lng);
        distanceMarker1 = new PdMarker(point,largeGreenMarker);
        map.removeOverlay(stations[distanceStation1].marker);
        map.addOverlay(distanceMarker1);
        distanceMarker1.setTooltip(camelCase(stations[distanceStation1].station_name));
	distanceMarker1.showTooltip();

      } else {
        data += "<tr><td class='dist4'>Select 1st station from below...</td></tr>";
      }
    } else if (! distanceStation2) {
      data += "<tr><td class='dist8'>1st station: <span style='font-weight:bold'>"+camelCase(fetchStationName(distanceStation1))+"</span></td></tr>";
      if (station_id > 0) {
        distanceStation2 = station_id;

        point  = new GLatLng(stations[distanceStation2].lat,stations[distanceStation2].lng);
        distanceMarker2 = new PdMarker(point,largeGreenMarker);
        map.removeOverlay(stations[distanceStation2].marker);
        map.addOverlay(distanceMarker2);
        distanceMarker2.setTooltip(camelCase(stations[distanceStation2].station_name));
	distanceMarker2.showTooltip();

        data += "<tr><td class='dist4'>2nd station: <span style='font-weight:bold'>"+camelCase(fetchStationName(distanceStation2))+"</span></td></tr>";
        dist = calculateDistanceBetween(distanceStation1,distanceStation2);
        dists = dist.split("\|");
        data += "<tr><td class='dist4'>The distance between them is: <span style='font-weight:bold'>"+dists[0]+"</span> miles</td></tr>";
        data += "<tr><td class='dist4' style='color:#F3F06B'>The distance between them is: <span style='font-weight:bold;color:#900'>"+dists[1]+"</span><span style='color:#900'> kms</span></td></tr>";
        data += "<tr><td class='dist4' style='color:#900;text-align:left'>Choose another station...</td></tr>";
	drawDistanceLine(line_id,distanceStation1,distanceStation2,dists);
        savedDistanceStation1 = distanceStation1;
        distanceStation1 = false;
        savedDistanceStation2 = distanceStation2;
        distanceStation2 = false;
      } else {
        if (infoMarker) {
          map.removeOverlay(infoMarker);
          infoMarker = false;
        }
        if (distanceLine) {
          map.removeOverlay(distanceLine);
          distanceLine = false;
        }
        if (distanceMarker1) {
          map.removeOverlay(distanceMarker1);
          distanceMarker1 = false;
        }
        if (distanceMarker2) {
          map.removeOverlay(distanceMarker2);
          distanceMarker2 = false;
        }
        data += "<tr><td class='dist4'>Select 2nd station from below...</td></tr>";
      }
    }
    data += "</table>";
  } else {
    data += "</td></tr></table>";
    //stations[distanceStation1].marker.setTooltipHiding(true);
    //stations[distanceStation1].marker.hideTooltip();
    //stations[distanceStation1].marker.restoreMarkerZIndex();
    //stations[distanceStation2].marker.setTooltipHiding(true);
    //stations[distanceStation2].marker.hideTooltip();
    //stations[distanceStation2].marker.restoreMarkerZIndex();
    resetDistanceData();
    showMap(document.lineform.line.value,current_branch,SHOW_BRANCHES,SHOW_BUTTONS,SHOW_DISTANCE,SHOW_STATIONS);

    if ((line_id > 0) && (branch_id > 0) && (station_id > 0)) {
      thistdid = "tdsbgc"+station_id;
      thisaid  = "asbgc"+station_id;
      document.getElementById(thistdid).style.backgroundColor = '#FF3'; 
      backColour = document.getElementById(thistdid).style.backgroundColor;
      document.getElementById(thisaid).style.color = "#F00";
      fontColour = document.getElementById(thisaid).style.color;
      toggleSelected(station_id);
    } 
  }
  $('nav_distance').innerHTML = data;
}

// -------------------------------------------------------------------------------
function drawDistanceLine(line_id,station1,station2,dists) {
  //if (current_mapview == "markers") {
    //clearMap();
  //}
  colour = "F00";
  opacity = 1;
  thickness = 10;
  drawLine(stations[station1].lat,stations[station1].lng,stations[station2].lat,stations[station2].lng,colour,thickness,opacity);
  distanceLine = plottedLine;
  promoteDistance(line_id,station1,station2,dists);
}

// -------------------------------------------------------------------------------
function fetchStationName(station_id) {
  return(stations[station_id].station_name);
}

// -------------------------------------------------------------------------------
function calculateDistanceBetween(station1_id,station2_id)
{
  var glatlng1 = new GLatLng(stations[station1_id].lat, stations[station1_id].lng);
  var glatlng2 = new GLatLng(stations[station2_id].lat, stations[station2_id].lng);
  var miles    = glatlng1.distanceFrom(glatlng2, 3959).toFixed(2);
  var kms      = (miles * 1.609344).toFixed(2);
  var ret = miles+"|"+kms;
  return(ret);
}

// -------------------------------------------------------------------------------
function resetDistanceData() {
  distanceActive   = false;
  distanceStation1 = false;
  distanceStation2 = false;
}

// -------------------------------------------------------------------------------
function clearDistanceCheck() {
  resetDistanceData();
  $('nav_distance').innerHTML = showDistanceCheck();
}

// -------------------------------------------------------------------------------
function hideDistanceCheck() {
  resetDistanceData();
  $('nav_distance').innerHTML = "";
}

// -------------------------------------------------------------------------------
function hideViewButtons() {
  $('nav_buttons').innerHTML = "";
}

// -------------------------------------------------------------------------------
function hideBranches() {
  $('nav_branches').innerHTML = "";
}

// -------------------------------------------------------------------------------
function firstStationOnBranch(branch_id) {
  j=0;
  b_ranches = [];
  for(var i=0;i<platforms.length;i++) {
    if (platforms[i].branch_id == branch_id) {
      b_ranches[j++] = platforms[i].position+"|"+platforms[i].station_id;
    }
  }
  bits=[];
  for(i=0;i<b_ranches.length;i++) {
    bits = b_ranches[i].split("\|");
    if (bits[0] == 1) {
      return(bits[1]);
    }
  }
}

// -------------------------------------------------------------------------------
function lastStationOnBranch(branch_id) {
  j=0;
  b_ranches = [];
  for(var i=0;i<platforms.length;i++) {
    if (platforms[i].branch_id == branch_id) {
      b_ranches[j++] = platforms[i].position+"|"+platforms[i].station_id;
    }
  }
  bits=[];
  for(i=0;i<b_ranches.length;i++) {
    bits = b_ranches[i].split("\|");
    if (bits[0] == b_ranches.length) {
      return(bits[1]);
    }
  }
}

// -------------------------------------------------------------------------------

