$(document).ready(function(){
    coursemap.load();
});

var coursemap = {

    map:null,
    icon:null,
    icons:{},

    load:function(){
    
        this.icons.blueflag = new GIcon();
        this.icons.blueflag.image = "/images/flag_icon_lg_blue.png";
        this.icons.blueflag.iconSize = new GSize(24,24);
        this.icons.blueflag.shadowSize = new GSize(24,24);
        this.icons.blueflag.iconAnchor = new GPoint(12,22);
        this.icons.blueflag.infoWindowAnchor = new GPoint(22,4);
    
        this.icons.greenflag = new GIcon();
        this.icons.greenflag.image = "/images/flag_icon_lg_green.png";
        this.icons.greenflag.iconSize = new GSize(24,24);
        this.icons.greenflag.shadowSize = new GSize(24,24);
        this.icons.greenflag.iconAnchor = new GPoint(12,22);
        this.icons.greenflag.infoWindowAnchor = new GPoint(22,4);
            
        this.map = new GMap2(document.getElementById("map"));
        this.map.addControl(new GLargeMapControl());
        this.map.addControl(new GMapTypeControl());
        this.loadGPX(this.map,'/data/boilermaker.xml');
        this.loadPhotos(this.map);
    },
    
    loadGPX:function(map,filename) {
        
        map.clearOverlays(); // remove any existing overlays from the map

        $.get(filename,'',function(xml){
            parser = new GPXParser(xml,map);
            parser.SetTrackColour("#ff0000");    // Set the track line colour
            parser.SetTrackWidth(5);             // Set the track line width
            parser.SetMinTrackPointDelta(0.001); // Set the minimum distance between track points
            parser.CenterAndZoom(xml);           // Center and Zoom the map over all the points.
            parser.AddTrackpointsToMap();        // Add the trackpoints
            parser.AddWaypointsToMap();
            
            
        });
    },
    
    loadPhotos:function(map){
    
        var self = this;
        
        $.getJSON('/get_json.php',{type:'photos'},function(json){
        
            var icon = new GIcon();
            icon.image = "/_/images/camera_icon.png";
            //icon.shadow = "/images/camera_icon.png";
            icon.iconSize = new GSize(20,20);
            icon.shadowSize = new GSize(20,20);
            icon.iconAnchor = new GPoint(7,16);
            icon.infoWindowAnchor = new GPoint(5,1);
            
            $.each(json,function(n,photo){
                
                var point = new GLatLng(photo.lat,photo.lng);
                
                if (photo.icon) {
                    var marker = new PdMarker(point,self.icons[photo.icon],photo.title);
                    var hoverImage = photo.image;
                } else {
                    var marker = new PdMarker(point,icon,photo.title);
                    var hoverImage = "/_/images/camera_icon_hover.png";
                }
                
                var html = '<a href="/photos/'+photo.filename+'" class="thickbox" title="'+photo.title+'"><img src="/photos/'+photo.thumbnail+'" /></a>';
                marker.setTooltip(html);
                marker.setOpacity(90);
                marker.setHoverImage(hoverImage);

                GEvent.addListener(marker,"click",function() {
                    tb_show('<strong>'+photo.title+'</strong> <small>Elevation: '+photo.elevation+' ft.</small>','/photos/'+photo.filename);
                });

                map.addOverlay(marker);
            
            });
        
        });
    
    }

};

var googlemap = {

    map: null,
    api_key: 'ABQIAAAAMwdxgAqXzpdAWJT_nAd5dBQFwuY5_g50tzxAbH7zYGXQkWjcrRQOzsHOlb8xOUCy9X6__cy-DxqUvA',
    plotted_area: null,
    loaded:false,
    regions:false,
    
    init:function(){
    
        if (!GBrowserIsCompatible()) return;
        var self = this;
        
        // create a base marker icon
        this.flag = new GIcon();
        this.flag.image = "marker.png";
        this.flag.iconSize = new GSize(17,17);
        this.flag.iconAnchor = new GPoint(9,9);
        this.flag.infoWindowAnchor = new GPoint(9,9);

        // create a base marker icon
        this.flag_alt = new GIcon();
        this.flag_alt.image = "marker_large.png";
        this.flag_alt.iconSize = new GSize(27,27);
        this.flag_alt.iconAnchor = new GPoint(14,14);
        this.flag_alt.infoWindowAnchor = new GPoint(14,14);
        
        // create the map
        this.map = new GMap2(document.getElementById("map"));
        this.map.addControl(new GSmallMapControl());
        this.map.setCenter(new GLatLng(43.103983,-75.245415),2);
        
        // get the map's current bounds
        this.plotted_area = this.map.getBounds();
        
        this.showBrewery();
        this.showRegions();
        this.showCountries();

        GEvent.addListener(this.map,"zoomend",function(){
            self.plotted_area = self.map.getBounds();
        });
        
        GEvent.addListener(this.map,"moveend",function(){
            
            if (self.map.getZoom() > 5) {
            
                //if (!self.checkBoundsOverlap()) {
                //    self.plotted_area = self.map.getBounds();
                    //if (self.loaded) self.showClusters(); self.loaded = true;
                    if (self.loaded) self.showRunners(); self.loaded = true;
                //}
                
            } else {
            
                if (!self.regions) self.showRegions();

            }
            
        });

    },
    
    showRegions:function(){
    
        var self = this;
        var url = "/ajax/runners.json.php?regions=true";
        $.get(url,function(data){
            var json = eval("("+data+")");
            for (e in json) {
                var place = json[e];
                var point = new GLatLng(place.latitude,place.longitude);
                var info = '<p><strong><big>'+place.name+'</big></strong></p>'
                         + '<a onclick="googlemap.zoomRegion('+"'"+place.state + "','" + place.country + "','" + place.latitude +"','" + place.longitude + "'" + ');return false;" href="?">Click here to zoom in and view runners</a></p>';
                self.createMarkerAlt(self.map,point,info);
            }
        });
        self.regions = true;
        
    },
    
    showCountries:function(){
        
        var self = this;
        //this.map.clearOverlays();
        self.regions = false;
        
        //this.map.setCenter(new GLatLng(latitude,longitude),6);
                    
        var url = "/ajax/runners.json.php?countries=true";
        $.get(url,function(data){
            var json = eval("("+data+")");
            //alert(data);
            for (e in json) {
                var place = json[e];
                var point = new GLatLng(place.latitude,place.longitude);
                var info = '<p><strong><big>'+place.address+'</big></strong></p>'
                         + '<strong>Runners:</strong> '+place.runners+' (<a onclick="googlemap.showSearch('+place.id+');return false;" href="/?id='+place.id+'">view runners</a>)</p>';
                self.createMarker(self.map,point,info);
            }
        });
        
    },
    
    showRunners:function(){
    
        //alert('showing runners now');
        return;
        
        var self = this;
        this.map.clearOverlays();
        self.regions = false;
    
        var b = self.map.getBounds();
        var bounds =
            "?latitude=" + b.getSouthWest().lat() + "," + b.getNorthEast().lat() +
            "&longitude=" + b.getSouthWest().lng() + "," + b.getNorthEast().lng();
            
        var url = "/ajax/runners.json.php" + bounds;
        $.get(url,function(data){
            var json = eval("("+data+")");
            for (e in json) {
                var place = json[e];
                var point = new GLatLng(place.latitude,place.longitude);
                var info = '<p><strong><big>'+place.address+'</big></strong></p>'
                         + '<strong>Runners:</strong> '+place.runners+' (<a onclick="googlemap.showSearch('+place.id+');return false;" href="/?id='+place.id+'">view runners</a>)</p>';
                self.createMarker(self.map,point,info);
            }
        });
                
    },
    
    showClusters:function(){
        
        //alert('plot new!');
        var self = this;
        
        var b = self.map.getBounds();
        var bounds =
            "?latitude=" + b.getSouthWest().lat() + "," + b.getNorthEast().lat() +
            "&longitude=" + b.getSouthWest().lng() + "," + b.getNorthEast().lng();
        
        var url = "/ajax/clusters.json.php" + bounds;
        //alert(url);
        $.get(url,function(data){
            //alert(data);
        });
    
    },
    
    showBrewery:function(){
    
        // create a base marker icon
        flag = new GIcon();
        flag.image = "finishline.png";
        flag.iconSize = new GSize(40,37);
        flag.iconAnchor = new GPoint(20,20);
        flag.infoWindowAnchor = new GPoint(40,10);
    
        var self = this;
        var geocoder = new GClientGeocoder();
        var address = '830 Varick Street, Utica, NY 13502';
        geocoder.getLatLng(
            address,function(point) {
                if (!point) {
                    var error = "Address could not be located. Please try again later!";
                } else {
                    var marker = new GMarker(point,flag);
                    var info = "<p><strong>Utica Boilermaker Finish Line</strong></p><p>F.X. Matt Brewery</p>";
                    GEvent.addListener(marker,"click",function(){
                        marker.openInfoWindowHtml(info);
                    });
                    self.map.addOverlay(marker);
                    marker.openInfoWindowHtml(info);
                }
            }
        );
    
    },
    
    createMarker:function(map,point,info) {
        var self = this;
        var marker = new GMarker(point,self.flag);
        GEvent.addListener(marker,"click",function(){
            if (info) {
                marker.openInfoWindowHtml(info);
            } else {
                self.map.zoomIn(point);
            }
        });
        map.addOverlay(marker);
    },

    createMarkerAlt:function(map,point,info) {
        var self = this;
        var marker = new GMarker(point,self.flag_alt);
        GEvent.addListener(marker,"click",function(){
            if (info) {
                marker.openInfoWindowHtml(info);
            } else {
                self.map.zoomIn(point);
            }
        });
        map.addOverlay(marker);
    },
    
    showSearch:function(location_id) {
        
        var url = "/ajax/search.php?id="+location_id;    
        $("#searchresults").html("<p>Loading data&#8230;</p>");
        $("#searchresults").load(url,function(){
            enableLinks();
        });

        
    },
    
    zoomRegion:function(state,country,latitude,longitude) {
    
        var self = this;
        //this.map.clearOverlays();
        self.regions = false;
        
        this.map.setCenter(new GLatLng(latitude,longitude),6);
        
        var region = '?state='+state+'&country='+country;
            
        var url = "/ajax/runners.json.php" + region;
        $.get(url,function(data){
            var json = eval("("+data+")");
            //alert(data);
            for (e in json) {
                var place = json[e];
                var point = new GLatLng(place.latitude,place.longitude);
                var info = '<p><strong><big>'+place.address+'</big></strong></p>'
                         + '<strong>Runners:</strong> '+place.runners+' (<a onclick="googlemap.showSearch('+place.id+');return false;" href="/?id='+place.id+'">view runners</a>)</p>';
                self.createMarker(self.map,point,info);
            }
        });
    
    },
    
    checkBoundsOverlap:function() {
        
        var visible = this.map.getBounds();
        var plotted = this.plotted_area;
        
        var w = plotted.getNorthEast().lng() - plotted.getSouthWest().lng();
        var h = plotted.getNorthEast().lat() - plotted.getSouthWest().lat();
        
        var plotted_latmin = plotted.getSouthWest().lat() - h;
        var plotted_latmax = plotted.getNorthEast().lat() + h;
        var plotted_lngmin = plotted.getSouthWest().lng() - w;
        var plotted_lngmax = plotted.getNorthEast().lng() + w;
        
        if (visible.getSouthWest().lat() < plotted_latmin) return false;
        if (visible.getNorthEast().lat() > plotted_latmax) return false;
        if (visible.getSouthWest().lng() < plotted_lngmin) return false;
        if (visible.getNorthEast().lng() > plotted_lngmax) return false;

        return true;
    }
    
}
