﻿var geocoder;
var map = [];
var infoWindows = [];

function initializeMap(map_id, zoom, panable, zoomable, enableStreetView, enableMapType) {
    geocoder = new google.maps.Geocoder();
    var stockholm = new google.maps.LatLng(59.32522, 18.07002);
    var myOptions = {
        zoom: zoom,
        draggable: panable,
        panControl: panable,
        zoomControl: zoomable,
        scrollwheel: zoomable,
        streetViewControl: enableStreetView,
        mapTypeControl: enableMapType,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: stockholm
    };
    map[map_id] = new google.maps.Map(document.getElementById(map_id), myOptions);
    infoWindows[map_id] = [];
}

function showAddress(map_id, marker_id, address, title, body, centerAt) {
    geocoder.geocode({ 'address': address },
        function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                addMarker(map_id, marker_id, results[0].geometry.location, title, body);
                if (centerAt) {
                    centerAtMarker(map_id, marker_id);
                }
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        }
    );
}

function centerAtMarker(map_id, marker_id) {
    var infoWindow = infoWindows[map_id][marker_id];
    map[map_id].setCenter(infoWindow.getPosition());
}

function addMarker(map_id, marker_id, position, title, body) {

    var marker = new google.maps.Marker({
        position: position,
        map: map[map_id],
        title: title
    });

    infoWindows[map_id][marker_id] = new google.maps.InfoWindow({
        content: body,
        position: position
    });

    google.maps.event.addListener(marker, 'click', function () {
        openInfoWindow(map_id, marker_id);
    });

}

function openInfoWindow(map_id, marker_id) {
    for (var loop_id in infoWindows[map_id]) {
        infoWindows[map_id][loop_id].close();
    }
    if (map[map_id] && infoWindows[map_id][marker_id]) infoWindows[map_id][marker_id].open(map[map_id]);
}

