/*
Info

markers are stored in an a 2-dimensional array,
   array(marker,waypointLon,waypointLat,waypointName,waypointInfo);

TODO:
1) on dradgging, update the markers array and make sure that the waypointInfo and waypointName stay the same                                          

*/



Edit = new function() {
   this.ajax = null;
   this.tableDiv = null;
   this.table = null;
   this.waypointTable = null;
   this.tracksTable = null;
   this.pictureTable = null;
   this.noteTable = null;
   this.map = null;
   this.currEdited = null;
   this.numRows = 0;
   this.centerLat = 0;
   this.centerLon = 0;
   this.zoom = 0;
   this.user = [];
   this.trip = [];
   this.waypointMarkers = [];
   this.tracks = [];
   this.pictures = [];
   this.notes = [];
   this.activities = [];
   this.surfaces = [];
   this.panoramioPhotos = [];
   this.numWaypoints = 0;
   this.numTracks = 0;
   this.numPictures = 0;
   this.numNotes = 0;
   this.statusDiv = null;
   this.allPictures = [];

   this.textField = document.createElement("input");
   this.textField.type = "text";
   this.textField.size = 15;
   this.textField.onblur = function() {
      var self = Edit;
      self.currEdited.removeChild(this);
      self.currEdited.innerHTML = this.value;
      var cellId = self.currEdited.id;
      rowId = cellId.replace(/waypoint/,'');
      waypointId = rowId.replace(/Lon|Lat|Name|Info/,'');
      cellType = rowId.replace(waypointId,'');  //ERROR

      if(cellType == "Lon" || cellType == "Lat" || cellType == "Name" || cellType == "Info") {
         pointLatId = "waypoint" + waypointId + "Lat";
         pointLonId = "waypoint" + waypointId + "Lon";
         pointLatCell = document.getElementById(pointLatId);
         pointLonCell = document.getElementById(pointLonId);

         pointLat = pointLatCell.innerHTML;
         pointLon = pointLonCell.innerHTML;

         self.updateWaypointLocation(cellId,pointLat,pointLon);
      }

      this.value = "";
      self.currEdited = null;
   }

   this.textField.onkeypress = function(e) {
      if (!e) e = window.event;
      if (e.keyCode == 13) { this.blur();}
   }

   this.init = function() {
      var self = Edit;
      self.ajax = new Ajax();
    //  self.tableDiv = document.getElementById('tableDiv');
     // self.table = document.getElementById('table');
     // self.waypointTable = document.getElementById('viewtrip_waypoints');
    //  self.tracksTable = document.getElementById('viewtrip_tracks');

      self.centerLat = "37.42173";;
      self.centerLon = "-122.18654";
      self.zoom = "15";
      self.makeIcons();
      //self.load();

      //self.dataAjax();
      
   }

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

      if (GBrowserIsCompatible()) {
        Edit.map = new GMap2(self.mapDiv);
        Edit.map.addControl(new GLargeMapControl());
        Edit.map.setCenter(self.centerPoint, 2);
        var mapType = getMapFromName(Edit.mapType);

        Edit.map.setMapType(mapType);
        Edit.map.addControl(new GV_MapTypeControl());

        self.map.enableDoubleClickZoom();

         self.map.enableContinuousZoom();
         
         
         /* overview */
         if(self.miniMapDiv) {
            Edit.miniMap = new GMap2(self.miniMapDiv)
            Edit.miniMap.setCenter(self.centerPoint,3);
            Edit.miniMap.setMapType(G_NORMAL_MAP);
               marker = new GMarker(self.centerPoint);
            Edit.miniMap.addOverlay(marker);
         }
        
        // self.addGoogleEarthToMap();
     //   self.addFullScreenToMap();

      }
    }
    
    this.showThumbnailDiv = function(point,pictureId) {
      var self = Edit;
      
      picture = self.pictures[pictureId];
      thumb = picture['thumb'];

      maxDim = 400;


      var px1 = self.map.fromLatLngToDivPixel(point);
      var px2 = self.map.fromLatLngToDivPixel((self.map.getBounds()).getSouthWest());
      
      var mapHeight = 425;
      var px = new GPoint(px1.x-px2.x,px1.y-px2.y+mapHeight);


      self.currPicDiv = document.createElement('div');
      self.currPicDiv.style.position = 'absolute';
      //self.currPicDiv.style.width = "50px";
      //self.currPicDiv.style.height = "50px";
      self.currPicDiv.style.top = px.y+2 + 'px';
      self.currPicDiv.style.left = px.x+2 + 'px';
      self.currPicDiv.style.zindex = 100;
      self.currPicDiv.style.border = "1px solid #000000";
      
      self.currPicDiv.innerHTML = '<div style="border: 2px solid #FFFFFF"><img src="'+thumb+'" style="max-width:'+maxDim+'px; max-height:'+maxDim+'px; "></div>';
      
      


      self.mapDiv.appendChild(self.currPicDiv);
    

      
      
     /*
      var addMarker = document.createElement('input');
      addMarker.type = 'image';
      addMarker.src = 'extensions/images/add_marker_button.png';
      addMarker.alt = 'Add Waypoint';
      addMarker.style.position = 'absolute';
      addMarker.style.top = '5px';
      addMarker.style.left = '70px';
      addMarker.style.zindex = 100;   */

   }
   
   this.makeIcons = function() {
      var self = Edit;
      
      self.inactiveIcon = new GIcon();
      self.inactiveIcon.image = "images/marker.png";
      self.inactiveIcon.iconSize = new GSize(15, 15);
      self.inactiveIcon.shadowSize = new GSize(15, 15);
      self.inactiveIcon.iconAnchor = new GPoint(8, 8);
      self.inactiveIcon.infoWindowAnchor = new GPoint(8, 8);

      self.activeIcon = new GIcon();
      self.activeIcon.image = "images/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.trackStartIcon = new GIcon();
      self.trackStartIcon.image = "images/trackstart.png";
      self.trackStartIcon.iconSize = new GSize(16, 25);
      self.trackStartIcon.shadowSize = new GSize(16, 25);
      self.trackStartIcon.iconAnchor = new GPoint(16, 13);
      self.trackStartIcon.infoWindowAnchor = new GPoint(8, 8);
      
      
      self.trackEndIcon = new GIcon();
      self.trackEndIcon.image = "images/trackend.png";
      self.trackEndIcon.iconSize = new GSize(16, 25);
      self.trackEndIcon.shadowSize = new GSize(16, 25);
      self.trackEndIcon.iconAnchor = new GPoint(16, 13);
      self.trackEndIcon.infoWindowAnchor = new GPoint(8, 8);
      
      self.waypointIcon = new GIcon();
      self.waypointIcon.image = "images/red_marker_small.png";
      self.waypointIcon.iconSize = new GSize(11, 19);
      self.waypointIcon.shadowSize = new GSize(11, 19);
      self.waypointIcon.iconAnchor = new GPoint(6, 19);
      self.waypointIcon.infoWindowAnchor = new GPoint(6, 10);

   }
    
    
    this.addLoadingDiv = function(message) {

      var self = Edit;

      var mapContainer = self.mapDiv;

      self.statusDiv = document.createElement('div');
      self.statusDiv.id = 'statusDiv';

      var messageWidth = 120;
      var messageHeight = 20;

      var mapWidth = mapContainer.style.width.replace('px','');
      var mapHeight = mapContainer.style.height.replace('px','');


      var leftPos = (mapWidth-messageWidth)/2;
      var topPos = (mapHeight-messageHeight)/2;

      self.statusDiv.style.position = "absolute";
      self.statusDiv.style.zindex = 100;
      self.statusDiv.style.backgroundColor = "#FFFFFF";
      self.statusDiv.style.border = "2px solid #000000";
      self.statusDiv.style.left = leftPos+'px';
      self.statusDiv.style.top = topPos+'px';
      self.statusDiv.style.width = messageWidth + "px";
      self.statusDiv.style.height = messageHeight + "px";
      self.statusDiv.align = "center";
      self.statusDiv.verticalAlign = "middle";

      self.statusDiv.innerHTML = "<font size=+0>"+message+"</font>";

      mapContainer.appendChild(self.statusDiv);

   }
   
   this.removeLoadingDiv = function() {
      var self = Edit;
      
      self.mapDiv.removeChild(self.statusDiv);
      self.statusDiv = null;
   }


   this.editTextField = function(){
      var self = Edit;
      if (self.currEdited == this) return;
      self.textField.value = this.innerHTML;
      this.innerHTML = "";
      this.appendChild(self.textField);
      self.currEdited = this;


      self.textField.focus();
      self.textField.select();
   }
   this.deleteNote = function(id) {}

   this.makeDelete = function(row,id,type) {
      var self = Edit;
      var cell = row.insertCell(row.cells.length);
      cell_num = row.cells.length;
      cell.align = "center";

      var deleteButton = document.createElement("input");
      deleteButton.type = "submit";
      deleteButton.value = "Delete";


      if(type == "waypoint") {
         deleteButton.onclick = function() { self.deleteWaypoint(id); };
      } else if(type == "track") {
         deleteButton.onclick = function() { self.deleteTrack(id); };
      } else if(type == "picture") {
         deleteButton.onclick = function() { self.deletePicture(id); };
      } else if(type == "note") {
         deleteButton.onclick = function() { self.deleteNote(id); };
      }

      cell.appendChild(deleteButton);
      deleteButton = null;
      //cell.width = "0";      // ERROR
   }
   this.hideWaypoint = function() { }
   this.hideTrack = function() { }
   this.hidePicture = function() { }
   this.hideNote = function() { }
   this.hideTracksTable = function() { };

   this.makeHidebox = function(row,id,type,shouldShow) {
      var self = Edit;
      var cell = row.insertCell(row.cells.length);
      cell_num = row.cells.length;
      cell.align = "center";

      var checkbox = document.createElement("input");
      checkbox.type = "checkbox";
      checkbox.id = type + "Hidebox" + id;



      if(type == "waypoint") {
         checkbox.onclick = function() { self.hideWaypoint(id); };
      } else if(type == "track") {
         checkbox.onclick = function() { self.hideTrack(id); };
      } else if(type == "picture") {
         checkbox.onclick = function() { self.hidePicture(id); };
      } else if(type == "note") {
         checkbox.onclick = function() { self.hideNote(id); };
      }

      cell.appendChild(checkbox);
      //checkbox = document.getElementById(type+"Hidebox"+id);
      checkbox.checked = shouldShow;
      checkbox = null;
     // cell.width = "0";  ERROR
   }

   this.makeEdit = function(row,id,type,show) {
      var self = Edit;
      var cell = row.insertCell(row.cells.length);
      cell_num = row.cells.length;
      cell.align = "center";

      var editButton = document.createElement("input");
      editButton.type = "submit";
      editButton.value = "Edit";
      editButton.id = type+"Edit"+id;
      editButton.disabled = !show;

      if(type == "waypoint") {
         editButton.onclick = function() { self.editWaypoint(id); };
      } else if(type == "track") {
         editButton.onclick = function() { self.editTrack(id); };
      } else if(type == "picture") {
         editButton.onclick = function() { self.editPicture(id); };
      } else if(type == "note") {
         editButton.onclick = function() { self.editNote(id); };
      }

      cell.appendChild(editButton);
      editButton = null;
     // cell.width = "0"; ERROR
   }
   
   this.makeZoom = function(row,id,type,show) {
      var self = Edit;
      var cell = row.insertCell(row.cells.length);
      cell_num = row.cells.length;
      cell.align = "center";

      var zoomButton = document.createElement("input");
      zoomButton.type = "image";
      zoomButton.src = "images/zoom.gif";
      zoomButton.className = "btns";
      zoomButton.value = "Zoom";
      zoomButton.id = type+"Zoom"+id;
      zoomButton.disabled = !show;

      if(type == "waypoint") {
         zoomButton.onclick = function() { self.zoomWaypoint(id); };
      } else if(type == "track") {
         zoomButton.onclick = function() { self.zoomTrack(id); };
      } else if(type == "picture") {
         zoomButton.onclick = function() { self.zoomPicture(id,true); };
      } else if(type == "note") {
         zoomButton.onclick = function() { self.zoomNote(id); };
      }

      cell.appendChild(zoomButton);
      zoomButton = null;
     // cell.width = "0"; ERROR
   }

   this.addRow = function () {
      var self = Edit;
      var row;
      
      if (self.table.rows.length == 0) {
         row = self.table.insertRow(0);
         self.makeCell(row, "Lat", false, self.numRows);
         self.makeCell(row, "Lon", false, self.numRows);
         self.makeCell(row, "Delete", false, self.numRows);
         self.numRows++;
      }

      row = self.table.insertRow(self.numRows);
      self.makeCell(row, "test", true, self.numRows);
      self.makeCell(row,"par", true, self.numRows);
      //self.makeDelete(row,"way);
      self.numRows++;
   }
   this.updateWaypointLocation = function(cellId,pointLat,pointLon) {
      var self = Edit;
      rowId = cellId.replace(/waypoint/,'');
      waypointId = rowId.replace(/Lon|Lat|Name|Info/,'');
      var waypoint = self.waypointMarkers[waypointId]
      var cell = document.getElementById(cellId);

      /* Move marker */
      if(waypoint) {
         var oldLat = waypoint['pointLat'];
         var oldLon = waypoint['pointLon'];
         var waypointMarker = waypoint['waypointMarker'];

         /* Update point if it is different */
         if(oldLat != pointLat || oldLon != pointLon) {
            
            newPoint = new GLatLng(pointLat,pointLon);
            waypointMarker.setPoint(newPoint);
            /* Add check so they can only enter numbers */

         }
         pointName = document.getElementById("waypoint"+waypointId+"Name").innerHTML;
         pointInfo = document.getElementById("waypoint"+waypointId+"Info").innerHTML;
         self.updateWaypointArray(waypointId,pointLat,pointLon,pointName,pointInfo,waypointMarker,showWaypoint);
      }
   }

   this.updateWaypointRow = function(waypointId,pointLat,pointLon,pointEle,pointName) {
      var self = Edit;
      rowId = "waypoint" + waypointId;
      cellNameId = rowId + "Name";
      cellNameId = document.getElementById(cellNameId);
      cellNameId.innerHTML = pointName;

      pointLatRound = Math.round(pointLat*100000)/100000;
      pointLonRound = Math.round(pointLon*100000)/100000;
      pointEleRound = Math.round(pointEle*100000)/100000;


      cellLatId = rowId + "Lat";
      cellLatId = document.getElementById(cellLatId);
      cellLatId.innerHTML = pointLatRound;

      cellLonId = rowId + "Lon";
      cellLonId = document.getElementById(cellLonId);
      cellLonId.innerHTML = pointLonRound;
      
      cellEleId = rowId + "Ele";
      cellEleId = document.getElementById(cellEleId);
      cellEleId.innerHTML = pointEleRound;
   }

   this.updateWaypointArray = function(waypointId,pointLat,pointLon,pointEle,pointName,pointInfo,pointTags,waypointDB,pointMarker,showWaypoint) {
      var self = Edit;
      var waypoint = [];

      waypoint['waypointLat'] = pointLat;
      waypoint['waypointLon'] = pointLon;
      waypoint['waypointEle'] = pointEle;
      waypoint['waypointTags'] = pointTags; 
      waypoint['waypointName'] = pointName;
      waypoint['waypointInfo'] = pointInfo;
      waypoint['waypointMarker'] = pointMarker;
      waypoint['showWaypoint'] = showWaypoint;

      self.waypointMarkers[waypointId] = waypoint;
   }

   this.updateWaypointMarker = function(waypointId,pointLat,pointLon,marker) {
      newPoint = new GLatLng(pointLat,pointLon);
      marker.setPoint(newPoint);
   }

   this.makeCell = function(cellId, row, text, editable, id,cellWidth) {
      var self = Edit;
      var cellNum = row.cells.length;

      self.cell = row.insertCell(cellNum);
      self.cell_num = row.cells.length;
      self.cell.align = "left";
      if (editable) {
         self.cell.style.cursor = "text";
         self.cell.onclick = self.editTextField;
         self.cell.onchange = self.updateWaypointLocation(self.cell.id);
      }

      self.cell.innerHTML = text;
      self.cell.width = cellWidth;
      if(text == "Info") {
         self.cell.width = 200;
      }

      self.cell.id = cellId;


   }

   this.addWaypointHeader = function() {
      var self = Edit;
      row = self.waypointTable.insertRow(0);
      header = row.insertCell(0);
      header.align = "left";
      header.colSpan = 5;
      header.id = "waypointsHeader";
      header.innerHTML = "Waypoints <a href=# onclick='Edit.hideWaypointsTable();'>hide</a>";
      
      /*
      row = self.waypointTable.insertRow(1);
      self.makeCell("waypointLat",row,"",false,0);
      self.makeCell("waypointLon",row,"",false,0);
      self.makeCell("waypointName",row,"",false,0);
      self.makeCell("waypointInfo",row,"Name",false,0,"100%");
     // self.makeCell("waypointDelete",row,"Delete",false,0);
     */
   }

   this.addWaypointRow = function(waypointId,pointLat, pointLon,pointEle,pointName,pointInfo,showWaypoint) {
      var self = Edit;
      var row;
      var rowNumber = self.waypointTable.rows.length;
      var rowClass;
      /*
      if(rowNumber == 0) {
         self.addWaypointHeader();
         rowNumber += 1;
      }  */
      
      if(rowNumber % 2 == 1) {
         rowClass = "row_one";
      } else {
         rowClass = "row_two";
      }

      row = self.waypointTable.insertRow(rowNumber);
      row.className = rowClass;
      row.id = "waypoint" + waypointId;

      pointLatRound = Math.round(pointLat*100000)/100000;
      pointLonRound = Math.round(pointLon*100000)/100000;
      pointEleRound = Math.round(pointEle);
      
      units = self.unitPref("height");
      
      pointLatRound = self.gpsUnit(pointLatRound);
      pointLonRound = self.gpsUnit(pointLonRound);


     // self.makeDelete(row,waypointId,"waypoint");
      self.makeHidebox(row,waypointId,"waypoint",showWaypoint);
      //self.makeEdit(row,waypointId,"waypoint");
      self.makeZoom(row,waypointId,"waypoint",showWaypoint);
      self.makeCell(row.id+"Name",row,pointName,false,rowNumber,"50%");
      self.makeCell(row.id+"Lat",row,pointLatRound,false,rowNumber,"25%");
      self.makeCell(row.id+"Lon",row,pointLonRound,false,rowNumber,"25%");
      self.makeCell(row.id+"Ele",row,pointEleRound + " " + units,false,rowNumber,"25%");
   }
   this.statusDivControl = function(option) {
      var self = Edit;
      
       mapContainer = self.map.getContainer();
      
      if(option == "start") {
         self.statusDiv = document.createElement('div');
         self.statusDiv.id = 'statusDiv';

         self.statusDiv.className = 'startStatus';
         
         messageWidth = self.statusDiv.style.width.replace('px','') || 100;
         messageHeight = self.statusDiv.style.height.replace('px','') || 24;

         mapWidth = mapContainer.style.width.replace('px','');
         mapHeight = mapContainer.style.height.replace('px','');


         leftPos = (mapWidth-messageWidth)/2;
         topPos = (mapHeight-messageHeight)/2;

         self.statusDiv.style.left = leftPos+'px';
         self.statusDiv.style.top = topPos+'px';

         self.statusDiv.innerHTML = "Loading...";

         mapContainer.appendChild(self.statusDiv);


      } else {
         mapContainer.removeChild(self.statusDiv);
         self.statusDiv.innerHTML = ""
      }
   }
   
   this.addGoogleEarthToMap = function() {
      var self = Edit;
      mapContainer = self.map.getContainer();
      
      self.googleEarthDiv = document.createElement('span');
      self.googleEarthDiv.id = 'googleEarthDiv';

      self.googleEarthDiv.className = 'googleEarthDiv';
         
      messageWidth =  85;
      messageHeight =  20;

      mapWidth = mapContainer.style.width.replace('px','');
      mapHeight = mapContainer.style.height.replace('px','');

      //fullScreenWidth = self.fullScreenDiv.style.width.replace('px','');


      leftPos = (mapWidth-messageWidth)/2;
      topPos = 8;

      self.googleEarthDiv.style.left = leftPos+'px';
      self.googleEarthDiv.style.top = topPos+'px';

      self.googleEarthDiv.innerHTML = "Google Earth";
      
      self.googleEarthDiv.onclick = function() {
         self.googleEarthAjax();
      };


      self.map.getContainer().appendChild(self.googleEarthDiv);
   }
   
   this.mapTypeTitle = function() {
      var self = Edit;
      mapContainer = self.map.getContainer();
      
      self.mapTypeDiv = document.createElement('span');
      self.mapTypeDiv.id = 'mapTypeDiv';

      self.mapTypeDiv.className = 'mapTypeDiv';

      messageWidth =  45;
      messageHeight =  14;

      mapWidth = mapContainer.style.width.replace('px','');
      mapHeight = mapContainer.style.height.replace('px','');

      //fullScreenWidth = self.fullScreenDiv.style.width.replace('px','');


      leftPos = mapWidth-400;
      topPos = 8;

      self.mapTypeDiv.style.left = leftPos+'px';
      self.mapTypeDiv.style.top = topPos+'px';

      self.mapTypeDiv.innerHTML = "Map Type";

      self.map.getContainer().appendChild(self.mapTypeDiv);
   }

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

      var w = document.documentElement.clientWidth; 
      w = w-10
      var h = parseInt(document.documentElement.clientHeight)-50; 
      
      return GB_show('Everytrail - '+self.tripName+' - Full Screen', 'http://www.everytrail.com/iframe.php?noFrame=true&trip_id='+self.tripId+'&fullscreen=true&width=100%&height='+h+'px', h, w);
   }
   
   this.verticalProfile = function() {
      var self = Edit;

      var w = 550;
      var h = 350;

      return GB_show('Everytrail - '+self.tripName+' - Vertical Profile', 'http://www.everytrail.com/ChartsApp/Chart.php?trip_id='+self.tripId, h, w);
   }
   


   this.addFullScreenToMap = function() {
      var self = Edit;
      mapContainer = self.map.getContainer();
      
      self.fullScreenDiv = document.createElement('span');
      self.fullScreenDiv.id = 'fullScreenDiv';

      self.fullScreenDiv.className = 'fullScreenDiv';

      messageWidth =  85;
      messageHeight =  20;

      mapWidth = mapContainer.style.width.replace('px','');
      mapHeight = mapContainer.style.height.replace('px','');                   


      leftPos = 75;
      topPos = 8;
     // leftPos = mapWidth-400;

      self.fullScreenDiv.style.left = leftPos+'px';
      self.fullScreenDiv.style.top = topPos+'px';

      self.fullScreenDiv.innerHTML = "Full Screen";

      self.fullScreenDiv.onclick = function() {
         self.fullScreen();
      };
        
      self.map.getContainer().appendChild(self.fullScreenDiv);
   }
   
   this.showPanoramioPhotos = function(show) {
      var self = Edit;
      
      for(var i=0; i<self.panoramioPhotos.length; i++) {
         pan = self.panoramioPhotos[i];
         marker = pan['pictureMarker'];
         
         if(marker) {
            if(show) {
               self.map.addOverlay(marker);
            } else {
               self.map.removeOverlay(marker);
            }
         }  
      }

   }

   this.getPanoramioPhotos = function(show) {
      var self = Edit;

      if(self.panoramioPhotos.length == 0 && show) {

         var bounds = self.getTripBounds();
         var sw = bounds.getSouthWest();
         var ne = bounds.getNorthEast();

         self.ajax.abort();
         var url = "panoramio.php?w="+sw.lng()+"&s="+sw.lat()+"&n="+ne.lat()+"&e="+ne.lng();


         self.ajax.doGet(url, self.panoramioResponse,"text");
      } else if(self.panoramioPhotos.length > 0) {
         self.showPanoramioPhotos(show);
      }
   }

   this.panoramioResponse = function(rsp) {
      var self = Edit;

      var cmd = rsp.parseJSON();

      for(var i=0; i<cmd.photos.length; i++) {
         pan = [];

         photo = cmd.photos[i];


         pan['pictureName'] = photo.photo_title;
         pan['pictureThumbnail'] = "http://www.panoramio.com/photos/small/"+photo.photo_id+".jpg";
         pan['pictureFullsize'] = "http://www.panoramio.com/photos/medium/"+photo.photo_id+".jpg";
         pan['pictureLat'] = photo.latitude;
         pan['pictureLon'] = photo.longitude;
         pan['pictureEle'] = photo.height;
         pan['pictureOwnerName'] = photo.owner_name;
         pan['pictureOwnerId'] = photo.owner_id;
         pan['pictureId'] = photo.photo_id;
         point = new GLatLng(photo.latitude,photo.longitude);

         self.panoramioPhotos.push(pan);


                            pan['pictureMarker']
         pan['pictureMarker'] = self.createPanoramioMarker(self.panoramioPhotos.length-1);


          //alert(pan['pictureMarker'].getPoint());
         self.map.addOverlay(pan['pictureMarker']);





         //self.addPicture(pictureName,"",pictureThumbnail,pictureFullsize,pictureLat,pictureLon,pictureEle,pictureTime,"false")
      }
   }
   
   this.addTrackMarkers = function() {
      var self = Edit;
      
      if(self.tracks.length > 0) {
         var startTrack = self.tracks[0];
         var endTrack = self.tracks[self.tracks.length-1];
         
         if(startTrack['trackPoints'][0] && startTrack['trackPoints'][0]['trackPoint']) {
            try {
            var startPoint = startTrack['trackPoints'][0]['trackPoint'];
            var startMarker = new GMarker(startPoint,self.trackStartIcon);
            self.map.addOverlay(startMarker);
            } catch(e) {
            }
         }

         if(endTrack['trackPoints'][endTrack['trackPoints'].length-1]) {
            try {
            var endPoint = endTrack['trackPoints'][endTrack['trackPoints'].length-1]['trackPoint'];
            var endMarker = new GMarker(endPoint,self.trackEndIcon);
            self.map.addOverlay(endMarker);
            } catch(e) {
            }
         }


      }


   }


   this.dataAjax = function() {
      var self = Edit;
      var tripId = self.tripId;

      start = new Date();
      start = start.getTime();
      self.ajax.doGet('get_data.php?tripId='+tripId+'&start='+start, self.uploadDataResponse,"xml");
      self.addLoadingDiv("Loading...");
   }

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


      /* Get User */
      var res = [];
      res = XMLParse.xml2ObjArray(xml,'userPref');
      for(var i = 0; i < res.length; i++) {
         self.user['lengthUnit'] = res[i].lengthUnit;
         self.user['gpsUnit'] = res[i].gpsUnit;
      }

      /* Get Trip */
      var res = [];
      res = XMLParse.xml2ObjArray(xml,'trip');
      for(var i = 0; i < res.length; i++) {
         self.trip['tripName'] = res[i].tripName;
         self.trip['tripInfo'] = res[i].tripInfo;
         self.trip['tripDate'] = res[i].tripDate;
         self.trip['tripTags'] = res[i].tripTags;
         self.trip['tripCenterLat'] = parseInt(res[i].tripCenterLat) || 0;
         self.trip['tripCenterLon'] = parseInt(res[i].tripCenterLon) || 0;
         self.trip['tripZoom'] = parseInt(res[i].tripZoom) || 0;
         self.trip['tripUserId'] = res[i].tripUserId;
         self.trip['tripUsername'] = res[i].tripUsername;
         self.user['userPhoto'] = res[i].userPhoto

      }
      //self.makeTripTable();
      

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

         var trackName = res[i].name;
         var trackInfo = res[i].desc;
         var trackLength = res[i].length;
         var trackTags = res[i].tags || "";
         var trackDB = res[i].track_id;
         var res2 = XMLParse.xml2ObjArray(trk[i],'trkpt');
         for(var j = 0; j < res2.length; j++) {
            var points = [];
            var lat = parseFloat(res2[j].lat);
            var lon = parseFloat(res2[j].lon);
            var ele = res2[j].ele;
            var time = res2[j].time;
            var point = new GLatLng(lat,lon,true);
                  
            points['trackPoint'] = point;
            points['trackLat'] = parseFloat(lat);
            points['trackLon'] = parseFloat(lon);
            points['trackEle'] = ele;
            points['trackTime'] = time;
            track.push(points);
         } 
         self.addTrack(track,trackName, trackInfo,"#0000FF",trackLength,trackTags,trackDB);
      }
      
      self.addTrackMarkers();

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

         self.addWaypoint(lat,lon,ele,name,desc,tags,waypointDB,"false");
      }

      /* Get Pictures */
      /*
      res = [];
      res = XMLParse.xml2ObjArray(xml,'picture');
      var notes = [];
      for(var i = 0; i < res.length; i++) {
         pictureLat = res[i].lat;
         pictureLon = res[i].lon;
         pictureEle = res[i].ele;
         pictureName = res[i].name || "";
         pictureInfo = res[i].desc || "";
         pictureThumbnail = res[i].picture_thumbnail;
         pictureFullsize = res[i].picture_fullsize;
         pictureTime = res[i].time;
         server = res[i].server;
         serverLink = res[i].serverLink;
         picWidth = parseInt(res[i].width);
         picHeight = parseInt(res[i].height);
         picId = res[i].picture_id;

        // self.addPicture(pictureName,pictureInfo,pictureThumbnail,pictureFullsize,pictureLat,pictureLon,pictureEle,pictureTime,"false");
          self.addPicture(pictureLat,pictureLon,pictureName,pictureInfo,pictureThumbnail,pictureFullsize,server,serverLink,picWidth,picHeight,picId);
      }  */
      
      self.addAllPictures();




     // if(self.trip['tripCenterLat'] == 0 && self.trip['tripCenterLat'] == 0 && self.trip['tripZoom'] == 0) {
         //self.getPanoramioPhotos();
         self.zoomFit();

         //self.getPanoramioPhotos(false);

    //  }
   }
   
   this.addAllPictures = function() {
      var self = Edit;
      
      for(i=0;i<self.allPictures.length;i++) {
         pictureLat = self.allPictures[i]['lat'];
         pictureLon = self.allPictures[i]['lon'];
         pictureName = self.allPictures[i]['name'];
         pictureInfo = self.allPictures[i]['desc'];
         pictureThumbnail = self.allPictures[i]['thumb'];
         pictureFullsize = self.allPictures[i]['full'];
         server = self.allPictures[i]['server'];
         serverLink = self.allPictures[i]['serverLink'];
         picWidth = self.allPictures[i]['picWidth'];
         picHeight = self.allPictures[i]['picHeight'];
         picId = self.allPictures[i]['id'];

         self.addPicture(pictureLat,pictureLon,pictureName,pictureInfo,pictureThumbnail,pictureFullsize,server,serverLink,picWidth,picHeight,picId);

      }
   }

   this.addWaypoint = function(pointLat, pointLon, pointEle,pointName,pointInfo,pointTags,waypointDB,editWaypoint) {
      var self = Edit;

      var point;
      var waypoint = [];
      var image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
      pointInfo = pointInfo || "";
      pointName = pointName || "untitled waypoint";
      pointEle = pointEle || 0;
      editWaypoint = editWaypoint || "true";
      waypointDB = waypointDB || "";
      var showWaypoint = true;

      if(pointLon && pointLat) {
         var point = new GLatLng(pointLat,pointLon);
      } else {
         var point = self.map.getCenter();
         pointLat = point.lat();
         pointLon = point.lng();
      }
      var waypointId = self.numWaypoints;


      waypoint['waypointName'] = pointName;
      waypoint['waypointInfo'] = pointInfo;
      waypoint['waypointLat'] = pointLat;
      waypoint['waypointLon'] = pointLon;
      waypoint['waypointEle'] = pointEle;
      waypoint['waypointTags'] = pointTags;
      waypoint['waypointDB'] = waypointDB;
      waypoint['showWaypoint'] = showWaypoint;
      waypoint['waypointMarker'] = null;
      self.waypointMarkers[waypointId] = waypoint;

      var marker = self.createPin("waypoint", waypointId);
      self.map.addOverlay(marker);

      waypoint['waypointMarker'] = marker;
      self.waypointMarkers[waypointId] = waypoint;

    //  self.addWaypointRow(waypointId,pointLat, pointLon,pointEle,pointName,pointInfo,showWaypoint);
      self.numWaypoints++
      

      if(editWaypoint == "true") {
         self.editWaypoint(waypointId);
      }
   }
   this.rowActive = function(isActive,type,id) {
      var self = Edit;

      zoomBox = document.getElementById(type+"Zoom"+id);


         row = document.getElementById(type+id);
         if(isActive) {
            zoomBox.disabled = false;
          //  row.className = "disabledRow";
         } else {
            zoomBox.disabled = true;
          //  row.className = "enabledRow";
         }


   }

   this.hideWaypoint = function(waypointId,showHide) {
      var self = Edit;
      waypoint = self.waypointMarkers[waypointId];

      hidebox = document.getElementById("waypointHidebox" + waypointId);

      if(showHide == "show") {
         showWaypoint = true;
      } else if(showHide == "hide") {
         showWaypoint = false;
      } else {
         showWaypoint = hidebox.checked;
      }
      waypointMarker = waypoint['waypointMarker'];

      if(showWaypoint) {
         self.map.addOverlay(waypointMarker);
         hidebox.checked = true;
         self.rowActive(true,"waypoint",waypointId);
      } else {
         self.map.removeOverlay(waypointMarker);
         self.map.closeInfoWindow();
         hidebox.checked = false;
         self.rowActive(false,"waypoint",waypointId);
      }
      waypoint['showWaypoint'] = showWaypoint;
      self.waypointMarkers[waypointId] = waypoint;

   }

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

      var numWaypoints = self.waypointTable.rows.length;

      for(var i=0; i<numWaypoints; i++) {
         self.waypointTable.deleteRow(0);
      }
      
  
      var header = document.getElementById('hideWaypoints');
      header.innerHTML = '<a href="#" onclick="Edit.showWaypointsTable();">show</a>';
   }
   
   this.showWaypointsTable = function() {
      var self = Edit;
      var numWaypoints = self.waypointMarkers.length;

      for(var i=0; i<numWaypoints; i++) {
         var waypoint = self.waypointMarkers[i];
         if(waypoint) {
            var pointLat = waypoint['waypointLat'];
            var pointLon = waypoint['waypointLon'];
            var pointEle = waypoint['waypointEle'];
            var pointName = waypoint['waypointName'];
            var pointInfo = waypoint['waypointInfo'];
            var showWaypoint = waypoint['showWaypoint'];
            self.addWaypointRow(i, pointLat,pointLon,pointEle,pointName,pointInfo,showWaypoint);
         }
      }
      
      var header = document.getElementById('hideWaypoints');
      header.innerHTML = "<a href=# onclick='Edit.hideWaypointsTable();'>hide</a>";
   }
   


   this.updateWaypoint = function(waypointId,lat,lon,ele,tags,name,info,marker) {
      var self = Edit;
      waypoint = self.waypointMarkers[waypointId];
    // alert(name+info);
      if(!marker) {
         marker = waypoint['waypointMarker'];
      }
      showWaypoint = waypoint['showWaypoint'];
      waypointDB = waypoint['waypointDB'];

      self.updateWaypointArray(waypointId,lat,lon,ele,name,info,tags,waypointDB,marker,showWaypoint);
      self.updateWaypointRow(waypointId,lat,lon,ele,name);
      self.updateWaypointMarker(waypointId,lat,lon,marker);

      editWaypointLat2 = document.getElementById('editWaypointLat');
      editWaypointLon2 = document.getElementById('editWaypointLon');
      if(editWaypointLat2) {
         editWaypointLat2.value = Math.round(lat*100000)/100000;
      }
      if(editWaypointLon2) {
         editWaypointLon2.value = Math.round(lon*100000)/100000;
      }



   }

   this.editWaypoint = function(waypointId) {
      var self = Edit;
      self.editedWaypoint = waypointId;
      waypoint = self.waypointMarkers[waypointId];
      pointLat = waypoint['waypointLat'];
      pointLon = waypoint['waypointLon'];
      pointEle = waypoint['waypointEle'];
      pointTags = waypoint['waypointTags'];
      marker = waypoint['waypointMarker'];
      pointName = waypoint['waypointName'];
      pointInfo = waypoint['waypointInfo'];

      content = document.createElement('div');
      content.width = '200px';
      content.height = '100px';
      content.display = 'block';


      nameBox = document.createElement('input');
      nameBox.type = 'text';
      nameBox.value = pointName;
      nameBox.position = 'absolute';
      nameBox.display = 'block';
      nameBox.id = "editWaypointName";

      infoBox = document.createElement('textarea');
      infoBox.width = '200';
      infoBox.height = '100';
      infoBox.value = pointInfo;
      infoBox.top= '20px';
      infoBox.left = '20px';
      infoBox.position = 'absolute';
      infoBox.display = 'block';
      infoBox.id = "editWaypointInfo";

      latBox = document.createElement('input');
      latBox.type = 'text';
      latBox.value = Math.round(pointLat*100000)/100000;
      latBox.display = 'block';
      latBox.id = "editWaypointLat";

      lonBox = document.createElement('input');
      lonBox.type = 'text';
      lonBox.value = Math.round(pointLon*100000)/100000;
      lonBox.id = "editWaypointLon";
      
      eleBox = document.createElement('input');
      eleBox.type = 'text';
      eleBox.value = pointEle;
      eleBox.id = "editWaypointEle";
      
      tagsBox = document.createElement('input');
      tagsBox.type = 'text';
      tagsBox.value = pointTags;
      tagsBox.id = "editWaypointTags";
      
      submit = document.createElement('input');
      submit.type = 'submit';
      submit.value = 'Update';
      submit.onclick = function() {
         lat = latBox.value;
         lon = lonBox.value;
         ele = eleBox.value;
         name = nameBox.value;
         info = infoBox.value;
         tags = tagsBox.value;
         self.updateWaypoint(waypointId,lat,lon,ele,tags,name,info);

         newPoint = new GLatLng(lat,lon);
         self.map.closeInfoWindow();
         self.map.panTo(newPoint);
         self.editedWaypoint = null;
         
         while(self.editTable.firstChild) {
            self.editTable.removeChild(self.editTable.firstChild);
         }
      };

      nameStr = document.createTextNode("Waypoint Name ");
      info = document.createTextNode("Waypoint Info ");
      lat = document.createTextNode("Lat ");
      lon = document.createTextNode("Lon ");
      ele = document.createTextNode("Ele ");
      tags = document.createTextNode("Tags ");
      
      /* divs */
      nameDiv = document.createElement('div');
      nameDiv.id = "nameDiv";
      nameDiv.position = 'absolute';
      nameDiv.display = 'block';
      
      infoDiv = document.createElement('div');
      infoDiv.id = "infoDiv";
      infoDiv.position = 'absolute';
      infoDiv.display = 'block';

      latDiv = document.createElement('div');
      latDiv.id = "latDiv";
      latDiv.position = 'absolute';
      latDiv.display = 'block';
      
      lonDiv = document.createElement('div');
      lonDiv.id = "lonDiv";
      lonDiv.position = 'absolute';
      lonDiv.display = 'block';
      
      eleDiv = document.createElement('div');
      eleDiv.id = "eleDiv";
      eleDiv.position = 'absolute';
      eleDiv.display = 'block';

      tagsDiv = document.createElement('div');
      tagsDiv.id = "tagsDiv";
      tagsDiv.position = 'absolute';
      tagsDiv.display = 'block';

      /* add data to divs */
      nameDiv.appendChild(nameStr);
      nameDiv.appendChild(nameBox);
      infoDiv.appendChild(info);
      infoDiv.appendChild(infoBox);
      latDiv.appendChild(lat);
      latDiv.appendChild(latBox);
      lonDiv.appendChild(lon);
      lonDiv.appendChild(lonBox);
      eleDiv.appendChild(ele);
      eleDiv.appendChild(eleBox);
      tagsDiv.appendChild(tags);
      tagsDiv.appendChild(tagsBox);

      content.appendChild(nameDiv);
      content.appendChild(infoDiv);
      content.appendChild(latDiv);
      content.appendChild(lonDiv);
      content.appendChild(eleDiv);
      content.appendChild(tagsDiv);
      content.appendChild(submit);

      text = "Please edit the waypoint below.";

      marker.openInfoWindow(text,{maxWidth:300});

      while(self.editTable.firstChild) {
         self.editTable.removeChild(self.editTable.firstChild);
      }
   //   self.editTable.innerHTML = "";

      self.editTable.appendChild(content);
   }

   this.deleteWaypoint = function(waypointId) {
      var self = Edit;

      var answer = confirm ("Are you sure that you want to delete this waypoint?");
      
      if(answer) {
         self.deleteWaypointMarker(waypointId);
         self.deleteWaypointRow(waypointId);
         self.deleteWaypointArray(waypointId);
      }
   }
   this.deleteWaypointArray = function(waypointId) {
      var self = Edit;
      self.waypointMarkers[waypointId] = null;
   }

   this.deleteWaypointMarker = function(waypointId) {
      var self = Edit;  
      
      var waypoint = self.waypointMarkers[waypointId];
      marker = waypoint['waypointMarker'];
      if(marker) {
         self.map.removeOverlay(marker);
         self.map.closeInfoWindow();
      }
   }

   this.deleteWaypointRow = function(waypointId) {
      var self = Edit;
      rowId = "waypoint" + waypointId;
      waypointRow = document.getElementById(rowId);
      rowNum = waypointRow.rowIndex;
      self.waypointTable.deleteRow(rowNum);
   }
   
   this.createPanoramioMarker = function (panId) {
      var self = Edit;
      
      pan = self.panoramioPhotos[panId];
      imageName = pan['pictureName'];

      var marker = new GMarker(point, {icon: panoramioIcon, title:imageName});

      GEvent.addListener(marker, "click", function() {
         pan = self.panoramioPhotos[panId];
         imageName = pan['pictureName'];
         imageThumbnail = pan['pictureThumbnail'];
         imageFullsize = pan['pictureFullsize'];
         pictureOwner = pan['pictureOwnerName'];
         pictureOwnerId = pan['pictureOwnerId'];
         pictureId = pan['pictureId'];

         html = "<div style='width:250px;max-height:300px;min-height:230px'><b>" + imageName + "</b><br>"+
                "<a href=\"" + imageFullsize + "\" rel=\"lightbox\" onclick=\"pop(this);return false;\">" +
                "<img src='"+imageThumbnail+"' style='border:none;'></a><br>" +
                "<a href=\"" + imageFullsize + "\" rel=\"lightbox\" onclick=\"pop(this);return false;\">Enlarge</a><br>" +
                "<a href='http://www.panoramio.com/photo/"+pictureId+"' target='_blank'>View</a> on Panoramio<br>"+
                "Photo by <a href='http://www.panoramio.com/user/"+pictureOwnerId+"' target='_blank'>"+pictureOwner+"</a></div>";
         marker.openInfoWindow(html,{maxWidth:400});
       });
       
       return marker;

   }

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

      if(type == "waypoint") {
         var waypointId = self.numWaypoints;
         waypoint = self.waypointMarkers[waypointId];
         pointName = waypoint['waypointName'];
         pointInfo = waypoint['waypointInfo'];
         pointLat = waypoint['waypointLat'];
         pointLon = waypoint['waywpointLon'];
         pointEle = waypoint['waypointEle'];
         point = new GLatLng(waypoint['waypointLat'],waypoint['waypointLon']);


         var marker = new GMarker(point, {icon: waypointIcon,title:pointName});

         GEvent.addListener(marker, "click", function() {
            waypoint = Edit.waypointMarkers[waypointId];
            pointInfo = waypoint['waypointInfo'];
            pointName = waypoint['waypointName'];
            pointLat = waypoint['waypointLat'];
            pointLon = waypoint['waypointLon'];
            pointEle = waypoint['waypointEle'];

            lat = Math.round(pointLat*100000)/100000;
            lon = Math.round(pointLon*100000)/100000;
            ele = Math.round(pointEle);
            
            units = self.unitPref("height");

            html = "<b>" + pointName + "</b><br>";
            if(pointInfo != "") html += pointInfo+"<br>";

            html += "<font size=-2>(" + lat + ", " + lon + ")";
            marker.openInfoWindow(html,{maxWidth:300});
         });

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

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

            picId = picture['id'];
          top.location.href = "view_picture.php?picture_id=" + picId;
         });
         GEvent.addListener(marker, "mouseover", function() {
            self.highlightPicture(id);

         });
         GEvent.addListener(marker, "mouseout", function() {
            self.unhighlightPicture(id);
          //  self.mapDiv.removeChild(self.currPicDiv);
         });
      }

      return marker;
   }
   this.randomTrack = function() {
      var self = Edit;

      var bounds = self.map.getBounds();
      var southWest = bounds.getSouthWest();
      var northEast = bounds.getNorthEast();
      var lngSpan = northEast.lng() - southWest.lng();
      var latSpan = northEast.lat() - southWest.lat();
      var trackTime = "5";

      var points = [];
      for (var i = 0; i < 5; i++) {
         var track = [];
         pointLat = southWest.lat() + latSpan * Math.random();
         pointLon = southWest.lng() + lngSpan * Math.random();
         point = new GLatLng(pointLat,pointLon);
         track['trackPoint'] = point;
         track['trackLat'] = pointLat;
         track['trackLon'] = pointLon;
         track['trackTime'] = trackTime;
         points.push(track);
      }
      return points;
   }

   this.addTrack = function(points,trackName,trackInfo,trackColor,trackLength,trackTags,trackDB) {
      
      var self = Edit;
      var trackId = self.numTracks;
      var trackName = trackName || "Track Name";
      var trackColor = "#FF0000";
      var trackLength = trackLength || 0;  //trackColor || "#FF0000";
      var showTrack = true;
      var startMarker;
      var endMarker;


      if(points.length > 0) {
         var startPoint = points[0]['trackPoint'];
         var endPoint = points[points.length-1]['trackPoint'];
         
         var extraText = [];
         extraText[0] = "start of track";
         extraText[1] = trackDB;
      
         var startMarker = self.createPin("track",startPoint,trackName,trackInfo,trackLength,trackStartIcon,extraText);
         extraText[0] = "end of track";
         var endMarker = self.createPin("track",endPoint,trackName,trackInfo,trackLength,trackEndIcon,extraText);
      }

      var polylines = [];
      var polyline;
      for(var i=0;i<points.length;i = i+199) {
    //    alert("dd");
         points_seg = points.slice(i,i+201);
         polyline = self.createTrack(points_seg,trackColor);
          self.map.addOverlay(polyline);
      }
      


      self.addTrackToArray(trackId,points,polyline,startMarker,endMarker,trackName,trackInfo,trackColor,trackLength,trackTags,trackDB,showTrack);
     // self.addTrackRow(trackId,trackName,trackColor,trackLength,showTrack);

      //if(polyline) {
       //  self.map.addOverlay(polyline);
     /// }
      if(startMarker) {
         self.map.addOverlay(startMarker);
      }
      if(endMarker) {
         self.map.addOverlay(endMarker);
      } 
      self.numTracks++;
      self.currPoints = null;
   }

   this.addTrackToArray = function(trackId,points,polyline,startMarker,endMarker,trackName,trackInfo,trackColor,trackLength,trackTags,trackDB,showTrack) {
      var self = Edit;
      var track = [];

      track['trackPoints'] = points;
      track['trackLine'] = polyline;
      track['startMarker'] = startMarker;
      track['endMarker'] = endMarker;
      track['trackName'] = trackName;
      track['trackInfo'] = trackInfo;
      track['trackColor'] = trackColor;
      track['trackLength'] = trackLength;
      track['trackTags'] = trackTags; 
      track['trackDB'] = trackDB;
      track['showTrack'] = showTrack;

      self.tracks[trackId] = track;
   }

   this.createTrack = function(points,trackColor,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);
      }

      if(trackPoints.length > 0) {
         var polyline = new GPolyline(trackPoints,trackColor,weight,opacity);
      } else {
         var polyline = false;
      }
      return polyline;
   }
   this.addTrackRow = function(trackId,trackName,trackColor,trackLength,showTrack) {
      var self = Edit;
      var row;

      var rowNumber = self.tracksTable.rows.length;
      var rowClass;
      /*
      if(rowNumber == 0) {
         self.addTracksHeader();
         rowNumber += 1;
      }*/
      
      if(rowNumber % 2 == 1) {
         rowClass = "row_one";
      } else {
         rowClass = "row_two";
      }

      row = self.tracksTable.insertRow(rowNumber);
      row.className = rowClass;
      row.id = "track" + trackId;
      units = self.unitPref("length");

      //self.makeDelete(row,trackId,"track");
      self.makeHidebox(row,trackId,"track",showTrack);
      //self.makeEdit(row,trackId,"track");
      self.makeZoom(row,trackId,"track",showTrack);
      self.makeCell(row.id+"Name",row,trackName,false,rowNumber,"100%");
      self.makeCell(row.id+"Length",row,trackLength + " " + units,false,rowNumber,"100%");
   }

   this.addTracksHeader = function() {
      var self = Edit;
      var row = self.tracksTable.insertRow(0);
      var header = row.insertCell(0);
      header.align = "left";
      header.colSpan = 4;
      header.id = "tracksHeader";
      header.innerHTML = "Tracks <A href=# onclick='Edit.hideTracksTable();'>hide</a>";

      /*
      var row = self.tracksTable.insertRow(1);
      self.makeCell("trackName",row,"Name",false,0);
      self.makeCell("trackColor",row,"Color",false,0);
      self.makeCell("trackDelete",row,"Delete",false,0);     
      */
   }
   this.hideTrack = function(trackId,showHide) {
      var self = Edit;
      track = self.tracks[trackId];
      trackLine = track['trackLine'];
      startMarker = track['startMarker'];
      endMarker = track['endMarker'];

      hidebox = document.getElementById("trackHidebox" + trackId);
      showTrack = hidebox.checked;

      if(showHide == "show") {
         showTrack = true;
      } else if(showHide == "hide") {
         showTrack = false;
      } else {
         showTrack = hidebox.checked;
      }

      if(showTrack) {
         if(trackLine) {
            self.map.addOverlay(trackLine);
         }
         if(startMarker) {
            self.map.addOverlay(startMarker);
         }
         if(endMarker) {
            self.map.addOverlay(endMarker);
         }
         hidebox.checked = true;
         self.rowActive(true,"track",trackId);
      } else {
         if(trackLine) {
            self.map.removeOverlay(trackLine);
         }
         if(startMarker) {
            self.map.removeOverlay(startMarker);
         }
         if(endMarker) {
            self.map.removeOverlay(endMarker);
         }
         self.map.closeInfoWindow();
         hidebox.checked = false;
         self.rowActive(false,"track",trackId);
      }
      track['showTrack'] = showTrack;
      self.tracks[trackId] = track;
   }
   this.hideTracksTable = function() {
      var self = Edit;
      var numTracks = self.tracksTable.rows.length;

      for(var i=0; i<numTracks; i++) {
         self.tracksTable.deleteRow(0);
      }
      var header = document.getElementById('hideTracks');
      header.innerHTML = '<a href="#" onclick="Edit.showTracksTable();">show</a>';
   }

   this.showTracksTable = function() {
      var self = Edit;
      var numTracks = self.tracks.length;

      for(var i=0; i<numTracks; i++) {
         var track = self.tracks[i];
         if(track) {
            var trackName = track['trackName'];
            var trackColor = track['trackColor'];
            var trackLength = track['trackLength'];
            var showTrack = track['showTrack'];
            self.addTrackRow(i, trackName,trackColor,trackLength,showTrack);
         }
      }

      
      var header = document.getElementById('hideTracks');
      header.innerHTML = "<a href=# onclick='Edit.hideTracksTable();'>hide</a>";
   }
   
   this.updateTrack = function(trackId,trackName,trackInfo,trackTags,trackActivityId,trackSurfaceId) {
      var self = Edit;
      track = self.tracks[trackId];
      track['trackName'] = trackName;
      track['trackInfo'] = trackInfo;
      track['trackTags'] = trackTags;
      track['trackActivityId'] = trackActivityId;
      track['trackSurfaceId'] = trackSurfaceId;
   }

   this.editTrack = function(trackId) {
      var self = Edit;
      self.editedTrack = trackId;
      track = self.tracks[trackId];

      //marker = track['waypointMarker'];
      trackName = track['trackName'];
      trackInfo = track['trackInfo'];
      trackActivityId = track['trackActivityId'];
      trackSurfaceId = track['trackSurfaceId'];
      trackSurface = track['trackSurface'];
      trackTags = track['trackTags'];

      content = document.createElement('div');
      content.width = '200px';
      content.height = '100px';
      content.display = 'block';


      nameBox = document.createElement('input');
      nameBox.type = 'text';
      nameBox.value = trackName;
      nameBox.position = 'absolute';
      nameBox.display = 'block';
      nameBox.id = "editTrackName";

      infoBox = document.createElement('textarea');
      infoBox.width = '200';
      infoBox.height = '100';
      infoBox.value = trackInfo;
      infoBox.top= '20px';
      infoBox.left = '20px';
      infoBox.position = 'absolute';
      infoBox.display = 'block';
      infoBox.id = "editTrackInfo";
      
      tagBox = document.createElement('input');
      tagBox.type = 'text';
      tagBox.value = trackTags;
      tagBox.position = 'absolute';
      tagBox.display = 'block';
      tagBox.id = "editTrackTags";
      
      /*
      activitiesBox = document.createElement('input');
      activitiesBox.type = 'text';
      activitiesBox.value = "";
      activitiesBox.position = 'absolute';
      activitiesBox.display = 'block';
      activitiesBox.id = "editTrackActivities";
      */
      
      activitySelectDiv = document.createElement('div');
      activityDropdown = document.createElement("select");  
      activityDropdown.id = "activitesDropdown";

      //alert(self.activities.length);
      for(var i=0; i<self.activities.length; i++) {
         activity = self.activities[i];

         option = document.createElement('option');
         option.value = activity['activityId'];
         option.text = activity['activityName'];

         if(trackActivityId == activity['activityId']) {
            option.selected = true;
         }

         try {
            activityDropdown.add(option, null); // standards compliant; doesn't work in IE
         } catch(ex) {
            activityDropdown.add(option); // IE only
         }
      }
      

      surfaceSelectDiv = document.createElement('div');
      surfaceDropdown = document.createElement("select");
      surfaceDropdown.id = "surfacesDropdown";

      for(var i=0; i<self.surfaces.length; i++) {
         surface = self.surfaces[i];

         option = document.createElement('option');
         option.value = surface['surfaceId'];
         option.text = surface['surfaceName'];

         if(trackSurfaceId == surface['surfaceId']) {
            option.selected = true;
         }

         try {
            surfaceDropdown.add(option, null); // standards compliant; doesn't work in IE
         } catch(ex) {
            surfaceDropdown.add(option); // IE only
         }
      }

      submit = document.createElement('input');
      submit.type = 'submit';
      submit.value = 'Update';
      submit.onclick = function() {
         trackName = nameBox.value;
         trackInfo = infoBox.value;
         trackTags = tagBox.value;
         activityOption = activityDropdown[activityDropdown.selectedIndex];
         surfaceOption = surfaceDropdown[surfaceDropdown.selectedIndex];

         trackActivityId = activityOption.value;
         trackSurfaceId = surfaceOption.value;
         

         self.updateTrack(trackId,trackName,trackInfo,trackTags,trackActivityId,trackSurfaceId);

         newPoint = new GLatLng(lat,lon);
         self.map.closeInfoWindow();
         //self.map.panTo(newPoint);
         self.editedWaypoint = null;
         
         while(self.editTable.firstChild) {
            self.editTable.removeChild(self.editTable.firstChild);
         }
      };

      nameStr = document.createTextNode("Track Name ");
      info = document.createTextNode("Track Info ");
      tagsStr = document.createTextNode("Tags ");
      activities = document.createTextNode("Activities ");
      surfaces = document.createTextNode("Surfaces ");

      content.appendChild(nameStr);
      content.appendChild(nameBox);
      content.appendChild(info);
      content.appendChild(infoBox);
      content.appendChild(tagsStr);
      content.appendChild(tagBox);
      content.appendChild(activities);
      content.appendChild(activityDropdown);
      content.appendChild(surfaces);
      content.appendChild(surfaceDropdown);
      content.appendChild(submit);

      text = "Please edit the track below.";

      //marker.openInfoWindow(text,{maxWidth:300});

      while(self.editTable.firstChild) {
         self.editTable.removeChild(self.editTable.firstChild);
      }
   //   self.editTable.innerHTML = "";

      self.editTable.appendChild(content);

   }
   
   this.deleteTrack = function(trackId) {
      var self = Edit;
      
      var answer = confirm ("Are you sure that you want to delete this track?");
      
      if(answer) {
         self.deleteTrackOnMap(trackId);
         self.deleteTrackRow(trackId);
         self.deleteTrackArray(trackId);
      }
   }
   this.deleteTrackArray = function(trackId) {
      var self = Edit;
      self.tracks[trackId] = null;
   }

   this.deleteTrackOnMap = function(trackId) {
      var self = Edit;  

      var track = self.tracks[trackId];
      polyline = track['trackLine'];
      if(polyline) {
         self.map.removeOverlay(polyline);
         self.map.closeInfoWindow();
      }
   }

   this.deleteTrackRow = function(trackId) {
      var self = Edit;
      rowId = "track" + trackId;
      trackRow = document.getElementById(rowId);
      rowNum = trackRow.rowIndex;
      self.tracksTable.deleteRow(rowNum);
   }
   this.uploadPicture = function(picture) {
      var self = Edit;
      start = new Date();
      start = start.getTime();
     // postData = formData2QueryString(self.form);
      //self.ajax.doPost('upload_picture.php?start=' + start, postData, this.uploadPictureResponse);
      self.ajax.doGet('upload_picture.php?start=' + start + "&picture=" + picture, this.uploadPictureResponse);

   }
   this.uploadPictureResponse = function(str) {
      var self = Edit; 
      
      var pictureData = str.split(",");
      pictureImage = pictureData[0];
      pictureTime = pictureData[1];;

      for(var i=0; i<self.tracks.length; i++) {
         track = self.tracks[i];
         if(track) {
            point = self.getTimeGPS(pictureTime,0);
         }
      }
      if(!point) {
         point = self.map.getCenter();
      }

      pictureName = "Picture Name";
      pictureInfo = "Picture Info";
      pictureLat = point.lat();
      pictureLon = point.lng();

      self.addPicture(pictureName,pictureInfo,pictureImage,pictureLat,pictureLon,pictureTime);
   }

   this.uploadPictureBox = function() {
      var self = Edit;
      var pictureDiv = null;
      
      var rowNumber = self.pictureTable.rows.length;
      if(rowNumber == 0) {
         self.addPictureHeader();
         rowNumber += 2;
      }
         
      /* create picture div */
      var pictureDiv = document.createElement('div');
      pictureDiv.className = "pictureDiv";
      
      /* Style */
      pictureDiv.style.color = "#CCCCCC";
      pictureDiv.style.border = "1px solid #DDDDDD";
      pictureDiv.style.background = "#CCCCCC";
      pictureDiv.style.width = "400px";
      pictureDiv.style.height = "50px";
      
      pictureDiv.innerHTML = "<input type=file id=\"picture\" name=\"picture\">";
      var submitButton = document.createElement('input');
      submitButton.type = "submit";
      submitButton.value = "Upload";
      submitButton.onclick = function() {
         alert("Upload not coded yet");
         picture = document.getElementById('picture');
         //alert(picture);
         self.uploadPicture(picture.value);
         self.pictureTable.removeChild(pictureDiv);
      }
      pictureDiv.appendChild(submitButton);

      self.pictureTable.appendChild(pictureDiv);
      
   }
   this.addPictureUpload = function() {
      self.uploadPictureBox();
   }
        /*
   this.addPicture = function(pictureName,pictureInfo,pictureThumbnail,pictureFullsize,pictureLat,pictureLon,pictureEle,pictureTime,editPicture) {
      var self = Edit;

      pictureId = self.numPictures;
      editPicture = editPicture || "true";
      // Fake Info

      iconImage = "image";
      showPicture = true;
      
      if(!pictureLat) { pictureLat = 0; }
      if(!pictureLon) { pictureLon = 0; }
      
      //pictureLat = parseInt(pictureLat);
      //pictureLon = parseInt(pictureLon);
      //pictureEle = parseInt(pictureEle);
      //alert(pictureLon+"--"+pictureLat);

      point = new GLatLng(pictureLat,pictureLon);

      marker = self.createPin("picture", point, pictureName, pictureInfo,pictureThumbnail,iconImage);

      self.addPictureToArray(pictureId,marker,pictureLat,pictureLon,pictureEle,pictureName,pictureInfo,pictureThumbnail,pictureFullsize,showPicture);
   //   self.addPictureRow(pictureId,pictureName,pictureInfo,pictureThumbnail,showPicture);
      self.map.addOverlay(marker);
      self.numPictures++;
      if(editPicture == "true") {
         self.editPicture(pictureId);
      }
   }      */
   
   this.addPicture = function(lat,lon,name,desc,thumb,full,server,serverLink,picWidth,picHeight,picId) {
      var self = Edit;
      var picture = [];
      pictureId = self.numPictures;


      picture['name'] = name;
      picture['desc'] = desc;
      picture['lat'] = lat;
      picture['lon'] = lon;
      picture['thumb'] = thumb;
      picture['full'] = full;
      picture['marker'] = null;
      picture['server'] = server;
      picture['serverLink'] = serverLink;
      picture['width'] = picWidth;
      picture['height'] = picHeight;
      picture['id'] = picId;
      self.pictures[pictureId] = picture;

      var marker = self.createPin("picture", pictureId);
      self.map.addOverlay(marker);

      picture['marker'] = marker;
      self.pictures[pictureId] = picture;

     // self.addPictureRow(pictureId);
      self.numPictures++;
   }
   

   this.addPictureToArray = function(pictureId,pictureMarker,pictureLat,pictureLon,pictureEle,pictureName,pictureInfo,pictureThumbnail,pictureFullsize,showPicture) {
      var self = Edit;
      var picture = [];
      picture['pictureMarker'] = pictureMarker;
      picture['pictureLat'] = pictureLat;
      picture['pictureLon'] = pictureLon;
      picture['pictureEle'] = pictureEle;
      picture['pictureName'] = pictureName;
      picture['pictureInfo'] = pictureInfo;
      picture['pictureThumbnail'] = pictureThumbnail;
      picture['pictureFullsize'] = pictureFullsize;
      picture['showPicture'] = showPicture;
      
      

      self.pictures[pictureId] = picture;
   }

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

      var row = self.pictureTable.insertRow(0);



      header = row.insertCell(0);
      header.align = "left";
      header.colSpan = 6;
      header.id = "picturesHeader";
      header.innerHTML = "Pictures <a href=# onclick='Edit.hidePicturesTable();'>hide</a>";

      /*
      var row = self.pictureTable.insertRow(1);
      self.makeCell("pictureImage",row,"Picture",false,0);
      self.makeCell("pictureLat",row,"Lat",false,0);
      self.makeCell("pictureLon",row,"Lon",false,0);
      self.makeCell("pictureName",row,"Name",false,0);
      self.makeCell("pictureInfo",row,"Info",false,0);
      self.makeCell("pictureDelete",row,"Delete",false,0);
      */
   }
                                 
   this.addPictureRow = function(pictureId,pictureName,pictureInfo,pictureThumbnail,showPicture) {
      var self = Edit;
      var row;
      var rowNumber = self.pictureTable.rows.length;
      var rowClass;
      /*
      if(rowNumber == 0) {
         self.addPictureHeader();
         rowNumber += 1;
      }
      */
      if(rowNumber % 2 == 1) {
         rowClass = "row_one";
      } else {
         rowClass = "row_two";
      }

      row = self.pictureTable.insertRow(rowNumber);
      row.className = rowClass;
      row.id = "picture" + pictureId;

      //self.makeDelete(row,pictureId,"picture");
      self.makeHidebox(row,pictureId,"picture",showPicture);
      //self.makeEdit(row,pictureId,"picture");
      self.makeZoom(row,pictureId,"picture",showPicture);
      self.makeCell(row.id+"Name",row,pictureName,false,rowNumber,"50%");

      lbText = "<img src='"+pictureThumbnail+"' width='50' class='lbOn' onClick=\"Edit.zoomPicture('"+pictureId+"');\">";
      self.makeCell(row.id+"Image",row,lbText,false,rowNumber,"50%");
   }
   this.hidePicture = function(pictureId,showHide) {
      var self = Edit;
      picture = self.pictures[pictureId];

      hidebox = document.getElementById("pictureHidebox" + pictureId);

      if(showHide == "show") {
         showPicture = true;
      } else if(showHide == "hide") {
         showPicture = false;
      } else {
         showPicture = hidebox.checked;
      }
      pictureMarker = picture['pictureMarker'];

      if(showPicture) {
         self.map.addOverlay(pictureMarker);
         hidebox.checked = true;
         self.rowActive(true,"picture",pictureId);
      } else {
         self.map.removeOverlay(pictureMarker);
         self.map.closeInfoWindow();
         hidebox.checked = false;
         self.rowActive(false,"picture",pictureId);
      }
      picture['showPicture'] = showPicture;
      self.pictures[pictureId] = picture;

   }

   this.hidePicturesTable = function() {
      var self = Edit;
      var numPictures = self.pictureTable.rows.length;
                                                                    
      for(var i=0; i<numPictures; i++) {
         self.pictureTable.deleteRow(0);
      }
      
      var header = document.getElementById('hidePictures');
      header.innerHTML = "<a href=# onclick='Edit.showPicturesTable();'>show</a>";
   }
   
   this.showPicturesTable = function() {
      var self = Edit;                                      
      var numPictures = self.pictures.length;

      for(var i=0; i<numPictures; i++) {
         var picture = self.pictures[i];
         if(picture) {
            var pictureName = picture['pictureName'];
            var pictureInfo = picture['PictureInfo'];
            var pictureThumbnail = picture['pictureThumbnail'];
            var pictureFullsize = picture['pictureFullsize'];
            var showWaypoint = picture['showPicture'];

            self.addPictureRow(i, pictureName,pictureInfo,pictureThumbnail,pictureFullsize,showWaypoint);
         }
      }
      
      var header = document.getElementById('hidePictures');
      header.innerHTML = "<a href=# onclick='Edit.hidePicturesTable();'>hide</a>";
   }
   
   this.updatePictureRow = function(pictureId,pointLat,pointLon,pointName) {
      var self = Edit;
      rowId = "picture" + pictureId;
      cellNameId = rowId + "Name";
      cellNameId = document.getElementById(cellNameId);
      cellNameId.innerHTML = pointName;

      /*
      pointLatRound = Math.round(pointLat*100000)/100000;
      pointLonRound = Math.round(pointLon*100000)/100000;

      cellLatId = rowId + "Lat";
      cellLatId = document.getElementById(cellLatId);
      cellLatId.innerHTML = pointLatRound;

      cellLonId = rowId + "Lon";
      cellLonId = document.getElementById(cellLonId);
      cellLonId.innerHTML = pointLonRound;
      */
   }

   this.updatePictureArray = function(pictureId,pointLat,pointLon,pointName,pointInfo,pointMarker,showPicture) {
      var self = Edit;
      var picture = [];

      picture['pictureLat'] = pointLat;
      picture['pictureLon'] = pointLon;
      picture['pictureName'] = pointName;
      picture['pictureInfo'] = pointInfo;
      picture['pictureMarker'] = pointMarker;
      picture['showPicture'] = showPicture;

      self.pictures[pictureId] = picture;
   }

   this.updatePictureMarker = function(pictureId,pointLat,pointLon,marker) {
      newPoint = new GLatLng(pointLat,pointLon);
      marker.setPoint(newPoint);
   }
   
   this.updatePicture = function(pictureId,lat,lon,name,info,marker) {
      var self = Edit;
      picture = self.pictures[pictureId];
    // alert(name+info);
      if(!marker) {
         marker = picture['pictureMarker'];
      }
      showPicture = picture['showPicture'];

      self.updatePictureArray(pictureId,lat,lon,name,info,marker,showPicture);
      self.updatePictureRow(pictureId,lat,lon,name);
      self.updatePictureMarker(pictureId,lat,lon,marker);
   }

   this.editPicture = function(pictureId) {
      var self = Edit;
      //self.editedWaypoint = waypointId;
      picture = self.pictures[pictureId];
      pointLat = picture['pictureLat'];
      pointLon = picture['pictureLon'];
      marker = picture['pictureMarker'];
      pointName = picture['pictureName'];
      pointInfo = picture['pictureInfo'];

      content = document.createElement('div');
      content.width = '200px';

      nameBox = document.createElement('input');
      nameBox.type = 'text';
      nameBox.value = pointName;

      infoBox = document.createElement('textarea');

      infoBox.width = '200';
      infoBox.height = '100';
      infoBox.value = pointInfo;
      infoBox.top= '20px';
      infoBox.left = '20px';
      infoBox.position = 'absolute';

      latBox = document.createElement('input');
      latBox.type = 'text';
      latBox.value = Math.round(pointLat*100000)/100000;

      lonBox = document.createElement('input');
      lonBox.type = 'text';
      lonBox.value = Math.round(pointLon*100000)/100000;

      submit = document.createElement('input');
      submit.type = 'submit';
      submit.value = 'Update';
      submit.onclick = function() {
         lat = latBox.value;
         lon = lonBox.value;
         name = nameBox.value;
         info = infoBox.value;
         self.updatePicture(pictureId,lat,lon,name,info);

         newPoint = new GLatLng(lat,lon);
         self.map.closeInfoWindow();
         self.map.panTo(newPoint);
        // self.editedWaypoint = null;

      };

      name = document.createTextNode("Picture Name ");
      info = document.createTextNode("Picture Info ");
      lat = document.createTextNode("Lat ");
      lon = document.createTextNode("Lon ");

      content.appendChild(name);
      content.appendChild(nameBox);
      content.appendChild(info);
      content.appendChild(infoBox);
      content.appendChild(lat);
      content.appendChild(latBox);
      content.appendChild(lon);
      content.appendChild(lonBox);
      content.appendChild(submit);

      marker.openInfoWindow(content,{maxWidth:300});




   }


   this.deletePicture = function(pictureId) {
      var self = Edit;

      var answer = confirm ("Are you sure that you want to delete this picture?");
      
      if(answer) {
         self.deletePictureOnMap(pictureId);
         self.deletePictureRow(pictureId);
         self.deletePictureArray(pictureId);
      }
   }
   this.deletePictureArray = function(pictureId) {
      var self = Edit;
      self.pictures[pictureId] = null;
   }

   this.deletePictureOnMap = function(pictureId) {
      var self = Edit;

      var picture = self.pictures[pictureId];
      marker = picture['pictureMarker'];
      if(marker) {
         self.map.removeOverlay(marker);
         self.map.closeInfoWindow();
      }
   }

   this.deletePictureRow = function(pictureId) {
      var self = Edit;
      rowId = "picture" + pictureId;
      trackRow = document.getElementById(rowId);
      rowNum = trackRow.rowIndex;
      self.pictureTable.deleteRow(rowNum);
   }

   this.locationFromPictureTime = function(pictureTime,tracks) {
      var self = Edit;
      var point;
      for(var i = 0; i < tracks.length; i++) {
         track = tracks[i];
         trackPoint = track['trackPoint'];
         trackTime = trackPoint['trackTime'];

         
      }
      return point;
   }

   this.addNoteHeader = function() {
      var self = Edit;
      row = self.noteTable.insertRow(0);
      header = row.insertCell(0);
      header.align = "left";
      header.colSpan = 4;
      header.id = "notesHeader";
      header.innerHTML = "Notes <a href=# onclick='Edit.hideNotesTable();'>hide</a>";
   }
   
   this.addNoteRow = function(noteId,noteName,showNote) {
      var self = Edit;
      var row;
      var rowNumber = self.noteTable.rows.length;
      var numNotes = self.numNotes;
      var rowClass;
      /*
      if(rowNumber == 0) {
         self.addNoteHeader();
         rowNumber += 1;
      }
      */
      if(rowNumber % 2 == 1) {
         rowClass = "row_one";
      } else {
         rowClass = "row_two";
      }

      row = self.noteTable.insertRow(rowNumber);
      row.className = rowClass;
      row.id = "note" + noteId;

      //self.makeDelete(row,noteId,"note");
      self.makeHidebox(row,noteId,"note",showNote);
      //self.makeEdit(row,noteId,"note");
      self.makeZoom(row,noteId,"note",showNote);
      self.makeCell(row.id+"Name",row,noteName,false,rowNumber,"100%");  
   }

   this.addNoteToArray = function(noteId, pointLat, pointLon, pointEle,noteName, noteInfo,noteMarker,showNote) {
      var self = Edit;
      var note = [];
      
      note['noteName'] = noteName;
      note['noteInfo'] = noteInfo;
      note['noteLat'] = pointLat;
      note['noteLon'] = pointLon;
      note['noteEle'] = pointEle;
      note['noteMarker'] = noteMarker;
      note['showNote'] = showNote;
      self.notes[noteId] = note;
   }

   this.addNote = function(pointLat, pointLon, pointEle,noteName,noteInfo,editNote) {
      var self = Edit;
      var point;

      var image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
      noteInfo = noteInfo || "Note Description";
      noteName = noteName || "Note Name";
      showNote = true;
      editNote = editNote || "true";

      if(pointLon && pointLat) {
         point = new GLatLng(pointLat,pointLon);
      } else {
         point = self.map.getCenter();
         pointLat = point.lat();
         pointLon = point.lng();
      }
      noteId = self.numNotes;

      var marker = self.createPin("note", point, noteName, noteInfo,"",image);

    //  self.addNoteRow(noteId,noteName,showNote);
      self.addNoteToArray(noteId,pointLat, pointLon, pointEle,noteName, noteInfo,marker,showNote);    
      self.map.addOverlay(marker);
      self.numNotes++
      
      if(editNote == "true") {
         self.editNote(noteId);
      }
   }

   this.hideNote = function(noteId,showHide) {
      var self = Edit;
      note = self.notes[noteId];
      noteMarker = note['noteMarker'];

      hidebox = document.getElementById("noteHidebox" + noteId);

      if(showHide == "show") {
         showNote = true;
      } else if(showHide == "hide") {
         showNote = false;
      } else {
         showNote = hidebox.checked;
      }

      if(showNote) {
         self.map.addOverlay(noteMarker);
         hidebox.checked = true;
         self.rowActive(true,"note",noteId);
      } else {
         self.map.removeOverlay(noteMarker);
         self.map.closeInfoWindow();
         hidebox.checked = false;
         self.rowActive(false,"note",noteId);
      }
      note['showNote'] = showNote;
      self.notes[noteId] = note;
   }
   
   this.hideNotesTable = function() {
      var self = Edit;
      var numNotes = self.noteTable.rows.length;

      for(var i=0; i<numNotes; i++) {
         self.noteTable.deleteRow(0);
      }
      var header = document.getElementById('hideNotes');
      header.innerHTML = '<a href="#" onclick="Edit.showNotesTable();">show</a>';
   }
   
   this.showNotesTable = function() {
      var self = Edit;
      var numNotes = self.notes.length;

      for(var i=0; i<numNotes; i++) {
         var note = self.notes[i];
         if(note) {
            var noteName = note['noteName'];
            var noteInfo = note['noteInfo'];
            var showNote = note['showNote'];

            self.addNoteRow(i, noteName,showNote);
         }
      }

      var header = document.getElementById('hideNotes');
      header.innerHTML = "<a href=# onclick='Edit.hideNotesTable();'>hide</a>";
   }
   
   this.updateNoteRow = function(noteId,pointLat,pointLon,pointName) {
      var self = Edit;
      rowId = "note" + noteId;
      cellNameId = rowId + "Name";
      cellNameId = document.getElementById(cellNameId);
      cellNameId.innerHTML = pointName;
      /*
      cellLatId = rowId + "Lat";
      cellLatId = document.getElementById(cellLatId);
      cellLatId.innerHTML = pointLat;

      cellLonId = rowId + "Lon";
      cellLonId = document.getElementById(cellLonId);
      cellLonId.innerHTML = pointLon;
      */
   }

   this.updateNoteArray = function(noteId,pointLat,pointLon,pointName,pointInfo,pointMarker,showNote) {
      var self = Edit;
      var note = [];

      note['noteLat'] = pointLat;
      note['noteLon'] = pointLon;
      note['noteName'] = pointName;
      note['noteInfo'] = pointInfo;
      note['noteMarker'] = pointMarker;
      note['showNote'] = showNote;

      self.notes[noteId] = note;
   }

   this.updateNoteMarker = function(noteId,pointLat,pointLon,marker) {
      newPoint = new GLatLng(pointLat,pointLon);
      marker.setPoint(newPoint);
   }
   this.updateNote = function(noteId,lat,lon,name,info,marker) {
      var self = Edit;
      note = self.notes[noteId];
      if(!marker) {
         marker = note['noteMarker'];
      }
      showNote = note['showNote'];


      self.updateNoteArray(noteId,lat,lon,name,info,marker,showNote);
      self.updateNoteRow(noteId,lat,lon,name);
      self.updateNoteMarker(noteId,lat,lon,marker);
   }

   this.editNote = function(noteId) {
      var self = Edit;
      note = self.notes[noteId];
      pointLat = note['noteLat'];
      pointLon = note['noteLon'];
      marker = note['noteMarker'];
      pointName = note['noteName'];
      pointInfo = note['noteInfo'];

      content = document.createElement('div');
      content.width = '200px';

      nameBox = document.createElement('input');

      nameBox.type = 'text';
      nameBox.value = pointName;
      nameBox.display = 'block';

      infoBox = document.createElement('textarea');
      infoBox.width = '200';
      infoBox.height = '100';
      infoBox.value = pointInfo;
      infoBox.top= '20px';
      infoBox.left = '20px';
      infoBox.position = 'absolute';
infoBox.display = 'block';



      latBox = document.createElement('input');
      latBox.type = 'text';
      latBox.value = Math.round(pointLat*100000)/100000;
      latBox.display = 'block';
      lonBox = document.createElement('input');
      lonBox.type = 'text';
      lonBox.value = Math.round(pointLon*100000)/100000;
lonBox.display = 'block';
      
      submit = document.createElement('input');
      submit.type = 'submit';
      submit.value = 'Update';
      submit.onclick = function() {
         lat = latBox.value;
         lon = lonBox.value;
         name = nameBox.value;
         info = infoBox.value;
         self.updateNote(noteId,lat,lon,name,info);
         
         newPoint = new GLatLng(lat,lon);
         self.map.closeInfoWindow();
         self.map.panTo(newPoint);

         while(self.editTable.firstChild) {
            self.editTable.removeChild(self.editTable.firstChild);
         }
      };

      nameStr = document.createTextNode("Note Name ");
      info = document.createTextNode("Note Info ");
      lat = document.createTextNode("Lat ");
      lon = document.createTextNode("Lon ");

      content.appendChild(nameStr);
      content.appendChild(nameBox);
      content.appendChild(info);
      content.appendChild(infoBox);
      content.appendChild(lat);
      content.appendChild(latBox);
      content.appendChild(lon);
      content.appendChild(lonBox);
      content.appendChild(submit);

      text = "Please edit the note below.";

      marker.openInfoWindow(text,{maxWidth:300});

      while(self.editTable.firstChild) {
         self.editTable.removeChild(self.editTable.firstChild);
      }
   //   self.editTable.innerHTML = "";

      self.editTable.appendChild(content);


   }

   this.deleteNote = function(noteId) {
      var self = Edit;
      
      var answer = confirm ("Are you sure that you want to delete this note?");
      
      if(answer) {
         self.deleteNoteMarker(noteId);
         self.deleteNoteRow(noteId);
         self.deleteNoteArray(noteId);
      }
   }
   this.deleteNoteArray = function(noteId) {
      var self = Edit;
      self.notes[noteId] = null;
   }

   this.deleteNoteMarker = function(noteId) {
      var self = Edit;  
      
      var note = self.notes[noteId];
      marker = note['noteMarker'];
      if(marker) {
         self.map.removeOverlay(marker);
         self.map.closeInfoWindow();
      }
   }

   this.deleteNoteRow = function(noteId) {
      var self = Edit;
      rowId = "note" + noteId;
      noteRow = document.getElementById(rowId);
      rowNum = noteRow.rowIndex;
      self.noteTable.deleteRow(rowNum);
   }

   this.draw = function() {
      var self = Edit;
      self.newPoints = [];
      
      listener2 =  GEvent.addListener(self.map,"mousemove", function() {
          var track = [];
           track['trackPoint'] = point; 
           self.newPoints.push(track);
        });
   }

   this.drawTrack = function() {
      var self = Edit;
      //self.map.disableDragging();
     // self.map.drag = function() { alert ("s"); };
     var moves = 0;

     var newLine = null;

        listener2 =  GEvent.addListener(self.map,"dragstart", function() {
           self.map.disableDragging();
           self.draw();
        });

     remove = GEvent.addListener(self.map,"dragend", function() {
      //  dragging = false;
        GEvent.removeListener(listener2);
      //  GEvent.removeListener(listener1);
        //alert(newPoints.length);
        //self.addTrack(newPoints);
        self.map.enableDragging();
        newPoints = null;
        GEvent.removeListener(remove);
        

      });
   }
   this.getData = function() {
      var self = Edit;

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

      var bounds = new GLatLngBounds();
      


      /* add waypoints */
         for(var i = 0; i<self.waypointMarkers.length; i++) {
            waypoint = self.waypointMarkers[i];
            if(waypoint) {
               showWaypoint = waypoint['showWaypoint'];
               if(showWaypoint) {
                  lat = waypoint['waypointLat'];
                  lon = waypoint['waypointLon'];
                  point = new GLatLng(lat,lon);
                  bounds.extend(point);
               }
            }
         }

         /* add pictures */

         for(var i = 0; i<self.pictures.length; i++) {
            picture = self.pictures[i];
            if(picture) {
               lat = picture['lat'];
               lon = picture['lon'];
               point = new GLatLng(lat,lon);
               bounds.extend(point);
            }
         }
         /* add tracks */
         
         for(var i = 0; i<self.tracks.length; i++) {
            var track = self.tracks[i];
            if(track) {
               var trackPoints = track['trackPoints'];


                  for(var j = 0; j<trackPoints.length; j++) {
                     var trackPoint = trackPoints[j];
                     var point = trackPoint['trackPoint'];
                     bounds.extend(point);
                  }

            }
         }


      var zoom = self.map.getBoundsZoomLevel(bounds);
     // zoom--;

      if(zoom > 17) { zoom = 17; }
      var center = bounds.getCenter();
      self.map.setCenter(center,zoom);
   }
   
   this.getTripBounds = function() {
      var self = Edit;

      var bounds = new GLatLngBounds();

      /* add waypoints */
         for(var i = 0; i<self.waypointMarkers.length; i++) {
            waypoint = self.waypointMarkers[i];
            if(waypoint) {
               showWaypoint = waypoint['showWaypoint'];
               if(showWaypoint) {
                  lat = waypoint['waypointLat'];
                  lon = waypoint['waypointLon'];
                  point = new GLatLng(lat,lon);
                  bounds.extend(point);
               }
            }
         }
         
         /* add notes */
         for(var i = 0; i<self.notes.length; i++) {
            note = self.notes[i];
            if(note) {
               showNote = note['showNote'];
               if(showNote) {
                  lat = note['noteLat'];
                  lon = note['noteLon'];
                  point = new GLatLng(lat,lon);
                  bounds.extend(point);
               }
            }
         }
         
         /* add pictures */
         for(var i = 0; i<self.pictures.length; i++) {
            picture = self.pictures[i];
            if(picture) {
               showPicture = picture['showPicture'];
               if(showPicture) {
                  lat = picture['pictureLat'];
                  lon = picture['pictureLon'];
                  point = new GLatLng(lat,lon);
                  bounds.extend(point);
               }
            }
         }
         /* add tracks */
         
         for(var i = 0; i<self.tracks.length; i++) {
            track = self.tracks[i];
            if(track) {
               trackPoints = track['trackPoints'];
               showTrack = track['showTrack'];
               if(showTrack) {
                  for(var j = 0; j<trackPoints.length; j++) {
                     trackPoint = trackPoints[j];
                     point = trackPoint['trackPoint'];
                     bounds.extend(point);
                  }
               }
            }
         }


      return bounds;
   }
   
   this.zoomWaypoint = function(waypointId) {
      var self = Edit;
      points = [];
      waypoint = self.waypointMarkers[waypointId];
      marker = waypoint['waypointMarker'];
      point = marker.getPoint();
      points.push(point);
      
      self.zoomFit(points);
      
      /* open info window */
      pointInfo = waypoint['waypointInfo'];
      pointName = waypoint['waypointName'];
      pointLat = waypoint['waypointLat'];
      pointLon = waypoint['waypointLon'];
      pointEle = waypoint['waypointEle'];

      lat = Math.round(pointLat*100000)/100000;
      lon = Math.round(pointLon*100000)/100000;
      ele = Math.round(pointEle*100000)/100000;
      
      units = self.unitPref("height");

     html = "<b>" + pointName + "</b><br>" + pointInfo + "<br>" +
                   "<font size=-2>lat/lon/ele: " + lat + " / " + lon + " / " + ele + " " + units +

                   "<br>[<a href=# onclick=\"Edit.hideWaypoint("+waypointId+",'hide');\">Hide</a>]</font>";
									 
     
     marker.openInfoWindow(html);
   }
   
   this.zoomTrack = function(trackId) {
      var self = Edit;
      points = [];

      track = self.tracks[trackId];
      trackPoints = track['trackPoints'];

      for(var i = 0; i<trackPoints.length; i++) {
         trackPoint = trackPoints[i];
         point = trackPoint['trackPoint'];
         points.push(point);
      }

      self.zoomFit(points);

      /* open info window */
   }
   this.zoomPicture = function(pictureId,doZoom) {
      var self = Edit;
      points = [];
      picture = self.pictures[pictureId];
      marker = picture['pictureMarker'];
      thumbnailUrl = picture['pictureThumbnail'];
      fullsizeUrl = picture['pictureFullsize'];
      point = marker.getPoint();
      points.push(point);
      
      if(doZoom) {
        self.zoomFit(points);
      }  
      
      /* open info window */
      pictureInfo = picture['pictureInfo'];
      pictureName = picture['pictureName'];
      pointLat = picture['pictureLat'];
      pointLon = picture['pictureLon'];
      pointEle = picture['pictureEle'];

      lat = Math.round(pointLat*100000)/100000;
      lon = Math.round(pointLon*100000)/100000;
      ele = Math.round(pointEle*100000)/100000;
            
      lat = self.gpsUnit(lat);
      lon = self.gpsUnit(lon);
      units = self.unitPref("height");
      
      info = "<b>" + pictureName + "</b><br>"+
                              "<a href=\"" + fullsizeUrl + "\" rel=\"lightbox\" onclick=\"pop(this);return false;\">" +
						"<img src=\"" + thumbnailUrl + "\"> <br>" +
                              "Enlarge</a><Br>" +
                              pictureInfo;



      marker.openInfoWindow(info,{maxWidth:200});

   }
   this.zoomNote = function(noteId) {
      var self = Edit;
      self.map.closeInfoWindow();
      points = [];
      note = self.notes[noteId];
      marker = note['noteMarker'];
      point = marker.getPoint();
      points.push(point);

      self.zoomFit(points);
      
      /* open info window */
      pointInfo = note['noteInfo'];
      pointName = note['noteName'];
      pointLat = note['noteLat'];
      pointLon = note['noteLon'];
      pointEle = note['noteEle'];

      lat = Math.round(pointLat*100000)/100000;
      lon = Math.round(pointLon*100000)/100000;
      ele = Math.round(pointEle*100000)/100000;
            
      lat = self.gpsUnit(lat);
      lon = self.gpsUnit(lon);
      units = self.unitPref("height");

      info = "<b>" + pointName + "</b><br>" + pointInfo +
                   "<br><font size=-2>lat/lon/ele: " + lat + " / " + lon + " / " + ele + " " + units +
                   "<br>" +
                   "[<a href=# onclick=\"Edit.zoomNote("+noteId+");\">Zoom</a>] " +
                   "[<a href=# onclick=\"Edit.zoomFit();\">Zoom Fit</a>] " +
                   "</font>"
      marker.openInfoWindow(info,{maxWidth:200});
   }
   
   this.getTimeGPS = function(time,trackId) {
      var self = Edit;
      track = self.tracks[0];
      points = track['trackPoints'];
      
      lastPoint = points[points.length-1];
      lastPointTime = lastPoint['trackTime'];
      if((time - lastPointTime) > 300) {
         return false;
      }

      for(var i=0; i<points.length; i++) {
         point = points[i];
         trackTime = point['trackTime'];
         if(time >= trackTime) {
            matchedPoint = point['trackPoint'];
         } else {
            break;
         }
      }
      return matchedPoint;
   }
   
   this.makeTripTable = function() {
      var self = Edit;

      tripName = self.trip['tripName'];
      tripUsername = self.trip['tripUsername'];
      tripInfo = self.trip['tripInfo'];
      tripDate = self.trip['tripDate'];
      tripTags = self.trip['tripTags'];
      userPhoto = self.user['userPhoto'];
      tripUserId = self.trip['tripUserId'];

      /* text */
      editMapStr = "<a href='create_trip.php?trip_id="+self.tripId+"'>Edit this Trip</a>";

      img = "";
      if(userPhoto) {
         img = "<img src='"+userPhoto+"' height=60 align=left>";
      }


      tripNameStr = document.createTextNode(tripName + " created by " + tripUsername);
      tripDateStr = document.createTextNode("Trip created on: " + tripDate);
      tripDescStr = document.createTextNode("Trip Description: " + tripInfo);

      tripDiv = self.tripTable;
      tripDiv.innerHTML = img+'<h2>Trip: '+tripName+' by <a href="#">'+tripUsername+'</a> ' +
		                '<span class="trip-date">- '+tripDate+'</span></h2>';
    //  tripDiv.innerHTML = '<table><tr><td>'+img+'</td><td><h2>Trip: '+tripName+' by <a href="#">'+tripUsername+'</a> ' +
		         //       '<span class="trip-date">- '+tripDate+'</span></h2></td></tr></table>';

   }
   this.gpsUnit = function(gps) {
      var self = Edit;
      var gpsUnit = self.user['gpsUnit'];

      gps = parseInt(gps*1000000000000)/1000000000000;

      if(gpsUnit == "minutes") {
         degrees = Math.round(gps);
         r = gps-degrees;
         r = Math.abs(r);
         minutes = r*60;
         minutes = Math.round(minutes*1000)/1000;
         unit = degrees + "'" + minutes;
      } else {
         unit = gps;
      }   

      return unit;
   }
   
   this.unitPref = function(type) {
      var self = Edit;
      var lengthUnit = self.user['lengthUnit'];

      if(type == "length") {
         if(lengthUnit == "metric") {
            unit = "km";
         } else {
            unit = "miles";
         }
      } else if(type == "height") {
         if(lengthUnit == "metric") {
            unit = "m";
         } else {
            unit = "feet";
         }
      }
      return unit;
   }

   this.saveAjax = function() {
      var self = Edit;
      start = new Date();
      start = start.getTime();
      var query = 'start='+start;
      query += self.arrayToString();
      
      self.ajax.doPost('save_data.php',query, self.submitResponse,"text");

   }
   this.submitResponse = function(text) {
    //  alert("Submit not coded yet");
      alert(text);
   }     
   this.arrayToString = function() {
      var self = Edit;
      var query = "";
      var n = 0;

      /* format waypoints */
      for(var i=0; i<self.waypointMarkers.length; i++) {
         waypoint = self.waypointMarkers[i];
         if(waypoint) {
            waypointLat = waypoint['waypointLat'];
            waypointLon = waypoint['waypointLon'];
            waypointEle = waypoint['waypointEle'];
            waypointDB = waypoint['waypointDB'];
            waypointName = waypoint['waypointName'];
            waypointInfo = waypoint['waypointInfo'];
            showWaypoint = waypoint['showWaypoint']; 
            
            query += "&waypoints["+n+"][waypointLat]="+waypointLat;
            query += "&waypoints["+n+"][waypointLon]="+waypointLon;
            query += "&waypoints["+n+"][waypointEle]="+waypointEle;
            query += "&waypoints["+n+"][waypointDB]="+waypointDB;
            query += "&waypoints["+n+"][waypointName]="+waypointName;
            query += "&waypoints["+n+"][waypointInfo]="+waypointInfo;
            query += "&waypoints["+n+"][showWaypoint]="+showWaypoint;
            
            n++;

         }
      }
      
      /* format notes */
      n = 0;
      for(var i=0; i<self.notes.length; i++) {
         note = self.notes[i];
         if(note) {
            noteLat = note['noteLat'];
            noteLon = note['noteLon'];
            noteName = note['noteName'];
            noteInfo = note['noteInfo'];
            showNote = note['showNote'];
            
            query += "&notes["+n+"][noteLat]="+noteLat;
            query += "&notes["+n+"][noteLon]="+noteLon;
            query += "&notes["+n+"][noteName]="+noteName;
            query += "&notes["+n+"][noteInfo]="+noteInfo;
            query += "&notes["+n+"][showNote]="+showNote;
            
            n++;
         }
      }
      
      /* format tracks */
      
      n = 0;
      for(var i=0; i<self.tracks.length; i++) {
         track = self.tracks[i];

         if(track) {
            trackPoints = track['trackPoints'];
            trackName = track['trackName'];
            trackColor = track['trackColor'];
            trackDB = track['trackDB'];
            showTrack = track['showTrack'];

            query += "&tracks["+n+"][trackName]="+trackName;
            //query += "&tracks["+n+"][trackColor]="+trackColor;
            query += "&tracks["+n+"][trackDB]="+trackDB;
            query += "&tracks["+n+"][showTrack]="+showTrack;

            m = 0;


            for(var j=0; j < trackPoints.length; j++) {
               points = trackPoints[j];
               point = points['trackPoint'];
               lat = points['trackLat'];
               lon = points['trackLon'];
               ele = points['trackEle'];
               time = points['trackTime'];

               query += "&tracks["+n+"][points]["+m+"][lat]="+lat;
               query += "&tracks["+n+"][points]["+m+"][lon]="+lon;
               query += "&tracks["+n+"][points]["+m+"][ele]="+ele;
               query += "&tracks["+n+"][points]["+m+"][time]="+time;

               m++;
            }
            n++;
         }
         
      }
      
      /* format pictures */
      n = 0;

      for(var i=0; i<self.pictures.length; i++) {
         picture = self.pictures[i];
         if(picture) {
            pictureLat = picture['pictureLat'];
            pictureLon = picture['pictureLon'];
            pictureEle = picture['pictureEle'];
            pictureName = picture['pictureName'];
            pictureInfo = picture['pictureInfo'];
            pictureTime = picture['pictureTime'];
            pictureDB = picture['pictureDB'];
            pictureThumbnail = picture['pictureThumbnail'];
            pictureFullsize = picture['pictureFullsize'];

            showPicture = picture['showPicture'];
            isPrivate = picture['isPrivate'];

            query += "&pictures["+n+"][pictureLat]="+pictureLat;
            query += "&pictures["+n+"][pictureLon]="+pictureLon;
            query += "&pictures["+n+"][pictureName]="+pictureName;
            query += "&pictures["+n+"][pictureInfo]="+pictureInfo;
            query += "&pictures["+n+"][pictureTime]="+pictureTime;
            query += "&pictures["+n+"][showPicture]="+showPicture;
            query += "&pictures["+n+"][pictureThumbnail]="+pictureThumbnail;
            query += "&pictures["+n+"][pictureFullsize]="+pictureFullsize;

            n++;
         }
         
      }
      return query;

   }

   this.submit = function() {
      var self = Edit;
    //  waypoints = self.waypointMarkers;
     // alert(self.arrayToString());
      self.saveAjax();
   }

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

      var file = "user_data/KML/"+self.tripId+".kml";

     // var addr = "KML/"+file;
     // alert(addr);
      window.open ("downloadKML.php?file="+file+"&name="+self.tripId,"googleFrame","status=0,toolbar=0,location=0,menubar=0,resizable=0,width=50,height=50");

      /*
      var self = Edit;
      start = new Date();
      start = start.getTime();
      var query = 'start='+start;
      query += self.arrayToString();

      self.ajax.doPost('google_earth.php',query, self.googleEarthResponse,"text");
        */

   }
   this.googleEarthResponse = function(link) {
      var self = Edit;
      //alert(text);
       window.open ("downloadGPX.php?file="+link,"googleFrame","status=0,toolbar=0,location=0,menubar=0,resizable=0,width=50,height=50");
   }
   
   this.downloadGPXAjax = function() {
      var self = Edit;
      var file = "user_data/GPX/"+self.tripId+".gpx";

      //var addr = "KML/"+file;
     // alert(addr);
      window.open ("downloadGPX.php?file="+file+"&name="+self.tripId,"googleFrame","status=0,toolbar=0,location=0,menubar=0,resizable=0,width=50,height=50");

      /*
      var self = Edit;
      start = new Date();
      start = start.getTime();
      var query = 'start='+start;
      query += self.arrayToString();
      
      self.ajax.doPost('download_gpx.php',query, self.downloadGPXResponse,"text");
      */

   }
   this.downloadGPXResponse = function(link) {
      var self = Edit;
      //alert(link);
       window.open ("downloadGPX.php?file="+link,"googleFrame","status=0,toolbar=0,location=0,menubar=0,resizable=0,width=50,height=50");
   }
   
   this.getDirections = function() {
      var self = Edit;
      
      if(self.tracks.length > 0) {
         firstTrackPoint = self.tracks[0]['trackPoints'][0]['trackPoint'];

         var lat = firstTrackPoint.lat();
         var lon = firstTrackPoint.lng();
      } else {
         var lat = self.trip['tripCenterLat'];
         var lon = self.trip['tripCenterLon'];
      }
      
      var link = "http://maps.google.com/maps?f=q&hl=en&q="+lat+","+lon+"+("+self.tripName+")&ie=UTF8&z=12&om=1&iwloc=addr";

      window.open (link,"_blank","");
   }

   this.highlightStars = function(num) {
      for(var i=1;i<=5; i++) {
         var elem = document.getElementById("star"+i);
         if(i <= num) {
            elem.src = "/images/star-full.gif";
         } else {
            elem.src = "/images/star-empty.gif";
         }   
      }

      
   }
   
   this.unhighlightStars = function(num) {

      for(var i=1;i<=5; i++) {
         var elem = document.getElementById("star"+i);
         var rem = num-Math.floor(num);

         if(Math.floor(num) >= i) {
            elem.src = "/images/star-full.gif";
         } else if(rem >= .5 && (i-1) <= num) {
            elem.src = "/images/star-half.gif";
         } else {
            elem.src = "/images/star-empty.gif";
         }
      }
   }

   this.voteAjax = function(num) {
      var self = Edit;
      start = new Date();
      start = start.getTime();
      
      self.ajax.doGet("/trip/vote_ajax?tripId=" +self.tripId+'&start='+start+'&num='+num, self.voteResponse,"text");
   }
   
   this.voteResponse = function(response) {
     var self = Edit;
     response = response.split(",");
    
     numVote = parseInt(response[1]);
      if(numVote == -2) {
         alert("You can only vote for a trip once");
      } else if(numVote > 0) {

         self.trip_votes_span.innerHTML = numVote + " vote";
         if(numVote != 1) {
            self.trip_votes_span.innerHTML += "s";
         }
         
         self.tripVotes = response[0];
         self.unhighlightStars(response[0]);

      } else if(numVote == -1) {
         alert("Please log in or create an account to vote");
      }
      if(self.voteButton && self.trip_votes_span && numVote >= 0) {
         self.trip_votes_span.removeChild(self.voteButton);

      }
      

   }
   
   this.vote = function(num) {
      var self = Edit;
      if(!num) { num = 1; }

      self.voteAjax(num);
   }
   
   this.highlightPicture = function(pictureId) {
      var self = Edit;
      
      pictureDiv = "picture"+pictureId

      img = pictureDiv.replace(/Div/,'');

      picture = self.pictures[pictureId];
      if(picture) {
         marker = picture['marker'];
         if(marker && self.map.getBounds().contains(marker.getPoint())) {
            marker.setImage("images/markerend.png");
            self.showThumbnailDiv(marker.getPoint(),pictureId);
         }
      }
      
      document.getElementById(img).style.border = "4px solid #A1ED2D";
      


   }
   
   this.unhighlightPicture = function(pictureId) {
      var self = Edit;
      pictureDiv = "picture"+pictureId
      img = pictureDiv.replace(/Div/,'');
      

      picture = self.pictures[pictureId];
      if(picture) {
         marker = picture['marker'];
         if(marker) {
            marker.setImage("images/marker.png");
            if(self.currPicDiv) { self.mapDiv.removeChild(self.currPicDiv); self.currPicDiv = null;}
         }
      }
      document.getElementById(img).style.border = "4px solid #FFFFFF";   

   }
   
   this.addAllPictures = function() {
      var self = Edit;
      
      for(i=0;i<self.allPictures.length;i++) {
         pictureLat = self.allPictures[i]['lat'];
         pictureLon = self.allPictures[i]['lon'];
         pictureName = self.allPictures[i]['name'];
         pictureInfo = self.allPictures[i]['desc'];
         pictureThumbnail = self.allPictures[i]['thumb'];
         pictureFullsize = self.allPictures[i]['full'];
         server = self.allPictures[i]['server'];
         serverLink = self.allPictures[i]['serverLink'];
         picWidth = self.allPictures[i]['picWidth'];
         picHeight = self.allPictures[i]['picHeight'];
         picId = self.allPictures[i]['id'];

         self.addPicture(pictureLat,pictureLon,pictureName,pictureInfo,pictureThumbnail,pictureFullsize,server,serverLink,picWidth,picHeight,picId);

      }
   }

}

document.onload = Edit.init;
