/*--------------------------------------------------------------------------*/
/*  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 a topo map layer based on the free 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" } );
    }
    // Function to retrieve the 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';
    }
    // Create the layer
    var WMS_TOPO_MAP = WMSCreateMap( 'Topo', 'Imagery by USGS / Web Service by TerraServer',
      'http://www.terraserver-usa.com/ogcmap6.ashx', 'DRG', 4, 17, 't' );
    var map = new GMap2(document.getElementById("map"));
    map.addMapType(WMS_TOPO_MAP); // Add the topo 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";
  // alert(URL);
  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) &&
                        hasValue(features[i].properties.thumb) ){
                          tab1html += '<div style="float:right; margin-left: 5px;">' +
                          '<a href="' + features[i].properties.photo + 
                          '" rel="lytebox" onclick="myLytebox.start(this, false); return false;">';
              tab1html += '<img src="' + eatures[i].properties.thumb
                       + '" 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);
                    }

                    // Tab 4
                    /*
                    var hikeUrlEle = wpt[i].getElementsByTagName("hikeUrl");
                    var bikeUrlEle = wpt[i].getElementsByTagName("bikeUrl");
                    var otherUrlEle = wpt[i].getElementsByTagName("otherUrl");
                    
                    
                    if( hikeUrlEle.length || bikeUrlEle.length || otherUrlEle.length )
                    {
                        var tab4label = "Links";
                        var tab4html = '<div class="mapTab"><ul>';
                        thikeurl = "";
                        tbikeurl = "";
                        totherurl = "";
                      if( hikeUrlEle.length ) {
                            thikeurl = hikeUrlEle[0].firstChild.nodeValue;
                            tab4html += '<li><a href="' + 
                  thikeurl + '" target="_blank">Hike to This Waterfall</a></li>';
                      }
                      if( bikeUrlEle.length ) {
                            tbikeurl = bikeUrlEle[0].firstChild.nodeValue;
                            tab4html += '<li><a href="' +
                  tbikeurl + '" target="_blank">Mountain Bike Ride to This Waterfall</a></li>';
                        }
                        if( otherUrlEle.length ) {
                            totherurl = otherUrlEle[0].firstChild.nodeValue;
                            tab4html += '<li><a href="' + 
                  totherurl + '" target="_blank">More Information About This Waterfall</a></li>';
                        }
                      tab4html += "</ul></div>";
                      var tab4 = new GInfoWindowTab(tab4label,tab4html);
                      tabs.push(tab4);
                    }
                    */
                    
                    // 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 = '';
      }
        } // readyState
  } // function
  request.send(null);
} // End load and parse GPX file
