google.load("maps", "2");

MAP.addEvent(window,'load',function() {

      if (google.maps.BrowserIsCompatible()) {

        // Modify the style to show the map
        MAP.addClassName(MAP.$('map'), 'googleMap');
        MAP.addClassName(MAP.$('stores'), 'googleStores');

        // Instantiate the Google map API (version 2)
        var map = new google.maps.Map2(document.getElementById("map"));

        // Instantiate a new latitude and longitude coordinate
        var location = new google.maps.LatLng(54.8007,-4.4385);

        // Set the center of the map to location with a zoom level
        map.setCenter(location, 5);

        // Add a zoom/pan and type control
        map.addControl(new google.maps.LargeMapControl());
        map.addControl(new google.maps.MapTypeControl());

        // Retrieve all store <li> elements
        var stores = MAP.$('stores').getElementsByTagName('li');
        
        // Use a function to maintain the proper variable 
        // scope for the info window information
        function makeInfoWindow(marker,store) {
            var node = MAP.getElementsByClassName('vcard', 'div', store)[0].cloneNode(true);
            google.maps.Event.addListener(marker,'click',function() {
                marker.openInfoWindow(node);
            });
            MAP.addEvent(store,'click',function() {
                google.maps.Event.trigger(marker,'click');
            });
            MAP.addEvent(store,'mouseover',function() {
                MAP.addClassName(store,'hover');
            });
            MAP.addEvent(store,'mouseout',function() {
                MAP.removeClassName(store,'hover');
            });
            
        }
        
        // Loop through each store and retrieve the 
        // lattitude and longitude from the microformat
        for(i=0 ; (store = stores[i]) ; i++ ) {
            
            // This assumes all the elements exist and doesn't do any error checking
            var lattitude = null;
            if (MAP.getElementsByClassName('latitude', 'abbr', store)[0])
                var lattitude = MAP.getElementsByClassName('latitude', 'abbr', store)[0].getAttribute('title');
                
            var longitude = null;
            if (MAP.getElementsByClassName('longitude', 'abbr', store)[0])
                longitude = MAP.getElementsByClassName('longitude', 'abbr', store)[0].getAttribute('title');
            
            if (lattitude && longitude)
            {
                // Create and add the marker to the map
                var marker = new google.maps.Marker(new google.maps.LatLng(lattitude, longitude));
                makeInfoWindow(marker,store);
                map.addOverlay(marker); 
            }
        }
      }
});

MAP.addEvent(window,'unload',google.maps.Unload);

