var TNT = {};


TNT.pointmap = {
	
	currentTrailheads: null,
	trailheadMarkerManager: null,

    init: function(trailhead, editing) {

        var icon = null;
        var trailheadIcon = new GIcon();
		if (!editing) {
			trailheadIcon.image = "/media/images/map/pin_s_trailhead_active.png";
		} else {
			trailheadIcon.image = "/media/images/map/pin_s_trailhead.png";
		}
        
        trailheadIcon.iconSize = new GSize(34, 36);
        //trailheadIcon.shadowSize = new GSize(38, 36);
        trailheadIcon.iconAnchor = new GPoint(14, 30);
        trailheadIcon.infoWindowAnchor = new GPoint(14, 10);


        var campgroundIcon = new GIcon();
        campgroundIcon.image = "/media/images/map/pin_s_campground.png";
        campgroundIcon.iconSize = new GSize(34, 36);
        campgroundIcon.shadowSize = new GSize(38, 36);
        campgroundIcon.iconAnchor = new GPoint(14, 30);
        campgroundIcon.infoWindowAnchor = new GPoint(14, 10);

        if (trailhead) {
            icon = trailheadIcon;
        } else {
            icon = campgroundIcon;
        }

        if (editing) {
            trailheadMarkerOptions = {
                icon: icon,
                draggable: true,
                clickable: true
            };
        } else {
            trailheadMarkerOptions = {
                icon: icon,
                draggable: true,
                clickable: false
            }
        };

        var start = new GLatLng(37.887771, -122.256452);
        this.startmarker = new GMarker(start, trailheadMarkerOptions);

        this.editing = editing;
        this.map = new GMap2($('#plan-map')[0]);
        this.map.setCenter(start, 17);
        //this.map.setCenter(startLatLng, 16);
        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.map.addOverlay(this.startmarker);
        GEvent.bind(this.startmarker, "dragend", this, this.moveStart);
        GEvent.bind(this.map, "dblclick", this, this.saveMap);
		this.trailheadMarkerManager = new MarkerManager(this.map);
		loadKeyFromSession('map.zoom',function(data){
          if( data.match(/NOT_FOUND/) == null ){
            var newZoom = Number(data);
            TNT.pointmap.map.setZoom(newZoom);
          }
        })
    },

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

    moveStart: function(overlay, latlng) {
        if (overlay) {
            this.updateLatLngInputs(this.startmarker.getLatLng());
        }
        if (latlng) {
            this.startmarker.setLatLng(latlng);
            this.updateLatLngInputs(latlng);
        }
		downloadurl = "/trailheads/near/xml?lat=" +
        this.startmarker.getLatLng().lat() +
        "&long=" +
        this.startmarker.getLatLng().lng() +
        "&distance=100";
        GDownloadUrl(downloadurl,
        function(data) {
            TNT.pointmap.loadTrailheads(data);
        });
    },

    updateLatLngInputs: function(latlng) {
        $('#id_latitude').val(latlng.lat());
        $('#id_longitude').val(latlng.lng());
    },

    loadTrailhead: function(id, editing) {
        url = "/json/Trailhead/" + id;
        var self = this;
        GDownloadUrl(url,
        function(data) {
            var object = $.parseJSON(data);
            var startLatLng = new GLatLng(parseFloat(object.latitude), parseFloat(object.longitude));
            self.map.setCenter(startLatLng, 13);
            self.startmarker.setLatLng(startLatLng);
            self.map.panTo(self.startmarker.getLatLng());
            self.updateLatLngInputs(startLatLng);
        });
    },

	createTrailheadMarker: function(pointId, pointTitle, latlng) {
        var that = this;
        var tinyIcon = new GIcon();
        tinyIcon.image = "/media/images/map/Map-Pins-Small.png";
        tinyIcon.iconSize = new GSize(27, 28);
        //tinyIcon.shadowSize = new GSize(38, 36);
        tinyIcon.iconAnchor = new GPoint(14, 30);
        tinyIcon.infoWindowAnchor = new GPoint(14, 10);

        var pointMarkerOptions = {
            icon: tinyIcon,
            title: pointTitle,
            draggable: false,
            clickable: true
        };
        var newMarker = new GMarker(latlng, pointMarkerOptions);

        GEvent.addListener(newMarker, "click",
        function() {
            that.showTrailhead(pointId);
        });
        return newMarker;
    },

    loadTrailheads: function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("trailhead");
        this.currentTrailheads = []
        this.trailheadMarkerManager.clearMarkers();
        $(markers).each(function(index,item) {
            var latlng = new GLatLng(parseFloat(item.getAttribute("lat")), parseFloat(item.getAttribute("lng")));
            var distance = new Number(item.getAttribute("distance")).toPrecision(2);
            var pointTitle = item.getAttribute("name");
            var pointId = new Number(item.getAttribute("id"));
            var pointIndex = new Number(index);
            var newMarker = TNT.pointmap.createTrailheadMarker(pointId, pointTitle, latlng);
            TNT.pointmap.currentTrailheads[pointId] = newMarker;
            //if (this.showTrailheads) {
                TNT.pointmap.trailheadMarkerManager.addMarker(newMarker, 0);
            //}    				
        });
		
        this.trailheadMarkerManager.refresh();
    },

    loadCampground: function(id) {
        var self = this;
        url = "/json/Campground/" + id;
        GDownloadUrl(url,
        function(data) {
            var object = $.parseJSON(data);
            var startLatLng = new GLatLng(parseFloat(object.latitude), parseFloat(object.longitude));
            self.map.setCenter(startLatLng, 13);
            self.startmarker.setLatLng(startLatLng);
            self.map.panTo(self.startmarker.getLatLng());
            self.updateLatLngInputs(startLatLng);
        });
    },

    decodeAddress: function(address) {
        if (TNT.find.geocoder) {
            TNT.find.geocoder.getLatLng(address,
            function(point) {
                if (point) {
                  this.startmarker.setLatLng(point);
                  this.updateLatLngInputs(point);                  
                }
            })
        }
    },

    chooseStart: function() {
      var endLatLng = null;
      // If there is a start location saved in the session then use it
      loadLocationFromSession(
        function(data) {
            if (data && data != 'undefined') {              
                TNT.pointmap.decodeAddress(data);
            }
            else {
                var start = new GLatLng(37.887771, -122.256452);
                if (google.loader.ClientLocation != null) {
                    start = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
                }
            
                TNT.pointmap.startmarker.setLatLng(start);
                TNT.pointmap.updateLatLngInputs(start);
            }
      });
      
        var start = new GLatLng(37.887771, -122.256452);
        if (google.loader.ClientLocation != null) {
            start = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
        }
        this.startmarker.setLatLng(start);
        this.map.panTo(start);
        this.updateLatLngInputs(start);
    }

};

function initTrailheadDetails(id, editing) {
    if (GBrowserIsCompatible()) {
        TNT.pointmap.init(true, editing);
        TNT.pointmap.loadTrailhead(id, editing);
        if (!editing)
        {
            TNT.pointmap.startmarker.disableDragging();
        }	
    }
}

function initCampgroundDetails(id, editing) {
    if (GBrowserIsCompatible()) {
        TNT.pointmap.init(false, editing);
        TNT.pointmap.loadCampground(id);
        if (!editing)
        {
            TNT.pointmap.startmarker.disableDragging();
        }

    }
}

// Initialize google maps and the rounded corners
function initEditing(trailhead, editing) {
    if (GBrowserIsCompatible()) {
        TNT.pointmap.init(trailhead, editing);
        TNT.pointmap.startmarker.enableDragging();
        if (editing) {
            TNT.pointmap.startmarker.setLatLng(new GLatLng(parseFloat($('#id_latitude').val()), parseFloat($('#id_longitude').val())));
            TNT.pointmap.map.panTo(TNT.pointmap.startmarker.getLatLng());
        }
        else {
            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.pointmap.startmarker.setLatLng(newCenter);
                    TNT.pointmap.map.setCenter(TNT.pointmap.startmarker.getLatLng());
                    TNT.pointmap.updateLatLngInputs(newCenter);
                }
                else {
                    TNT.pointmap.chooseStart();
                }
            });
			
            zoomUrl = '/session/loadkv/map.zoom';
            GDownloadUrl(zoomUrl,
            function(data) {
                if (data.match(/NOT_FOUND/) == null) {
                    newZoom = parseInt(data, 10);
                    //alert(newZoom);
                    TNT.pointmap.map.setZoom(newZoom);
                }
            });
			
			// begin adding peripheral trailheads for user knowledge
			downloadurl = "/trailheads/near/xml?lat=" +
	        "37.887771" +
	        "&long=" +
	        "-122.256452" +
	        "&distance=100";
	        GDownloadUrl(downloadurl,
	        function(data) {
	            TNT.pointmap.loadTrailheads(data);
	        });
			// end adding peripheral trailheads for user knowledge
        }

    }
}

