
function SMap(id, type)
{
  this.pts = [];
  this.type = type;
  if(this.type=="live")
  {
    this.map = new LMap(id);
  }
  else
  {
    this.map = new GMap(document.getElementById(id));
  }
  this.photos = [];
  this.pois = [];
  this.markers = [];
  this.polyline;
  
  var latitude = document.getElementById("__STARTLATITUDE");
  var longitude = document.getElementById("__STARTLONGITUDE");
  
  if (latitude != null & longitude != null) {
    this.map.setMapCenter(latitude.value, longitude.value, 12);
  }
}

SMap.prototype.redraw = function() {
  var pts = this.pts;
  this.clear();
  this.pts = pts;
  this.draw(typeof(prevStartTime) === "undefined" ? 0 : prevStartTime, prevEndTime);
}
var prevStartTime, prevEndTime;

SMap.prototype.draw = function(startTime, endTime) {
  var color = trackColor;
  prevStartTime = startTime;
  prevEndTime = endTime;
  if(this.pts.length>0)
  {
    var pos1 = -1, pos2 = -1;
    for(i=0;i<this.pts.length;i++)
    {
      if(this.pts[i].time>=startTime && pos1<0)
      {
        pos1 = i;
        if(pos1>0 && this.pts[i].time>startTime) pos1--; // if overshot then step back
      }
      if(this.pts[i].time<=endTime)
      {
        pos2 = i;
      }
      else
      {
        break;
      }
    }
    if(pos2<this.pts.length-1) pos2++;
    var newpts = this.pts.slice(pos1, pos2 + 1);
    this.map.resetCentre(newpts);
    this.map.clearOverlays();
    if(newpts.length==1)
    {
      newpts.add(newpts[0]); // if only one pt then add it in twice
    }
    if(newpts.length>1)
    {
      var thisColor;
      if(1==0)
      {
        this.map.drawPolyline(0, newpts, "#BB0000", 3);
      }
      else
      {
        // find out max speed
        var maxSpeed = 0;
        for(i=0;i<newpts.length;i++)
        {
          if(newpts[i].speed > maxSpeed) maxSpeed = newpts[i].speed;
        }
        var colors;
        if(this.type=="live")
        {
          colors = [new VEColor(0,0,0,0.9), new VEColor(31,144,255,0.9), new VEColor(0,240,0,0.9), new VEColor(240,0,0,0.9)];
        }
        else
        {
          colors = ["#000000", "#1E90FF", "#00F000", "#F00000"];
        }
        var sepSize = Math.ceil(maxSpeed / 5);
        var trackSpeed = [2*sepSize, 3*sepSize, 4*sepSize, 5*sepSize];
        var currentDivision = 0;
        var currentDivisionStartPos = 0;
        for(i=0;i<newpts.length;i++)
        {
          var speed = newpts[i].speed;
          var division = 0;
          if(speed >= trackSpeed[0]) division = 1;
          if(speed >= trackSpeed[1]) division = 2;
          if(speed >= trackSpeed[2]) division = 3;
          
          if(division != currentDivision)
          {
            thisColor = (typeof(color) === "undefined" || color === null) ? colors[currentDivision] : color;
            var ln = newpts.slice(currentDivisionStartPos, i + 1);
            this.map.drawPolyline(i+1, ln, thisColor, 3);
            currentDivision = division;
            currentDivisionStartPos = i;
          }
        }
        var ln = newpts.slice(currentDivisionStartPos, newpts.length);
        thisColor = (typeof(color) === "undefined" || color === null) ? colors[currentDivision] : color;
        this.map.drawPolyline(0, ln, thisColor, 3);
      }
    }
  }
  
    if(this.photos.length>0)
  {
    for(i=0;i<this.photos.length;i++)
    {
      this.map.drawPhoto(this.photos[i]);
    }
  }
      
  if(this.pois.length>0)
  {
    for(var i=0;i<this.pois.length;i++)
    {
      var poi = this.pois[i];
      this.map.drawPoi(poi);
    }
  }
}

SMap.prototype.loadLap = function(n, x, y, t, s)
{
  if(n==0)
  {
    this.pts = [];
  }

  for (var i = 0; i < x.length; i++) 
  {
    var newPt = this.map.createPoint(y[i], x[i], t[i], s[i]);
    this.pts.push(newPt);
  }

  if(this.pts.length>0)
  {
    this.startTime = this.pts[0].time;
    this.endTime = this.pts[this.pts.length - 1].time;
  }

  // limit amount displayed
  this.minDisplayPosition = this.startTime;
  if(this.pts.length>100)
  {
    this.maxDisplayPosition = this.pts[100].time;
  }
  else
  {
    this.maxDisplayPosition = this.endTime;
  }
}

SMap.prototype.setStart = function(x, y)
{
  this.map.setStart(x,y);
}

SMap.prototype.setEnd = function(x, y)
{
  this.map.setEnd(x,y);
}

SMap.prototype.showDoer = function(x, y)
{
  this.map.showDoer(x,y);
}
SMap.prototype.checkResize = function()
{
  this.map.checkResize();
}
SMap.prototype.resize = function(x, y)
{
  this.map.resize(x, y);
}
SMap.prototype.centreDoer = function()
{
  this.map.centreDoer();
}
SMap.prototype.resetCentre = function()
{
  this.map.resetCentre();
}
SMap.prototype.clear = function()
{
  this.map.clearOverlays(true);
  this.pts = [];
}
SMap.prototype.centrePois = function()
{
  if(this.pois.length>0)
  {
    this.map.centrePois(this.pois);
  }
}







function GMap(mapDiv)
{
  this.bounds = new GLatLngBounds();
  this.map = new GMap2(mapDiv);
  this.map.smap = this;
  this.distanceUnits = "km";

  this.icon = new GIcon();
  this.icon.image = "/ui/sportsdo/doer.png";
  this.icon.shadow = "/ui/sportsdo/doer_shadow.png";
  this.icon.iconSize = new GSize(24, 33);
  this.icon.shadowSize = new GSize(46, 33);
  this.icon.iconAnchor = new GPoint(12, 16);
  this.icon.infoWindowAnchor = new GPoint(15, 12);

  this.iconPhoto = new GIcon();
  this.iconPhoto.image = "/ui/sportsdo/photo.png";
  this.iconPhoto.iconSize = new GSize(26, 26);
  this.iconPhoto.iconAnchor = new GPoint(13, 13);
  this.iconPhoto.infoWindowAnchor = new GPoint(15, 12);

  this.startIcon = new GIcon();
  this.startIcon.image = "/ui/sportsdo/green_dot.png";
  this.startIcon.iconSize = new GSize(23, 23);
  this.startIcon.iconAnchor = new GPoint(12, 16);
  this.endIcon = new GIcon();
  this.endIcon.image = "/ui/sportsdo/red_dot.png";
  this.endIcon.iconSize = new GSize(23, 23);
  this.endIcon.iconAnchor = new GPoint(12, 16);
  
  this.startMarker = null;
  this.endMarker = null;
  this.doer = null;

  var instance = this; 
  if (window.attachEvent) 
  { 
    window.attachEvent("onunload", function(evnt) { instance.unload(evnt) });
  } 
  else
  {
    window.addEventListener("unload", function(evnt) { instance.unload(evnt) } , false);
  }

  this.map.addControl(new GSmallMapControl());
  this.map.addControl(new GMapTypeControl());
  this.map.addControl(new TextualZoomControl(this));
}

GMap.prototype.unload = function()
{
  GUnload();
}

GMap.prototype.drawPhoto = function(p)
{
  var instance = this;
  var point = new GLatLng(p.latitude, p.longitude);
  var marker = new GMarker(point, this.iconPhoto);
  marker.sphoto = p;
  GEvent.addListener(marker, "click", function() { instance.openPhotoWindow(marker, p.id, point); });
  this.map.addOverlay(marker);
}

GMap.prototype.drawPoi = function(p)
{
}

GMap.prototype.setStart = function(x, y)
{
  var point = new GLatLng(y, x);
  if(this.startMarker == null)
  {
      this.startMarker = new GMarker(point, this.startIcon);
      this.map.addOverlay(this.startMarker);
  }
  else
  {
    this.startMarker.setPoint(point);
  }
}

GMap.prototype.setEnd = function(x, y)
{
  var point = new GLatLng(y, x);
  if(this.endMarker == null)
  {
      this.endMarker = new GMarker(point, this.endIcon);
      this.map.addOverlay(this.endMarker);
  }
  else
  {
    this.endMarker.setPoint(point);
  }
}

GMap.prototype.openPhotoWindow = function(marker, id)
{
    var photo = marker.sphoto;
    var dateCell = "";
    var width = 120;
    if (photo != null && typeof(photo.date) != "undefined") {
        var d = new Date();
        d.setTime(photo.date);
        dateCell = "<tr><td style=\"font-family: verdana; font-size: 8pt\">Taken: " + d.format("dd MMM yyyy - hh:mm:ss") + "</td></tr>";
        width = 200;
    }
    marker.openInfoWindowHtml("<div style='width:" + width + "px; height:140px'><table><tr><td><a target=\"_blank\" href=\"/photos/photo.aspx?id=" + id + "\"><img title='View photo' src='/photos/photo.ashx?thumbnail=1&id=" + id + "'  /></a></td></tr>" + dateCell + "<tr><td><a target=\"_blank\" href=\"/photos/photo.aspx?id=" + id + "\">View Image</a></td></tr></table></div>");
}


GMap.prototype.createPoint = function(y, x, t, s)
{
  return new GglPoint(y, x, t, s, 0);
}

GMap.prototype.resetCentre = function(pts)
{
  if(pts != null)
  {
    this.bounds = new GLatLngBounds();
    for (var i = 0; i < pts.length; i++)
    {
      this.bounds.extend(pts[i]);
    }
  }
  
  // set the map zoom based on the bounds 
  // first work out the centre of the bounds
  var clat = (this.bounds.getNorthEast().lat() + this.bounds.getSouthWest().lat()) /2;
  var clng = (this.bounds.getNorthEast().lng() + this.bounds.getSouthWest().lng()) /2;
  // then centre and zoom
  this.map.setCenter(new GLatLng(clat,clng), this.map.getBoundsZoomLevel(this.bounds));
}

GMap.prototype.clearOverlays = function(clearAll)
{
  this.map.clearOverlays();
  
  if(clearAll == null)
  {
      if(this.startMarker != null)
      {
        this.map.addOverlay(this.startMarker);
      }
      if(this.endMarker != null)
      {
        this.map.addOverlay(this.endMarker);
      }
      if(this.doer != null)
      {
        this.map.addOverlay(this.doer);
      }
  }
}

GMap.prototype.drawPolyline = function(id, pts, colour, width)
{
  this.map.addOverlay(new GPolyline(pts, colour, width, 0.9));
}

GMap.prototype.showDoer = function(x, y)
{
  if(this.doer == null)
  {
    this.doer = new GMarker(new GLatLng(y, x), this.icon);
    this.map.addOverlay(this.doer);
  }
  else
  {
    this.doer.setPoint(new GLatLng(y, x));
  }
}

GMap.prototype.checkResize = function()
{
  this.map.checkResize();
}

GMap.prototype.resize = function(x, y)
{
  this.map.checkResize();
}

GMap.prototype.centreDoer = function()
{
  if(this.doer != null)
  {
    var pt = this.doer.getPoint();
    this.map.setCenter(pt);
  }
}

/*
GMap.prototype.loadData = function(x, y, t)
{
  this.pts = [];
  this.index = [];
  
  for (var i = 0; i < x.length; i++) 
  {
    var newPt = new GgPoint(y[i], x[i], t[i], 0, 0);
    this.pts.push(newPt);
    this.index[t[i]] = i;
  }

  this.startTime = 0;
  this.endTime = 0;
  if(this.pts.length>0)
  {
    this.startTime = this.pts[0].time;
    this.endTime = this.pts[this.pts.length - 1].time;
  }

  // limit amount displayed
  this.minDisplayPosition = this.startTime;
  if(this.pts.length>100)
  {
    this.maxDisplayPosition = this.pts[100].time;
  }
  else
  {
    this.maxDisplayPosition = this.endTime;
  }
}
*/






function LMap(id)
{
  this.map = new VEMap(id);
  this.map.LoadMap(new VELatLong(0, 0), 3);
  this.distanceUnits = "km";
  this.pts = [];
  this.doer = null;
  this.restaurant = null;
  
  this.iconPhoto = "/ui/sportsdo/photo.png";
}
LMap.prototype.clearOverlays = function()
{
  this.map.DeleteAllPolylines();
}
LMap.prototype.drawPolyline = function(id, pts, colour, width)
{
//alert("" + id + ":" + pts.length + ":(" + colour.R + "," + colour.G + "," + colour.B + "):" + width);
  var poly = new VEPolyline(id, pts); 
  poly.SetWidth(width);            
  poly.SetColor(colour);            
  this.map.AddPolyline(poly);
}
LMap.prototype.checkResize = function()
{
//  this.map.Resize();
}
LMap.prototype.resize = function(x, y)
{
  this.map.Resize(x, y);
}
LMap.prototype.resetCentre = function(pts)
{
  this.map.SetMapView(pts);
}
LMap.prototype.showDoer = function(x, y)
{
 if(this.doer == null)
  {
    this.doer = new VEPushpin("doer", new VELatLong(y, x), "/ui/sportsdo/doer.gif", "", "");
    this.map.AddPushpin(this.doer);
  }
  else
  {
    this.map.DeletePushpin("doer");
    this.doer = new VEPushpin("doer", new VELatLong(y, x), "/ui/sportsdo/doer.gif", "", "");
    this.map.AddPushpin(this.doer);
  }
}
LMap.prototype.addRestaurantIcon = function(id, name, y, x)
{
  var icon = new VEPushpin(id, new VELatLong(y, x), "/ui/hut.png", name, "");
  this.map.AddPushpin(icon);
}
LMap.prototype.centreDoer = function()
{
}
LMap.prototype.createPoint = function(y, x, t, s)
{
  return new LivePoint(y, x, t, s, 0);
}
LMap.prototype.centrePois = function(pois)
{
    var poiPts = []
    for(var j=0;j<pois.length;j++)
    {
      var poi = pois[j];
      if(poi.sh==1)
      {
        for(i=0;i<poi.xy.list.source.length;i++)
        {
          var poiPt = poi.xy.list.source[i];
          var ll = new VELatLong(poiPt.la, poiPt.lo);
          poiPts.push(ll);
        }
      }
    }
    if(poiPts.length>0)
    {
      this.map.SetMapView(poiPts);
    }
}
LMap.prototype.drawPoi = function(p)
{
  if(p.sh==0)
  {
    this.addRestaurantIcon(p.uid, p.name, p.xy.la, p.xy.lo);
  }
  else if(p.sh==1)
  {
    var poiPts = []
    for(i=0;i<p.xy.list.source.length;i++)
    {
      var poiPt = p.xy.list.source[i];
      var ll = new VELatLong(poiPt.la, poiPt.lo);
      poiPts.push(ll);
    }
    var poly = new VEPolyline(p.uid, poiPts);
    poly.SetWidth(5);
    if(p.ty=="lift")
    {
      poly.SetColor(new VEColor(128,128,128,0.9));
    }
    else if(p.ty="ski trail")
    {
      if(p.su=="blue")
      {
        poly.SetColor(new VEColor(64,64,255,0.9));
      }
      else if(p.su=="red")
      {
        poly.SetColor(new VEColor(255,64,64,0.9));
      }
      else if(p.su.indexOf("black")>=0)
      {
        poly.SetColor(new VEColor(248,102,63,0.9));
      }
      else
      {
        poly.SetColor(new VEColor(64,255,64,0.9));
      }
    }
    else
    {
      poly.SetColor(new VEColor(255,64,64,0.9));
    }
    this.map.AddPolyline(poly);
  }
}
LMap.prototype.drawPhoto = function(p)
{
  var instance = this;
  var point = new VELatLong(p.latitude, p.longitude);
  
  var dateCell = "";
  var width = 120;
  if (p != null && typeof(p.date) != "undefined") {
    var d = new Date();
    d.setTime(p.date);
    dateCell = "<tr><td style=\"font-family: verdana; font-size: 8pt\">Taken: " + d.format("dd MMM yyyy - hh:mm:ss") + "</td></tr>";
    width = 200;
  }
  var bubble = "<div style='width:" + width + "px; height:140px'><table><tr><td><a target=\"_blank\" href=\"/photos/photo.aspx?id=" + p.id + "\"><img title='View the image' src='/photos/photo.ashx?thumbnail=1&id=" + p.id + "'  /></a></td></tr>" + dateCell + "<tr><td><a target=\"_blank\" href=\"/photos/photo.aspx?id=" + p.id + "\">View Image</a></td></tr></table></div>";
  
  var shape = new VEShape(VEShapeType.Pushpin, point);
  shape.SetCustomIcon(this.iconPhoto);
  shape.SetDescription(bubble);
  
  this.map.AddShape(shape);
}
LMap.prototype.setMapCenter = function(y, x, zoom) {
  this.map.SetCenterAndZoom(new VELatLong(y, x), zoom);
}


function TextualZoomControl(map)
{
  this.map = map;
}

TextualZoomControl.prototype = new GControl();

TextualZoomControl.prototype.initialize = function(map)
{
  var container = document.createElement("div");

  var img = document.createElement("img");
  img.src = "/ui/centre.gif";
  img.style.cursor = "pointer";
  var instance = this;
  GEvent.addDomListener(img, "click", function() { instance.map.resetCentre(); });
  container.appendChild(img);

  img = document.createElement("img");
  img.src = "/ui/centre_doer.gif";
  img.style.cursor = "pointer";
  GEvent.addDomListener(img, "click", function() { instance.map.centreDoer(); });
  container.appendChild(img);

  map.getContainer().appendChild(container);
  return container;
}

TextualZoomControl.prototype.getDefaultPosition = function()
{
  return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5, 30));
}


function GglPoint(lat, lng, time)
{
  GLatLng.call(this, lat, lng);
  this.time = time;
  this.speed = 0;
  this.distance = 0;
}

function GglPoint(lat, lng, time, speed, distance)
{
  GLatLng.call(this, lat, lng);
  this.time = time;
  this.speed = speed;
  this.distance = distance;
}
GglPoint.prototype = new GLatLng();

function LivePoint(lat, lng, time)
{
  VELatLong.call(this, lat, lng);
  this.time = time;
  this.speed = 0;
  this.distance = 0;
}

function LivePoint(lat, lng, time, speed, distance)
{
  VELatLong.call(this, lat, lng);
  this.time = time;
  this.speed = speed;
  this.distance = distance;
}
LivePoint.prototype = new VELatLong();

/* Functions added by Lukasz */

SMap.prototype.drawFromMarkers = function()
{
    // drawing polyline from markers here
    var markers = map.getMarkers();
    var newPts = [];    
    var i = 0;
    for (i = 0; i < markers.length; i++)
    {
        var newPt = this.map.createPoint(markers[i].getPoint().y, markers[i].getPoint().x, i, 1);
        newPts.push(newPt);
    }    
    map.drawPolyline(0, newPts, "#BB0000", 5)
        
}


SMap.prototype.setListeners = function()
{
    this.map.setListeners();
}

GMap.prototype.setListeners = function()
{       
    GEvent.addListener(this.map, "click", function(marker, point) 
    {
        if (marker) 
        {
            map.deleteMarker(marker);
        } 
        else 
        {              
            map.setNewMarker(point);
        }
    });
}


SMap.prototype.drawPolyline = function(id, points, color, weight)
{
    this.map.drawPolyline(id, points, color, weight);
}

//GMap.prototype.drawPolyline = function(id, points, color, weight)
//{       
//    this.map.removeOverlay(this.map.polyline);  
//    this.map.polyline = new GPolyline(points, color, weight);
//    this.map.addOverlay(this.map.polyline);
//}




SMap.prototype.setNewMarker = function(point)
{
    this.map.setNewMarker(point);
}

GMap.prototype.setNewMarker = function(point)
{   
    if (this.map.markers == null)
    {
        this.map.markers = [];
    }
    var newMarker = new GMarker(point, {draggable: true});    
    GEvent.addListener(newMarker, "dragend", function() 
    {
         map.drawFromMarkers(); 
    });        
    
    this.map.markers.push(newMarker);    
    this.map.addOverlay(newMarker);    
    map.drawFromMarkers();
}


SMap.prototype.deleteMarker = function(marker)
{
    this.map.deleteMarker(marker);
}


GMap.prototype.deleteMarker = function(marker)
{   
    var index = 0;
    while (index < this.map.markers.length)
    {
        if (this.map.markers[index].getPoint() == marker.getPoint())
        {
            break;
        }            
        index++
    }
    alert(index);
    alert(this.map.markers.length);
    this.map.markers.splice(index, 1);
    this.map.removeOverlay(marker);    
    alert(this.map.markers.length);
}


SMap.prototype.getMarkers = function()
{
    return this.map.getMarkers();
}

GMap.prototype.getMarkers  = function()
{   
    return this.map.markers;
}



SMap.prototype.getMarkerLocation = function(marker)
{
    return this.map.getMarkerLocation(marker);
}

GMap.prototype.getMarkerLocation = function(marker)
{       
    return marker.getPoint();
}



SMap.prototype.getMapCenter = function()
{
    return this.map.getMapCenter();
}

GMap.prototype.getMapCenter = function()
{
    return this.map.getCenter();
}



SMap.prototype.setMapCenter = function(y, x, zoom)
{   
    this.map.setMapCenter(y, x, zoom);
}

GMap.prototype.setMapCenter = function(y, x, zoom)
{
    this.map.setCenter(new GLatLng(y, x), zoom);
}



/* End of functions by Lukasz */
