/**
 * @author jmoe
 */
// <![CDATA[

TNT = {};

TNT.tripmap = {
    init: function(editing,new_trip) {
        this.editing = editing;
        // Initialize the map
        this.add_to_start_mode = 'add_to_start';
        this.viewing_mode = 'viewing';
        this.add_to_end_mode = 'add_to_end'
        this.editing_mode = 'editing'
        
        // setup the map
        this.map = new GMap2($('#plan-map')[0]);
        this.map.setCenter(new GLatLng(37.7750, -122.4190), 15);
        this.map.addControl(new GLargeMapControl3D());
        this.map.addControl(new GMapTypeControl());
        var scaleControlPosition = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10, 40));
        this.map.addControl(new GScaleControl(), scaleControlPosition);
        //this.map.enableScrollWheelZoom();
        this.map.enableContinuousZoom();
        this.map.enableGoogleBar();
        var copyOSM = new GCopyrightCollection("<a href=\"http://www.openstreetmap.org/\">OpenStreetMap</a>");
        copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, " "));
        var tilesMapnik = new GTileLayer(copyOSM, 1, 17, {
            tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'
        });
        var mapMapnik = new GMapType([tilesMapnik], G_NORMAL_MAP.getProjection(), "OSM");
        this.map.addMapType(mapMapnik);
        
        this.map.addMapType(G_PHYSICAL_MAP);
        this.map.addMapType(G_SATELLITE_3D_MAP);
        this.map.setMapType(G_NORMAL_MAP);
            
        this.startmarker = null;
        this.endmarker = null;
        
        this.geocoder = new GClientGeocoder();
        
        // Create our start marker icon
        var startIcon = new GIcon();
        startIcon.image = "/media/images/map/trip-start.png";
        startIcon.iconSize = new GSize(35, 39);
        startIcon.shadowSize = new GSize(38, 36);
        startIcon.iconAnchor = new GPoint(12, 35);
        
        // Set up our GMarkerOptions object
        var markerOptions = {
            icon: startIcon,
            draggable: editing
        };
        
        var startLatLng = new GLatLng(37.7750, -122.4190);
        this.startmarker = new GMarker(startLatLng, markerOptions);
        
        // Create our start marker icon
        var endIcon = new GIcon();
        endIcon.image = "/media/images/map/trip-end.png";
        endIcon.iconSize = new GSize(35, 39);
        endIcon.shadowSize = new GSize(38, 36);
        endIcon.iconAnchor = new GPoint(17, 33);
        
        // Set up our GMarkerOptions object
        
        var endMarkerOptions = {
            icon: endIcon,
            draggable: editing
        };
                
        this.endmarker = new GMarker(new GLatLng(0, 0), endMarkerOptions);        
                
        this.trailheadMarkerManager = new MarkerManager(this.map);
        
        TNT.tripmap.tripLine = new GPolyline();
        this.map.addOverlay(TNT.tripmap.tripLine);                       
        GEvent.addListener(TNT.tripmap.tripLine, "lineupdated", function(){          
          TNT.tripmap.updateDistanceDiv();
          // TNT.tripmap.endmarker.setLatLng(TNT.tripmap.tripLine.getVertex(TNT.tripmap.tripLine.getVertexCount() -
        // 1));
        });
                
        if (editing) {
          this.showTrailheads();
          if(!new_trip) {
            this.tripLine.enableEditing();
            this.tripLine.enableDrawing();
          }
          var centerUrl = '/session/loadkv/map.center';
          GDownloadUrl(centerUrl, function(data) {          
            if (data.match(/NOT_FOUND/) == null) {
              latlngarray = data.split(",");
              lat = parseFloat(latlngarray[0]);
              lng = parseFloat(latlngarray[1]);
              var newCenter = new GLatLng(lat, lng);                
              TNT.tripmap.map.setCenter(newCenter);              
            }
            else {
              TNT.tripmap.map.setCenter(this.startmarker.getLatLng(), 15);
            }
          });
        } 
        
        GEvent.bind(this.map, "moveend", this, this.onMoveEnd);       
        
    },

    saveMap : function(){
        saveKeyValueToSession('map.center', TNT.tripmap.map.getCenter().toUrlValue());
        saveKeyValueToSession('map.zoom', TNT.tripmap.map.getZoom());
    },

    loadTripStartData : function(data){
        var latlng = new GLatLng(parseFloat(data.latitude), parseFloat(data.longitude));
        var title = data.name;
        TNT.tripmap.startmarker.setLatLng(latlng);      
        TNT.tripmap.map.addOverlay(TNT.tripmap.startmarker);
        if (TNT.tripmap.tripLine == null) {
            var points = new Array();
            points.push(latlng);
            TNT.tripmap.map.removeOverlay(this.tripLine);
            TNT.tripmap.tripLine = new GPolyline(points);
            TNT.tripmap.map.addOverlay(this.tripLine);
            TNT.tripmap.startmarker.hide();
        }
        else {
            TNT.tripmap.tripLine.insertVertex(0, this.startmarker.getLatLng());
        }        
    },

    loadTripStart : function(id){
        var url = "/json/Trailhead/" + id;
        $.get(url, function(response){
                TNT.tripmap.loadTripStartData(response);    
                TNT.tripmap.startmarker.trailhead_id = id;            
        },'json');
    },

    loadTripEnd : function(id){
        url = "/json/Trailhead/" + id;
        GDownloadUrl(url, function(data){
            var object = $.parseJSON(data);
            var latlng = new GLatLng(parseFloat(object.latitude), parseFloat(object.longitude));
            var title = object.name;
            TNT.tripmap.endmarker.trailhead_id = id;
            if (TNT.tripmap.endmarker != null) {
                TNT.tripmap.endmarker.setLatLng(latlng);
            }
            if(!TNT.tripmap.editing) {
                TNT.tripmap.map.addOverlay(TNT.tripmap.endmarker);
            }
        });
    },

    onMoveEnd : function(){
        if (this.editing) {
            this.showTrailheads()
        }
        saveKeyValueToSession("map.center", this.map.getCenter().toUrlValue());
        saveKeyValueToSession("map.zoom", this.map.getZoom());
    },

    showTrailheads : function(){
        var sw = this.map.getBounds().getSouthWest();
        var ne = this.map.getBounds().getNorthEast();
        
        var sw_lat = sw.lat();
        var sw_long = sw.lng();
        var ne_lat = ne.lat();
        var ne_long = ne.lng();
        
        var url = "/trailheads/find_in/?sw_lat=" + sw_lat + "&sw_long=" + sw_long +
        "&ne_lat=" +
        ne_lat +
        "&ne_long=" +
        ne_long;
        
        GDownloadUrl(url, function(data){
            var xml = GXml.parse(data);
            var trailheads = xml.documentElement.getElementsByTagName("trailhead");
            var currentTrailheads = [];            
            TNT.tripmap.currentTrailheadsById = {}
            for (var i = 0; i < trailheads.length; i++) {                
                var pointId = trailheads[i].getAttribute("id");
                  var pointTitle = trailheads[i].getAttribute("name");
                  var latlng = new GLatLng(parseFloat(trailheads[i].getAttribute("lat")), parseFloat(trailheads[i].getAttribute("lng")));
                  
                  var newMarker = TNT.tripmap.createMarker(pointId, latlng, pointTitle);
                  TNT.tripmap.currentTrailheadsById[pointId] = newMarker;
                  currentTrailheads[i] = newMarker;
            }
            
            TNT.tripmap.trailheadMarkerManager.clearMarkers();
            TNT.tripmap.trailheadMarkerManager.addMarkers(currentTrailheads, 0);          
            TNT.tripmap.trailheadMarkerManager.refresh();
        });
    },

    createMarker : function(id, latlng, pointTitle){
        var tinyIcon = new GIcon();
        tinyIcon.image = "/media/images/map/trailhead.png";
        tinyIcon.iconSize = new GSize(27, 28);
        tinyIcon.shadowSize = new GSize(0, 0);
        tinyIcon.iconAnchor = new GPoint(10, 27);
        tinyIcon.infoWindowAnchor = new GPoint(10, 5);
        if(TNT.tripmap.startmarker.trailhead_id == id){
          tinyIcon.image = "/media/images/map/trip-start.png";
          tinyIcon.iconSize = new GSize(35, 39);
          tinyIcon.shadowSize = new GSize(38, 36);
          tinyIcon.iconAnchor = new GPoint(12, 35);
        } else if(TNT.tripmap.endmarker.trailhead_id == id){
          tinyIcon.image = "/media/images/map/trip-end.png";
          tinyIcon.iconSize = new GSize(35, 39);
          tinyIcon.shadowSize = new GSize(38, 36);
          tinyIcon.iconAnchor = new GPoint(12, 35);
        }

        var pointMarkerOptions = {
            icon: tinyIcon,
            title: pointTitle,
            draggable: false,
            clickable: true
        };
        
        var newMarker = new GMarker(latlng, pointMarkerOptions);
        newMarker.value = "" + id;
        GEvent.addListener(newMarker, "click", function(){
            var url = "/trips/editor/getinfowindow/?id=" + id;
            GDownloadUrl(url, function(data){
                var myHtml = data;
                TNT.tripmap.map.openInfoWindowHtml(newMarker.getLatLng(), myHtml);
            });
        });
        return newMarker;
    },

    createWayPointMarker : function(latlng){
        var tinyIcon = new GIcon();
        tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
        tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        tinyIcon.iconSize = new GSize(12, 20);
        tinyIcon.shadowSize = new GSize(22, 20);
        tinyIcon.iconAnchor = new GPoint(6, 20);
        tinyIcon.infoWindowAnchor = new GPoint(5, 1);
        pointMarkerOptions = {
            icon: tinyIcon,
            draggable: false,
            clickable: true
        };        
        var newMarker = new GMarker(latlng, pointMarkerOptions);
        return newMarker;
    },


    makeTripStart : function(id){
        var startLatLng = TNT.tripmap.currentTrailheadsById[id].getLatLng();
        TNT.tripmap.startmarker.setLatLng(startLatLng);
        TNT.tripmap.startmarker.trailhead_id = id;    
        if (TNT.tripmap.tripLine == null) {
            points = new Array();
            points.push(startLatLng);
            TNT.tripmap.map.removeOverlay(this.tripLine);
            TNT.tripmap.tripLine = new GPolyline(points);
            TNT.tripmap.map.addOverlay(TNT.tripmap.tripLine);            
        }
        else {
            TNT.tripmap.tripLine.insertVertex(0, startLatLng);
            if(TNT.tripmap.tripLine.getVertexCount() > 1) {
              TNT.tripmap.tripLine.deleteVertex(1);
              TNT.tripmap.tripLine.redraw();
            }
        }
        TNT.tripmap.map.closeInfoWindow();
        TNT.tripmap.startmarker.show();        
        $('#id_starting_point').val(id);        
        TNT.tripmap.tripLine.enableDrawing();
        TNT.tripmap.tripLine.enableEditing();
        TNT.tripmap.showTrailheads();
    },

    editTrip: function(){
      //TNT.tripmap.map.removeOverlay(TNT.tripmap.tripLine);
      //TNT.tripmap.map.addOverlay(TNT.tripmap.tripLine);
      TNT.tripmap.tripLine.enableDrawing();
      TNT.tripmap.tripLine.enableEditing();
    },

    makeTripEnd : function(id){
        if(!TNT.tripmap.startmarker.trailhead_id) {
          alert("Please choose a starting point first.");
          return false;
        }
        var markerLatLng = TNT.tripmap.currentTrailheadsById[id].getLatLng();
        if (TNT.tripmap.tripLine != null) {
            count = TNT.tripmap.tripLine.getVertexCount();
            TNT.tripmap.tripLine.insertVertex(count, markerLatLng);
        }
        TNT.tripmap.endmarker.setLatLng(markerLatLng);
        TNT.tripmap.endmarker.trailhead_id = id;
        TNT.tripmap.map.closeInfoWindow();
        $('#id_ending_point').val(id);
        TNT.tripmap.showTrailheads();
    },

    clearWayPoints : function(){
        var clearConfirm = confirm("Are you sure you want to clear this trip route?");
        if (clearConfirm == true) {
            this.map.removeOverlay(this.tripLine);
            points = new Array();
            points.push(this.startmarker.getLatLng());
            points.push(this.endmarker.getLatLng());
            this.map.addRemove(this.tripLine);
            this.tripLine = new GPolyline(points)
            this.map.addOverlay(this.tripLine);
            this.tripLine.enableEditing();
            this.tripLine.enableDrawing();
        }
        
    },

    eraseFromEnd : function(){
        this.tripLine.deleteVertex(this.tripLine.getVertexCount() - 1);
        this.endmarker.setLatLng(this.tripLine.getVertex(this.tripLine.getVertexCount() -
        1));
        this.updateDistanceDiv();
        TNT.tripmap.editTrip();
    },

    eraseFromStart : function(){
        this.tripLine.deleteVertex(0);
        this.startmarker.setLatLng(this.tripLine.getVertex(0));
        this.updateDistanceDiv();
    },

    getWayPointHtml : function(){
        var pointArray = new Array();
        for (i = 0; i < this.tripLine.getVertexCount(); i++) {
            var subArray = new Array();
            subArray.push(parseFloat(this.tripLine.getVertex(i).lat()));
            subArray.push(parseFloat(this.tripLine.getVertex(i).lng()));
            pointArray.push(subArray);
        }
        var xml = JSON.stringify(pointArray)
        $('#id_route').val(xml);
        $('#id_description').text($("#id_description").val());
    },

    centerOnTrip : function(){
        var bounds = TNT.tripmap.tripLine.getBounds();
        var centerpoint = bounds.getCenter();
        var zoom = TNT.tripmap.map.getBoundsZoomLevel(bounds);
        TNT.tripmap.map.setCenter(centerpoint, zoom);
    },

    loadJSONRoute : function(){        
        var bounds = new GLatLngBounds();
        var route = $.parseJSON($('#id_route').val());
        var points = new Array();
        points.push(new GLatLng(route[0][0], route[0][1]));
        for (i = (route.length-1); i >= 0; i--) {
            var newVertex = new GLatLng(route[i][0], route[i][1]);
            TNT.tripmap.tripLine.insertVertex(0,newVertex);
            bounds.extend(newVertex);
        }
        if ($('#id_starting_point').val() != '') {
            TNT.tripmap.loadTripStart($('#id_starting_point').val());
        }
        
        if ($('#id_ending_point').val() != '') {
            TNT.tripmap.loadTripEnd($('#id_ending_point').val());
        }    
        var centerpoint = bounds.getCenter();
        var zoom = TNT.tripmap.map.getBoundsZoomLevel(bounds);
        TNT.tripmap.map.setCenter(centerpoint, zoom);

    },

    updateDistanceDiv : function(){
        distance = this.tripLine.getLength() * 0.000621371192;
        text = distance.toFixed(1) + " Miles";
        $('#distance').html(text);
    },


    setAddToStartMode : function(){
        this.mode = this.add_to_start_mode;        
        this.tripLine.enableEditing();
        this.tripLine.enableDrawing();
    },

    setAddToEndMode : function(){
        this.mode = this.add_to_end_mode;          
        this.tripLine.enableEditing();
        this.tripLine.enableDrawing();
    },

    editRoute : function(){
        document.body.style.cursor = "wait";
        this.tripLine.enableEditing();
        this.tripLine.enabledDrawing();
        document.body.style.cursor = "default";
    },

}
// ]]>

