function Legend(list)
{
    this.list = list;
    this.maxNumber = 1;
    this.numbers = {};

    this.hasLabel = function(label) {
        return true && this.numbers[label];
    }

    this.labelIndex = function(label) {
        return this.numbers[label];
    }

    this.addLabel = function(label)
    {
        if (this.hasLabel(label))
            return;
        this.numbers[label] = this.maxNumber++;
        this.list.appendChild(new Element('li', {
            'class' : 'icon' + this.numbers[label],
            'html'  : label
        }));
    }
}

function Mapper(map, coords, legend)
{
    this.map = map;
    this.coords = coords;
    this.legend = legend;

    this.addPlace = function(place)
    {
        var title = place.getAttribute('data-label') || place.innerHTML;
        if (!title || !this.coords[title])
            return;
        this.legend.addLabel(title);
        var iconIndex = this.legend.labelIndex(title);
        place.addClass('icon' + iconIndex);
        map.addPlaceMarker({
            index: iconIndex,
            center: this.coords[title],
            title: title
        });
    }
}

function Map(canvas)
{
    var classes = {
        closeup: { zoom: 14, center: [49.196312, 16.603176] },
        context: { zoom:  7, center: [49.100000, 17.100000] }
    };
    var mapClass = canvas.getAttribute('data-class') || 'closeup';
    var settings = classes[mapClass];
    this.options = {
        zoom: settings.zoom,
        center: new google.maps.LatLng(settings.center[0], settings.center[1]),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false
    };
    this.gmap = new google.maps.Map(canvas, this.options);

    this.addPlaceMarker = function(options)
    {
        var map = this.gmap;
        var marker = new google.maps.Marker({
            icon: "/img/markers/" + options.index + '.png',
            title: options.title,
            position: new google.maps.LatLng(options.center[0], options.center[1]),
            map: map
        });
        google.maps.event.addListener(marker, 'click', function() {
            map.setCenter(marker.getPosition());
            map.setZoom(16);
        });
    }
}

window.addEvent('domready', function() {
    new Asset.javascript('/code/coords.js', {
        onload: function() {
            // Prevents a double-load event in Opera.
            if (window.mapLoaded)
                return;
            var map = new Map($('canvas'));
            var legend = new Legend($('legend'));
            var mapper = new Mapper(map, window.coords, legend);
            $$('span.mapped').each(function(place) {
                mapper.addPlace(place);
            });
            window.mapLoaded = true;
        }
    });
});
