﻿var geocoder;
var maps = [];

function mapinitialize(mapcanvasid, centerlocation, initialzoomlevel)
{   
    //The following coordinates are the US center (by default)
    var myLatlng = new google.maps.LatLng(40.613952, -98.085937);
    var zoomLevel = 4;
    if (initialzoomlevel != "")
    {
        zoomLevel = initialzoomlevel;
    }

    var myOptions = {
        zoom: zoomLevel,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    if (geocoder == null)
    {
        geocoder = new google.maps.Geocoder();
    }

    var map = new google.maps.Map(document.getElementById(mapcanvasid), myOptions);

    //Try center the map on the specified address
    if (centerlocation != "")
    {
        geocoder.geocode({ 'address': centerlocation }, function(results, status)
        {
            if (status == google.maps.GeocoderStatus.OK)
            {
                map.setCenter(results[0].geometry.location);
            }
        });
    }

    maps.push(map);

    return maps.length - 1;
}

function insertMarkerGeocoded(address, currentmapindex)
{
    geocoder.geocode({ 'address': address }, function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            var marker = new google.maps.Marker({
                map: maps[currentmapindex],
                position: results[0].geometry.location,
                animation: google.maps.Animation.DROP
            });

            var addresscontent = "<div class=\"mapinfowindow\">";
            addresscontent += address + " <a target=\"_blank\" href=\"http://maps.google.com/maps?daddr=" + address.replace(" ", "+") + "\">Driving Directions</a>";
            addresscontent += "</div>";

            var infowindow = new google.maps.InfoWindow({
                content: addresscontent
            });

            google.maps.event.addListener(marker, 'click', function()
            {
                infowindow.open(maps[currentmapindex], marker);
            });
        }
        else
        {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}
