﻿function MapControl(elementId, feedUrl, markerIconUrl)
{
    this.element = document.getElementById(elementId);
    this.feedUrl = feedUrl;
    this.markerIcon = markerIconUrl;
    this.icon = null;
    this.initialize();
}

MapControl.prototype = {

    initialize: function() {

        this.icon = new GIcon();
        this.icon.image = this.markerIcon;
        this.icon.iconSize = new GSize(16, 16);
        this.icon.iconAnchor = new GPoint(16, 16);

        map = new GMap2(document.getElementById("map"));
        map.setCenter(new google.maps.LatLng(0, 0), 2);
        map.addControl(new GLargeMapControl3D());
        map.addControl(new GNavLabelControl());
        map.setMapType(G_PHYSICAL_MAP);

        var self = this;
        GDownloadUrl(this.feedUrl, function(data) { self.parseData.call(self, data); });
    },

    parseData: function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("place");
        for (var i = 0; i < markers.length; i++) {
            var descriptionNode = markers[i].getElementsByTagName("description")[0];
            var description = this.getNodeText(descriptionNode);
            var title = markers[i].getAttribute("title");
            var link = markers[i].getAttribute("link");
            var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
            var markup = '<h2>' + title + '</h2><p style="font-weight: normal;">' + description + '</p>';
            map.addOverlay(this.createMarker(latlng, link, markup));
        }

    },

    createMarker: function(point, link, markup) {
        var marker = new LabeledMarker(point, { labelText: markup, icon: this.icon });
        GEvent.addListener(marker, "click", function() { window.location = link; });
        return marker;
    },

    getNodeText: function(node) {
        var s = '';
        for (var nodeIndex = 0; nodeIndex < node.childNodes.length; nodeIndex++) {
            var childNode = node.childNodes[nodeIndex];
            if (childNode.nodeType == 3)
                s += childNode.nodeValue;
        }
        return s;
    }
}

