
// Globals
var map;
var mapLayer;
var aerialLayer;
var routeLayer;
var markerLayer;
var mapCenterX = '';
var mapCenterY = '';


function drawMaps() {
     $(".olMap").each(function() {
         str = this.innerHTML.replace(/(<!--|-->)/g, '');
         eval(str);
     });
}

OpenLayers.Map.prototype.drawPin = function(kkjX, kkjY) {
      var size = new OpenLayers.Size(34,34);
      var offset = new OpenLayers.Pixel(-1,-34);
      var icon = new OpenLayers.Icon('./images/mapIcons/pointer.gif',size,offset);
      this.getLayersByName('markers')[0].clearMarkers();
      this.getLayersByName('markers')[0].addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(kkjX,kkjY),icon));
}

OpenLayers.Map.prototype.clearMarkers = function() {
      this.getLayersByName('markers')[0].clearMarkers();
}

function drawMap(divId,zoom,route) {
   var options = {
      maxExtent: new OpenLayers.Bounds(0,0,3000000,7000000),
      controls: [
         new OpenLayers.Control.Navigation({'zoomWheelEnabled': false}),
         new OpenLayers.Control.ScaleLine(),
         new OpenLayers.Control.PanZoomBar()/*,
         new OpenLayers.Control.KeyboardDefaults()*/
      ],
      resolutions: [0.5,
      1.125,
      2.5,
      3.125,
      4,
      6.25,
      20,
      66.66,
      133],
      restrictedExtent: new OpenLayers.Bounds(2515998,6650001,2570198,6705001),
      units: 'm',
      projection: "EPSG:2392"
      //center: new OpenLayers.LonLat(kkjX, kkjY)
   };
   map = new OpenLayers.Map(divId, options);
   // Add layers
   mapLayer = new OpenLayers.Layer.TMS("YTV Map",
      MAP_URL, //"http://ntile1.navici.com/t/reittiopas/",
      {
         layers: 'basic',
         buffer : 0,
         transitionEffect: 'resize',
         getURL: getMapUrl
      });
   map.addLayer(mapLayer);
   aerialLayer = new OpenLayers.Layer.TMS("YTV Aerial",
      AERIAL_URL, //"http://ntile1.navici.com/t/reittiopas/",
      {
         layers: 'basic',
         buffer : 0,
         transitionEffect: 'resize',
         getURL: getAerialUrl
      });
   map.addLayer(aerialLayer);
   map.zoomTo(zoom);
   if (route) {
      routeLayer = new OpenLayers.Layer.Vector("route", { rendererOptions: {zIndexing: true}});
      map.addLayer(routeLayer);
      autoZoom = (zoom==-1 ? 1 : 0);
      drawRoute(route, autoZoom);
   }
   markerLayer = new OpenLayers.Layer.Markers("markers", { rendererOptions: {zIndexing: true}});
   map.addLayer(markerLayer);   
   // Set center & draw buttons
   if (mapCenterX != '' && mapCenterY != '') {
      map.setCenter(new OpenLayers.LonLat(mapCenterX, mapCenterY), zoom);
   }
}

function getCoordsAsGeometry(coordsStr, geometryType) {
   // coords -> points
   var pointsArr = [];
   var coords = coordsStr.split(' ');
   for(var j=0;j<coords.length; j++) {
      var arr = coords[j].split(",");
      var p = new OpenLayers.Geometry.Point(arr[0], arr[1]);
      pointsArr.push(p);
   }
   // return type
   if (geometryType == 'LineString') {
      var ls = new OpenLayers.Geometry.LineString(pointsArr);
      return ls;
   }
   else if (geometryType == 'MultiPoint') {
      var mp = new OpenLayers.Geometry.MultiPoint(pointsArr);
      return mp;
   }
   else {
      alert('unknown geometryType');
      return '';
   }
}


function drawRoute(route, autoZoom) {
   
   // build each leg
   legs = route.legs;
   
   for (var i=0; i<legs.length; i++) {
      // define styles
      style_walk = {
         strokeColor: "#0063ff",
         strokeDashstyle: 'dash',
         strokeWidth: 5,
         graphicZIndex: 0
      };
      style_bus = {
         strokeColor: "#193695",
         strokeOpacity: 1,
         strokeWidth: 5,
         graphicWidth: 8,
         graphicHeight: 8,
         graphicXOffset: -4,
         graphicYOffset: -4,
         externalGraphic : './images/mapIcons/circle_bus.png'
      };
      style_metro = {
         strokeColor: "#ef3f0c",
         strokeOpacity: 1,
         strokeWidth: 5,
         graphicWidth: 8,
         graphicHeight: 8,
         graphicXOffset: -4,
         graphicYOffset: -4,
         externalGraphic : './images/mapIcons/circle_metro.png'
      }
      style_tram = {
         strokeColor: "#00af2e",
         strokeOpacity: 1,
         strokeWidth: 5,
         graphicWidth: 8,
         graphicHeight: 8,
         graphicXOffset: -4,
         graphicYOffset: -4,
         externalGraphic : './images/mapIcons/circle_tram.png'
      };
      style_ferry = {
         strokeColor: "#5ac5d8",
         strokeOpacity: 1,
         strokeWidth: 5
      };
      style_train = {
         strokeColor: "#e9001a",
         strokeOpacity: 1,
         strokeWidth: 5,
         graphicWidth: 8,
         graphicHeight: 8,
         graphicXOffset: -4,
         graphicYOffset: -4,
         externalGraphic : './images/mapIcons/circle_train.png'
      };
      style_bullet_block = {
         graphicWidth: 10,
         graphicHeight: 10,
         graphicXOffset: -5,
         graphicYOffset: -5,
         graphicZIndex: 1000,
         externalGraphic : './images/mapIcons/endpoint.png'
      };
      style_bullet_circle = {
         graphicWidth: 10,
         graphicHeight: 10,
         graphicXOffset: -5,
         graphicYOffset: -5,
         graphicZIndex: 1000,
         externalGraphic : './images/mapIcons/changepoint.png'
      };
      
      if (legs[i].mode == 'walk') style = style_walk;
      else if (legs[i].mode == 'bus') style = style_bus;
      else if (legs[i].mode == 'metro') style = style_metro;
      else if (legs[i].mode == 'tram') style = style_tram;
      else if (legs[i].mode == 'ferry') style = style_ferry;
      else if (legs[i].mode == 'train') style = style_train;
      
      // draw route
      var geom = getCoordsAsGeometry(legs[i].routeCoords, 'LineString');
      var feat = new OpenLayers.Feature.Vector(geom, null, style);
      routeLayer.addFeatures([feat]);
      
      // draw stops enroute
      if (legs[i].stopCoords) {
         geom = getCoordsAsGeometry(legs[i].stopCoords, 'MultiPoint');
         feat = new OpenLayers.Feature.Vector(geom, null, style);
         routeLayer.addFeatures([feat]);
      }
      
      // draw change stop bullets
      if (legs[i].mode != 'walk') {
         var coords = legs[i].routeCoords.split(' ');
         coordsStr = '';
         if (i>0) coordsStr = coords[0]+' ';
         if (i<coords.length-1) coordsStr += coords[coords.length-1]+' ';
         coordsStr = coordsStr.substr(0, coordsStr.length-1);
         geom = getCoordsAsGeometry(coordsStr, 'MultiPoint');
         feat = new OpenLayers.Feature.Vector(geom, null, style_bullet_circle);
         routeLayer.addFeatures([feat]);
      }
      
      // draw end point bullets
      var viaCoordTxt = '';
      if (route.viaCoord) {
          viaCoordTxt = ' '+route.viaCoord;
      }
      geom = getCoordsAsGeometry(route.startCoord+' '+route.endCoord+viaCoordTxt, 'MultiPoint');
      feat = new OpenLayers.Feature.Vector(geom, null, style_bullet_block);
      routeLayer.addFeatures([feat]);
      
      // center and zoom map to routelayer
      routeExtent = routeLayer.getDataExtent();
      map.setCenter(routeExtent.getCenterLonLat());
      if (autoZoom) map.zoomToExtent(routeExtent);
   }

}

function getMapUrl(bounds) {
   var res = this.map.getResolution();
   var x = Math.round(bounds.left / (res * this.tileSize.w));
   var y = Math.round(bounds.bottom / (res * this.tileSize.h));
   var url = this.url+2392+"x"+res+"x"+x+"x"+y+".png?cid="+NAVICI_CID;
   return url;
}

function getAerialUrl(bounds) {
   var res = this.map.getResolution();
   var x = Math.round(bounds.left / (res * this.tileSize.w));
   var y = Math.round(bounds.bottom / (res * this.tileSize.h));
   var url = this.url+2392+"x"+res+"x"+x+"x"+y+".jpeg?cid="+NAVICI_CID;
   return url;
}

function log(text) {
   if (window.console) {
      window.console.log(text);
   }
}

function printArr(object) {
   var str;
   for(prop in object) {
      str += prop + ":"+ object[prop]+"\n";
   }
}


