google.load("maps", "2.x");

$(document).ready(function() {
    var map = new google.maps.Map2(document.getElementById("map"));
    var bounds = new google.maps.LatLngBounds();
    map.getInfoWindow();
    
    var bluePin = new google.maps.Icon(google.maps.DEFAULT_ICON);
    bluePin.image = "/lib/images/common/blue.png";
    bluePin.iconSize = new google.maps.Size(40, 34);
    bluePin.shadow = "";
    var greenPin = new google.maps.Icon(bluePin);
    greenPin.image = "/lib/images/common/green.png";
    
    var pins = { 'blue': bluePin, 'green': greenPin };
    
    $("#locationsDir > a").each(function() {
        var lat = $(this).next().find(".lat").html(), lng = $(this).next().find(".lng").html();
        var point = new google.maps.LatLng(lat, lng);
        bounds.extend(point);
        map.setCenter(point);
        var infoHTML = $(this).next().html();
        var marker = new google.maps.Marker(
            point,
            pins[ $(this).next().find(".pin_type").html() ]
        );
        var openInfoHandler = function() {
            map.openInfoWindowHtml(point, infoHTML);
            
            var container = $(map.getInfoWindow().getContentContainers()[0]);
            container.find(".directionsLink a").click(function() {
                container.find(".directionsLink").hide();
                container.find(".directions").show();
            });
            container.find(".directions input[type=button]").click(function() {
                var fromAddr = container.find(".directions input[type=text]").val();
                var toAddr = container.find(".address").html() + ", " 
                            + container.find(".city").html() + " "
                            + container.find(".state").html() + " "
                            + container.find(".zip").html();
                var url = 'http://maps.google.com/maps?f=q&hl=en&q=from%20' + fromAddr + '%20to%20' + toAddr;
                console.log(url);
                document.location.href=url;
            });
        };
        $(this).click(openInfoHandler);
        google.maps.Event.addListener(marker, 'click', openInfoHandler);
        map.addOverlay(marker);
    });
    
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
});