Edit = new function() {
   this.map = null;
   this.mapDiv = null;
   this.mapType = null;
   this.ajax = null;
this.activityId = "";

   this.bboxes = [];
   this.tripMarkers = [];

   this.tempWaypoints = [];
   this.numTempWaypoints = 0;
   this.tempTracks = [];
   this.numTempTracks = 0;
   
   function keyCode(e){
      var keynum;

      if(window.event) // IE
         keynum = e.keyCode;
      else if(e.which) // Netscape/Firefox/Opera
         keynum = e.which;
      return keynum;
   }


   this.load = function() {
      var self = Edit;

      self.ajax = new Ajax();

      self.makeIcons();

      if (GBrowserIsCompatible()) {

         self.map = new GMap2(self.mapDiv);
         self.map.addControl(new GLargeMapControl());
         self.map.setCenter(self.centerPoint, self.centerZoom);
        // alert(self.map.getCenter());

         self.map.addControl(new GV_MapTypeControl());
         self.changeMapType("Terrain");
         self.map.enableDoubleClickZoom();
        // self.map.enableScrollWheelZoom();
         self.map.enableContinuousZoom();
      }

      GEvent.addListener(self.map,"moveend",function() {
         self.getAllTrips();
      });

      self.getAllTrips();
     // self.addCreateMapButton();

   }

   
   this.addCreateMapButton = function() {
      var self = Edit;
      
      var div = document.createElement('div');
      div.style.width = "100px";
      div.style.height = "20px";
      div.style.top = "5px";
      div.style.left = "80px";
      div.style.position = "absolute";
      div.style.zindex = 100;
      div.style.backgroundColor = "#FFFFFF";
      div.style.border = "1px solid #000000";
      div.align = "center";
      div.verticalAlign = "middle";
      div.innerHTML = '<a href="javascript:Edit.createArticle();">add new place</a>';
      div.onclick = function() {
         self.createArticle();
      };   
      self.mapDiv.appendChild(div);

   }

   this.changeMapType = function(mapName) {
      var self = Edit;

      var mapType = getMapFromName(mapName);
      var mapId = getMapTypeId(mapName);

      var map_selector = document.getElementById('map_selector');
      map_selector.selectedIndex = mapId;
      Edit.map.setMapType(mapType);
   }

   this.centerOnLoc = function(locPoint) {
      var self = Edit;
      if(locPoint) {
         self.map.setCenter(locPoint,13);
      }   

   }
   
   this.updateActivities = function() {
      var self = Edit;
      self.activityId = "";
      for(var i=0; i<self.numActivities; i++) {

         if(document.getElementById("activityBox"+i) && document.getElementById("activityBox"+i).checked) {
           self.activityId += document.getElementById("activityBox"+i).value + ",";
         }
      }
      self.getAllTrips();

   }
   
   this.changeChecks = function() {
      var self = Edit;
      for(var i=0; i<self.numActivities; i++) {

         if(document.getElementById("activityBox"+i)) {
            document.getElementById("activityBox"+i).checked = document.getElementById('checkAll').checked;
         }
      }

   }
   
   this.whereKeyPress = function(e) {
      var self = Edit;
      if(keyCode(e) == 13){
         self.getGPSLocation(document.getElementById("address").value);
      }
   }
   
   this.getGPSLocation = function(address) {
      var self = Edit;
      
      var geocoder = new GClientGeocoder();
      geocoder.getLatLng(address, self.centerOnLoc);

   }
   
   this.makeIcons = function() {
      var self = Edit;
      
      self.tripIcon = new GIcon();
      self.tripIcon.image = "/images/spot/adv_map_icon.png";
      self.tripIcon.iconSize = new GSize(32, 32);
      self.tripIcon.shadowSize = new GSize(32, 32);
      self.tripIcon.iconAnchor = new GPoint(16, 16);
      self.tripIcon.infoWindowAnchor = new GPoint(16, 16);

      self.activeIcon = new GIcon();
      self.activeIcon.image = "/images/spot/marker_red.png";
      self.activeIcon.iconSize = new GSize(15, 15);
      self.activeIcon.shadowSize = new GSize(15, 15);
      self.activeIcon.iconAnchor = new GPoint(8, 8);
      self.activeIcon.infoWindowAnchor = new GPoint(8, 8);
      
      self.trackIcon = new GIcon();
      self.trackIcon.image = "/images/spot/track_marker.png";
      self.trackIcon.iconSize = new GSize(10, 10);
      self.trackIcon.shadowSize = new GSize(10, 10);
      self.trackIcon.iconAnchor = new GPoint(5, 5);
      self.trackIcon.infoWindowAnchor = new GPoint(5, 5);
      
      self.articleIcon = new GIcon();
      self.articleIcon.image = "/images/spot/trip_marker.png";
      self.articleIcon.iconSize = new GSize(9, 9);
      self.articleIcon.shadowSize = new GSize(9, 9);
      self.articleIcon.iconAnchor = new GPoint(9, 0);
      self.articleIcon.infoWindowAnchor = new GPoint(9, 9);
      
      self.waypointIcon = new GIcon();
      self.waypointIcon.image = "/images/spot/red_marker_small.png";
      self.waypointIcon.iconSize = new GSize(11, 19);
      self.waypointIcon.shadowSize = new GSize(11, 19);
      self.waypointIcon.iconAnchor = new GPoint(6, 10);
      self.waypointIcon.infoWindowAnchor = new GPoint(6, 10);


   }

   this.createPin = function(type,id) {
      var self = Edit;
      var marker = null;

      if(type == "waypoint") {
         var waypoint = self.waypoints[id];
         var name = waypoint['name'];
         var point = new GLatLng(waypoint['lat'],waypoint['lon']);
         marker = new GMarker(point, {title:name,draggable:true,icon:self.waypointIcon});

         GEvent.addListener(marker, "click", function() {
            waypoint = Edit.waypoints[id];

            name = waypoint['name'];
                                                         
            lat = Math.round(waypoint['lat']*1000)/1000;
            lon = Math.round(waypoint['lon']*1000)/1000;
            ele = waypoint['ele'];
            desc = waypoint['desc'];

            html = "<div style=''><b>" + name + "</b> [<a href='javascript:Edit.editWaypoint("+id+");'>edit</a>]<br>("+lat+","+lon+")</div>";

           marker.openInfoWindow(html);
         });

         GEvent.addListener(marker, "dragstart", function() {
            self.map.closeInfoWindow();
         });

         GEvent.addListener(marker, "dragend", function() {
            var point = marker.getPoint();

            self.waypoints[id]['lat'] = point.lat();
            self.waypoints[id]['lon'] = point.lng();

         });
         
         /*
         GEvent.addListener(marker, "mouseover", function() {
            self.highlightWaypoint("waypoint"+id);
         });
         GEvent.addListener(marker, "mouseout", function() {
            self.unhighlightWaypoint("waypoint"+id);
         });
         */
      }

      if(type == "picture") {
         var picture = self.pictures[id];
         var name = picture['name'];
         var point = new GLatLng(picture['lat'],picture['lon']);
         marker = new GMarker(point, {title:name});

         GEvent.addListener(marker, "click", function() {
            picture = Edit.pictures[id];

            name = picture['name'];

            lat = picture['lat'];
            lon = picture['lon'];
            ele = picture['ele'];
            desc = picture['desc'];

            html = "<div style=''><b>" + name + "</b><br>"+desc+"<br>("+lat+","+lon+")</div>";

           marker.openInfoWindow(html);
         });
         GEvent.addListener(marker, "mouseover", function() {
            self.highlightPicture("picture"+id);
         });
         GEvent.addListener(marker, "mouseout", function() {
            self.unhighlightPicture("picture"+id);
         });
      }

      return marker;
   }

   
   this.addTempWaypoint = function(lat,lon,ele,name,desc) {
      var self = Edit;
      var waypoint = [];
      waypointId = self.numTempWaypoints;

      waypoint['name'] = name;
      waypoint['desc'] = desc;
      waypoint['lat'] = lat;
      waypoint['lon'] = lon;
      waypoint['ele'] = ele;
      waypoint['marker'] = null;
      self.tempWaypoints[waypointId] = waypoint;

      var marker = new GMarker(new GLatLng(lat,lon),{icon:self.waypointIcon});
      self.map.addOverlay(marker);

      waypoint['marker'] = marker;
      self.tempWaypoints[waypointId] = waypoint;

      //self.addWaypointRow(waypointId);
      self.numTempWaypoints++;
   }


   this.makeMarker = function(trackId,num,marker) {
      var self = Edit;
      

      GEvent.addListener(marker,"drag",function(point) {
            self.tracks[trackId]['points'][num] = marker.getPoint();



            self.map.removeOverlay(self.tracks[trackId]['polyline']);

            self.tracks[trackId]['polyline'] = new GPolyline(self.tracks[trackId]['points'],"#FF0000",2,1);
            self.map.addOverlay(self.tracks[trackId]['polyline']);
      });
      
      GEvent.addListener(marker,"click",function(point) {
            if(num == self.tracks[trackId]['points'].length-1 || num == 0) {
               self.stopEditTrack();
               
            }
      });
      
      
   }

   this.createTrack = function(points,trackColor,isPolygon,weight) {
      var self = Edit;
      var weight = weight || 2;
      var opacity = 1;
      /*
      var trackPoints = [];
      for(var i=0;i<points.length;i++) {
         var point = points[i];
         var trackPoint = point['trackPoint'];
         trackPoints.push(trackPoint);
      }
      */
      
      var polyline = null;

      if(points.length > 0) {
         if(isPolygon) {
            polyline = new GPolygon(points,"#FF0000",2,1,"#FF0000",.5);
         } else {
            polyline = new GPolyline(points,"#FF0000",2,opacity);
         }
         self.map.addOverlay(polyline);
      } else {
         var polyline = null;
      }
      return polyline;
   }

   this.addTempTrack = function(points,trackName,trackInfo,isPolygon,trackColor,trackLength,eles) {
      var self = Edit;

      var trackId = self.numTempTracks;
      var trackLength = trackLength || 0;  //trackColor || "#FF0000";
      var startMarker;
      var endMarker;

      var track = [];
      track['points'] = points;
      track['name'] = trackName;
      track['info'] = trackInfo;
      track['trackLength'] = trackLength;
      //track['db'] = trackDB;
      track['markers'] = [];
      track['eles'] = eles;
   
      track['isPolygon'] = isPolygon;
      
      self.tempTracks[trackId] = track;
      
      var type = "line";
      if(isPolygon) type = "area";
      //self.addElementRow(type,trackId);
     // self.addTrackRow(trackId);

      polyline = self.createTrack(points,trackColor,isPolygon);
      self.tempTracks[trackId]['polyline'] = polyline;
      //self.addTrackRow(trackId,trackName,trackColor,trackLength,showTrack);
     
      if(polyline) {
         self.map.addOverlay(polyline);
      }


      self.numTempTracks++;
   }
   


   this.zoomFit = function() {
      var self = Edit;

      var bounds = self.getBounds();

      zoom = self.map.getBoundsZoomLevel(bounds);
      if(zoom > 17) { zoom = 17; }
      center = bounds.getCenter();
      self.map.setCenter(center,zoom);
   }

   this.getBounds = function() {
      var self = Edit;
      var bounds = new GLatLngBounds();

      for(i=0; i<self.tracks.length;i++) {
         var track = self.tracks[i];
         if(track) {

            for(j=0;j<track['points'].length;j++) {
               var point = track['points'][j];
               bounds.extend(point);
            }
         }
      }
      
      for(i=0; i<self.waypoints.length;i++) {
         var waypoint = self.waypoints[i];
         if(waypoint) {
            bounds.extend(new GLatLng(waypoint['lat'],waypoint['lon']));
         }
      }

      return bounds;
   }
   
   
   this.getAllTrips = function() {
      var self = Edit;
      
     // if(self.map.getZoom() > 3) {
         /* remove old trips */
         
        // if(self.map.getZoom() != 0) {

            start = new Date();
            start = start.getTime();
            var bounds = self.map.getBounds();
            var ne = bounds.getNorthEast();
            var sw = bounds.getSouthWest();
      
            var minLat = sw.lat();
            var minLon = sw.lng();
            var maxLat = ne.lat();
            var maxLon = ne.lng();

            var query = "&minLat="+minLat+"&minLon="+minLon+"&maxLat="+maxLat+"&maxLon="+maxLon+"&activityId="+self.activityId;


            self.ajax.abort();
            self.ajax.doGet('/trip/gettripsbbox?start='+start+query, self.showAllTrips,"xml");
        // }
      //}
   }
   

   this.hideMapData = function() {
      var self = Edit;
      
      for(i=0; i<self.numTempTracks;i++) {
         track = self.tempTracks[i];
         if(track) {
            self.map.removeOverlay(track['polyline']);
            self.tempTracks[i] = null;
         }
      }
      
      for(i=0; i<self.numTempWaypoints;i++) {
         waypoint = self.tempWaypoints[i];
         if(waypoint) {
            self.map.removeOverlay(waypoint['marker']);
            self.tempWaypoints[i] = null;
         }
      }
   }

   this.grabMapData = function(articleId) {
      var self = Edit;
      query = "&articleId="+articleId;
      self.ajax.abort();
      self.ajax.doGet('extensions/get_data.php?tripId='+articleId, self.showMapData,"xml");
      
   }
   
   this.showMapData = function(xml) {
      var self = Edit;

      self.hideMapData();

      /* Get Tracks */
      res = [];
      res = XMLParse.xml2ObjArray(xml,'trk');
      trk = xml.getElementsByTagName('trk');
      for(var i = 0; i < res.length; i++) {
         var track = [];

         trackName = res[i].name;
         trackType = res[i].trackType;
         trackInfo = res[i].desc;
         trackLength = res[i].length;
         trackTags = res[i].tags || "";
         trackDB = res[i].track_id;
         res2 = XMLParse.xml2ObjArray(trk[i],'trkpt');
         points = [];
         eles = [];
         for(var j = 0; j < res2.length; j++) {

            lat = parseFloat(res2[j].lat);
            lon =  parseFloat(res2[j].lon);
            ele = res2[j].ele;
            time = res2[j].time;
            point = new GLatLng(lat,lon,true);
            /*
            points['trackPoint'] = point;
            points['trackLat'] = lat;
            points['trackLon'] = lon;
            points['trackEle'] = ele; */
            eles.push(ele);
            points.push(point);
            track.push(points);
         } 

         isPolygon = false;
         if(trackType == "area") isPolygon = true;

         self.addTempTrack(points,trackName, trackInfo,isPolygon,"#FF0000",trackLength,eles);
      }

      /* Get Waypoints */
      res = [];
      res = XMLParse.xml2ObjArray(xml,'wpt');
      var waypoints = [];
      for(var i = 0; i < res.length; i++) {
         lat = res[i].lat;
         lon = res[i].lon;
         ele = res[i].ele;
         name = res[i].name;
         desc = res[i].desc;
         waypointDB = res[i].waypoint_id
         tags = res[i].tags || "";

         self.addTempWaypoint(lat,lon,ele,name,desc);
      }
      
      
   }
   
   this.imageDimensions = function(imgSrc) {
      var newImg = new Image();
      newImg.src = imgSrc;
      var height = newImg.height;
      var width = newImg.width;

      var dim = [];
      dim['height'] = height;
      dim['width'] = width;

      return dim;
   }

   this.drawBbox = function(bounds,articleName,articleId,img) {
      var self = Edit;
      var marker = new GMarker(bounds,{title:articleName,icon:self.tripIcon});

      GEvent.addListener(marker,"click",function() {
          var maxDim = 100;
          /*
         var dim = self.imageDimensions(img);
         var widthHeight = "";

         if(dim['width'] > dim['height']) {
            widthHeight = "width='"+maxDim+"'";
         } else {
            widthHeight = "height='"+maxDim+"'";
         }
           */
	  var articleName2 = articleName.replace(" ","_");
         var html = "<div style='min-height:110px;'><A href=\"/trip/view?trip_id="+articleId+"\">"+articleName+"</a><br>";
         
        // top.location.href = articleName2;


         if(img && img != "") { html += "<img class='img"+maxDim+"h img"+maxDim+"w' src="+img+" style='max-height:"+maxDim+"px;max-width:"+maxDim+"px'><br>"; }
            
         html+= "</div>";
         self.map.openInfoWindow(marker.getPoint(),html);
      });
      
      GEvent.addListener(marker,"mouseover",function() {
       //  self.dataAjax(articleId);
         //self.grabMapData(articleId);
      });
      
      GEvent.addListener(marker,"mouseout",function() {
         //self.hideMapData();
      });

      self.tripMarkers.push(marker);
      self.map.addOverlay(marker);
   }

   this.showAllTrips = function(xml) {
      var self = Edit;
    
	

      for(var i=0; i<self.tripMarkers.length; i++) {
         self.map.removeOverlay(self.tripMarkers[i]);
      }

      
      /* Get Waypoints */
      document.getElementById('num_trips').innerHTML = 0;
      document.getElementById('num_trips_extra').innerHTML = "";

      var res = [];
      res = XMLParse.xml2ObjArray(xml,'trip');
      var trips = [];
      var n = 1;


      for(var i = 0; i < res.length; i++) {
         var lat = res[i].centerLat;
         var lon = res[i].centerLon;
         var articleName = res[i].articleName;
         var articleId = res[i].articleId;
         var img = res[i].img;



         self.drawBbox(new GLatLng(lat,lon),articleName,articleId,img);
         document.getElementById('num_trips').innerHTML = n;


        n++;
      }
      
      if(n == 101) {
         document.getElementById('num_trips').innerHTML = "100 most popular";
         document.getElementById('num_trips_extra').innerHTML = "  Zoom in to see more";
      }

      
      
   }
   
   this.removeHelpDiv = function() {
      var self = Edit;
      
      var div = document.getElementById('helpDiv');
      if(div) {
         self.mapDiv.removeChild(div);
      }

   }
   
   this.addHelpDiv = function(text,point) {
      var self = Edit;
      
      var div = document.createElement('div');
      div.id = 'helpDiv';
      div.innerHTML = text;
      div.style.position = 'absolute';
      div.style.top = point.y + 'px';
      div.style.left = point.x + 'px';
      div.style.zindex = 110;
      div.style.border = "1px solid #CCCCCC";
      div.style.backgroundColor = "#FFFFFF";
      
      self.mapDiv.appendChild(div);
   }
   
   this.doSearch = function(e) {
      //alert("a");
      e = window.event
      if (!e) e = window.event;
      if (e.keyCode == 13) {
         Edit.getGPSLocation(document.getElementById('address').value);
         return false;
      }
   }
   
   this.createArticle = function() {
      var self = Edit;
      var center = self.map.getCenter();
      lat = center.lat();
      lon = center.lng();
      zoom = self.map.getZoom();
      
      top.location.href = "/wiki/Special:EditMap&center_lat="+lat+"&center_lon="+lon+"&zoom="+zoom;


   }


}