/*--------------------------------------------------------------------------*/
/*  Western North Carolina GPS Mapper                                       *
 *  A Google Maps Mashup for WEB 289 - Spring 2008                          *
 *  (c) 2008 Jordan Mitchell                                                *
 *  All rights reserved.                                                    *
/*--------------------------------------------------------------------------*/

// Settinate these up before...
var map;
var allMarkers = [];
var sidebarHTML = "<h2>Route Layers</h2>";

function gmapCommon() {
  if(GBrowserIsCompatible()){
    // Create some topo map layers

    // Create a topo map layer from the TerraServer WMS (Web Mapping Service)
    function WMSCreateMap(name, copyright, baseUrl, layer, minResolution, maxResolution, urlArg )
    {
      var tileLayer = new GTileLayer( new GCopyrightCollection( copyright ), minResolution, maxResolution );
      tileLayer.baseUrl = baseUrl;
      tileLayer.layer = layer;
      tileLayer.getTileUrl = WMSGetTileUrl;
      tileLayer.getCopyright = function () { return copyright; };
      var tileLayers = [ tileLayer ];
      return new GMapType( tileLayers, G_SATELLITE_MAP.getProjection(), name, { errorMessage:"Data Not Available" } );
    }

    // Retrieve a tile from the Terraserver WMS
    function WMSGetTileUrl( tile, zoom )
    {
      var southWestPixel = new GPoint( tile.x * 256, ( tile.y + 1 ) * 256);
      var northEastPixel = new GPoint( ( tile.x + 1 ) * 256, tile.y * 256);
      var southWestCoords = G_NORMAL_MAP.getProjection().fromPixelToLatLng( southWestPixel, zoom );
      var northEastCoords = G_NORMAL_MAP.getProjection().fromPixelToLatLng( northEastPixel, zoom );
      var bbox = southWestCoords.lng() + ',' + southWestCoords.lat() +
      ',' + northEastCoords.lng() + ',' + northEastCoords.lat();
      return this.baseUrl + '?VERSION=1.1.1&REQUEST=GetMap&LAYERS=' +
      this.layer + '&STYLES=&SRS=EPSG:4326&BBOX=' + bbox +
      '&WIDTH=256&HEIGHT=256&FORMAT=image/jpeg&BGCOLOR=0xCCCCCC&EXCEPTIONS=INIMAGE';
    }

    // Retrieve a tile from MyTopo
    function GetMyTopoTile( a, b, c) {
      var lURL = this.myBaseURL;
      lURL += b;
      lURL += "/"+a.x;
      lURL += "/"+a.y+".jpg";
      return lURL;
    }

    var WMS_TOPO_MAP = WMSCreateMap( 'Topo', 'Imagery by USGS/Web Service by TerraServer',
    'http://www.terraserver-usa.com/ogcmap6.ashx', 'DRG', 4, 17, 't' );

    // Create a topo map layer from MyTopo
    var mytopoCopy = new GCopyright( 1,
    new GLatLngBounds(
    new GLatLng(-90, -180),
    new GLatLng( 90, 180 ) ),
    0,
    '&#169; MyTopo <a href="http://www.mytopo.com/google/index.cfm" target="_blank"><b>(MyTopo Layer Terms of Use)</b></a>' );

    var mytopoc = new GCopyrightCollection( '' );
    mytopoc.addCopyright( mytopoCopy );

    var tileMytopo = new GTileLayer( mytopoc, 9, 15 );
    tileMytopo.myLayers   = 'topoG';
    tileMytopo.myFormat   = 'image/jpg';
    tileMytopo.myBaseURL  = 'http://maps.mytopo.com/wncoutdoors/tilecache.py/1.0.0/topoG/';
    tileMytopo.getTileUrl = GetMyTopoTile;
    var mytopoLayer = [tileMytopo];
    var MYTOPO_MAP  = new GMapType(mytopoLayer, G_SATELLITE_MAP.getProjection(), "MyTopo", { errorMessage:"Data Not Available" } );

    // Initialize map and add the layers.
    var map = new GMap2(document.getElementById("map"));

    map.addMapType( WMS_TOPO_MAP) ;   // Add the topo map
    map.addMapType( MYTOPO_MAP );     // Add the MyTopo map
    map.addMapType( G_PHYSICAL_MAP ); // Add the physical map
    map.addControl( new GLargeMapControl3D() );
    map.addControl( new GMapTypeControl() );

    // Add Ads
    var publisher_id = "pub-5006048085075876";
    var adPos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 30));
    // Set the anchor position and GSize offset to your desired values.

    adsManagerOptions = {
      maxAdsOnMap : 2,
      style: 'adunit',
      channel: '3877723853',
      position: adPos
    };

    adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
    adsManager.enable();

    map.enableScrollWheelZoom();
  } // End if browser is compatible
  return map;
} // End gmapCommon function

function gmapInitialize() {
  if (GBrowserIsCompatible()) {
    // Initialize the basic Google map
    map = gmapCommon();
    map.setCenter(new GLatLng(35.8005, -82.4770), 8, G_PHYSICAL_MAP);
    loadParseGeoJSON('waterfalls'); // Automatically load & parse the initial view
  } // End if browser is compatible
} // End gmapInitialize function

// *******************************************************
// The following functions are for loading and parsing GPX 
// *******************************************************

// Choose a Line Style
function chooseLineStyle(name, comment) {
  if (comment == "BB" ) {
    return(new Array("#00f0f0",5,.5))
  }
  return(new Array("#ff2000",6,.7))   // Color,Width,Opacity
}

// Create a marker with InfoWindow
function createMarker(map, point, tabarray, icon, pointid) {
  var marker = new GMarker(point, icon);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowTabsHtml(tabarray);
  });
  map.addOverlay(marker);
  allMarkers[pointid] = marker;
  return marker;
}

// Create a function to "click" a marker when you click something else
// (i.e. - a listing in the search results)

function myclick(pointid) {
  GEvent.trigger(allMarkers[pointid], "click");
}

function navigateMap(lat,lng,zoom){
  map.setCenter(new GLatLng(lat,lng),zoom);
}

function toggleMarkers(){
  for(var mc = 0; mc < allMarkers.length; mc++)
  {
    currentMarker = allMarkers[mc];
    if (currentMarker.isHidden()) {
      currentMarker.show();
    } else {
      currentMarker.hide();
    }
  }
}

// Toggle a route
function toggleRoute(rteOverlay) {
  if(rteOverlay.supportsHide()){
    if(rteOverlay.isHidden()) {rteOverlay.show();} else {rteOverlay.hide();}
  } else {
    // Figure out how to determine if the polyline is added tothe map and
    // toggle it based on that
  }
}

// Toggle an individual track segment
function toggleSegment(segmentOverlay) {
  if(segmentOverlay.supportsHide())
  {
    if(segmentOverlay.isHidden()) {segmentOverlay.show();} else {segmentOverlay.hide();}
  }
  else
  {
    // Figure out a way to determine if the polyline is added to the map and
    // toggle it based on that
  }
}

// ***************************
// Load and parse the GeoJSON
// ***************************

function loadParseGeoJSON(something){
  
  // Clear the sidebar
  markers = [];
  segmentHTML = '';
  trackSegmentHTML = '';
  trackHTML = '';
  
  // Give a loading indicator
  $('tbstatus').update('<p style="text-align:center;"><img src="/images/gphx/ajax-loader.gif"><br>Loading Map...</p>');
  
 
  // Modify this to set the icon types used
  var red_pin = new GIcon();
  red_pin.image            = "images/markers/mm_20_red.png";
  red_pin.shadow         = "images/markers/mm_20_shadow.png";
  red_pin.iconSize       = new GSize(12, 20);
  red_pin.shadowSize     = new GSize(22, 20);
  red_pin.iconAnchor     = new GPoint(6, 20);
  red_pin.infoWindowAnchor = new GPoint(5, 1);
  
  var green_pin = new GIcon();
  green_pin.image      = "images/markers/mm_20_green.png";
  green_pin.shadow     = "images/markers/mm_20_shadow.png";
  green_pin.iconSize     = new GSize(12, 20);
  green_pin.shadowSize = new GSize(22, 20);
  green_pin.iconAnchor = new GPoint(6, 20);
  green_pin.infoWindowAnchor = new GPoint(5, 1);
  
  var blue_pin = new GIcon();
  blue_pin.image       = "images/markers/mm_20_blue.png";
  blue_pin.shadow      = "images/markers/mm_20_shadow.png";
  blue_pin.iconSize      = new GSize(12, 20);
  blue_pin.shadowSize = new GSize(22, 20);
  blue_pin.iconAnchor = new GPoint(6, 20);
  blue_pin.infoWindowAnchor = new GPoint(5, 1);
  
  var wptsProcessed = false;
  var rtesProcessed = false;
  var trksProcessed = false;
  
  // Initialize common map parts.
  map = gmapCommon();
 
  var request = GXmlHttp.create();
  var URL = "http://" + window.location.hostname + "/data/waterfalls/all.geojson";
  request.open("GET", URL, true);

request.onreadystatechange = function() {
  if (request.readyState == 4) {
    var json = request.responseText;
    var mapData = JSON.parse(json);
    if( !mapData ) {
      alert("Could not load map document " + URL);
    } else if( hasValue(mapData['err']) ) {
      alert("Error: " + mapData['msg']);
    } else if( !hasValue(mapData['type']) ) {
      alert("Map data " + URL + "\nwas not recognized by the map loader");
    } else if( mapData['type'] != "FeatureCollection" ) {
      alert("This does not appear to be a valid GeoJson file.");
    } else { // This does appear to be a GeoJson document

      map.setCenter(new GLatLng(35.8005, -82.4770), 8, G_PHYSICAL_MAP);
      var boundsForZoomLevel = new GLatLngBounds();
      var features = mapData['features'];
      for (var i = 0; i < features.length; i++) {
        // Only worry about points on this map
        if (features[i].type == "Feature" && features[i].geometry.type == "Point") {
          wptLon = parseFloat(features[i].geometry.coordinates[0]);
          wptLat = parseFloat(features[i].geometry.coordinates[1]);
          point = new GPoint(wptLon,wptLat);
          latlng = new GLatLng(wptLat, wptLon);
          boundsForZoomLevel.extend(latlng);
          pointid = features[i].id;
          var tabs = new Array();

          // Tab 1 //
          var tab1label = "General";
          var tab1html = '<div class="mapTab">';

          if( hasValue( features[i].properties.photo ) ){
            if( features[i].properties.photo.indexOf("gallery.wncoutdoors.info") != -1 ){
              var regUrl = features[i].properties.photo.replace('thumbs','regular');
            } else {
              urlArr = features[i].properties.photo.split( '/' );
              var fileName = urlArr.pop();
              var size = urlArr.pop();
              urlArr.push( 's640' );
              urlArr.push( fileName );
              var regUrl = urlArr.join( '/' );
            }
            tab1html += '<div style="float:right; margin-left: 5px;">' +
            '<a href="' + regUrl +
            '" rel="lytebox" onclick="myLytebox.start(this, false); return false;">';
            tab1html += '<img src="' + features[i].properties.photo
            + '" style="border:1px solid black;"></a></div>';
          } // If there is a photo and thumbnail, which there won't be

          // name
          tname = features[i].properties.name;
          // Permalink
          var urlName = tname.replace('/\s/','_');
          var permalink = 'http://northcarolinawaterfalls.info/waterfall/' +
          pointid + '/' + urlName;
          tab1html += '<h2>' + tname + '</h2>';
          // desc
          tdesc = features[i].properties.description;
          tab1html += '<p>' + tdesc + '</p>' +
            '<p><a href="' + permalink +
            '">View this waterfall\'s full page...</a></p>';
          tab1html += '</div>';

          var tab1 = new GInfoWindowTab(tab1label,tab1html);
          tabs.push(tab1);

          // Tab 2 //
          var tab2label = "Stats";
          var tab2html = "";
          theight = "";
          telev = "";
          tlandowner = "";

          // Build a stats list
          tab2html += '<div class="mapTab"><ul>';

          // Height
          if(hasValue(features[i].properties.height)) {
            tab2html += '<li><strong>Height:</strong> ' +
            features[i].properties.height
            + '</li>';
          }
          // Elevation
          if(hasValue(features[i].properties.elevation)) {
            tab2html += '<li><strong>Base Elevation:</strong> ' + features[i].properties.elevation + ' ft</li>';
          }
          // Landowner
          if(hasValue(features[i].properties.landowner)) {
            tab2html += '<li><strong>Landowner:</strong> ' + features[i].properties.landowner + '</li>';
          }
          // Coordinates
          tab2html += '<li><strong>Coordinates:</strong> ' + Math.round(wptLat * 1000000)/1000000 +
          ', ' + Math.round(wptLon* 1000000)/1000000 + '</li>';

          tab2html += '</ul><p>Location is approximate.</p></div>';

          var tab2 = new GInfoWindowTab(tab2label,tab2html);
          tabs.push(tab2);

          // Tab 3
          var tdirections = features[i].properties.directions;
          var ttraildirections = features[i].properties.trailDirections;

          if( ( hasValue(tdirections)) ||
          ( hasValue(ttraildirections))){
            var tab3label = "Directions";
            var tab3html = '<div class="mapTab">';
            if( hasValue(tdirections)) {
              tab3html += '<h2>Driving</h2>' +
              '<p>' + tdirections + '</p>';
            }
            if( hasValue(ttraildirections)) {
              tab3html += '<h2>Trail</h2>' +
              '<p>' + ttraildirections + '</p>';
            }
            tab3html += '</div>';
            var tab3 = new GInfoWindowTab(tab3label,tab3html);
            tabs.push(tab3);
          }

          // Determine map symbol based on <type></type> or <icon> tag
          myicon = blue_pin;
          createMarker(map, point, tabs, myicon, pointid);
          wptsProcessed = true;
        } // Points
      } // All features
      $('tbstatus').update();
    } // gpxDoc

    if(!wptsProcessed && !rtesProcessed && !trksProcessed){
      alert("No waypoints, routes, or tracks were found.");
      sidebarHTML = '';
    }

    if( typeof( pointId ) != "undefined" && pointId != null ){
      map.setCenter( allMarkers[ pointId ].getPoint(), 15, G_PHYSICAL_MAP );
      myclick( pointId );
    }

  } // readyState
  } // function
  request.send(null);
} // End load and parse GPX file

