/*jslint browser:true */
/*globals jQuery $ google LatLonPoint Marker Mapstraction */

google.load("maps", "2.x");

var Map = {
    
    locations: [],
    controls: { pan: true, zoom: 'small' },
    
    initialize: function() {

        // load locations
        $('#locations li').map(function(i, location) {
            Map.addLocation(location);
        });

        // then draw the map
        Map.draw();

    },

    addLocation: function(locationTag) {
        var location = {
            latitude: parseFloat($(locationTag).children('.latitude').html()),
            longitude: parseFloat($(locationTag).children('.longitude').html()),
            content: $(locationTag).children('.content').html()
        };
        location.point = new LatLonPoint(location.latitude, location.longitude);
        location.marker = new Marker(location.point);
        this.locations.push(location);
    },

    draw: function() {
        var i;
        if (google.maps.BrowserIsCompatible()) {
            this.map = new Mapstraction($('#map')[0], 'google');
            this.map.addControls(this.controls);
            for (i = 0; i < this.locations.length; i++) {
                this.drawLocation(this.locations[i]);
            }
            this.map.autoCenterAndZoom();
        }
    },

    drawLocation: function(location) {
        if (location.content && location.content.replace(/^\s+|\s+$/g, '').length > 0) {
            location.marker.setInfoBubble(location.content);
        }
        this.map.addMarker(location.marker);
    }

};

$(document).ready(function() {
    setTimeout(Map.initialize, 3000);
    $(document.body).unload(function() { google.maps.Unload(); });
});
