(function(){

    if(!window['MAP'])
    {
        alert("Include the MAP namespace and library first of all!");
    }
    
    function storeMarkerList(node, theMap) {
        if(!(node = MAP.$(node))) {
            return;
        }
        
        var theMarkers = new Array();
        
        var makeInfoWindow = function (marker, store, stores) {
            var node = MAP.getElementsByClassName('vcard', 'div', store)[0];
            var nodeClone = node.cloneNode(true);
            MAP.addClassName(node, 'collapseNode');
            MAP.addClassName(nodeClone, 'googleMarker');
            google.maps.Event.addListener(marker,'click',function() {
                marker.openInfoWindow(nodeClone);
            });
            MAP.addClassName(node,'clickable');
            MAP.addEvent(store,'click',function() {
                for(i=0 ; i < stores.length; i++ ) {
                    var thisStore = stores[i];
                    if (MAP.hasClassName(thisStore.firstChild, 'vcard')) {
                        var aNode = MAP.getElementsByClassName('vcard', 'div', thisStore)[0];
                        if (!MAP.hasClassName(aNode, 'collapseNode')){
                            MAP.addClassName(aNode, 'collapseNode');
                        }
                    }
                }
                MAP.removeClassName(node, 'collapseNode');
                google.maps.Event.trigger(marker,'click');
                theMap.setZoom(14);
            });
        };

        var processStoreListUL = function (node) {
            if (!(node = MAP.$(node)))
            {
                return;
            }
            
            for(var i = 0; i < node.childNodes.length; i++)
            {
                if (MAP.hasClassName(node.childNodes[i].firstChild, 'vcard')) {
                    // This assumes all the elements exist and doesn't do any error checking
                    var lattitude = MAP.getElementsByClassName('latitude', 'abbr', node.childNodes[i])[0].getAttribute('title');
                    var longitude = MAP.getElementsByClassName('longitude', 'abbr', node.childNodes[i])[0].getAttribute('title');
                    
                    // Create and add the marker to the map
                    // Create our "tiny" marker icon
                    var myIcon = new GIcon(G_DEFAULT_ICON);
                    var marker = new google.maps.Marker(new google.maps.LatLng(lattitude, longitude), { icon:myIcon });
                    makeInfoWindow(marker, node.childNodes[i], node.childNodes);
                    theMarkers[theMarkers.length] = marker;
                }
                
            }
        };
        
        var initializeList = function (node){
            var exp = new RegExp(/(.*)Map/);
            var result = node.id.match(exp);
            if (!result) {
                return;
            }
            var newID = result[1] + 'List';
            processStoreListUL(MAP.getElementsByClassName('storeList', 'ul', MAP.$(newID))[0]);
            return;
        };  
        
        this.addMarkersToMap = function(){
            for(var i = 0; i < theMarkers.length; i++)
            {
                theMap.addOverlay(theMarkers[i]);
            }
            return;
        };  
        
        initializeList(node);
        return;
    }
    
    function countryMap (node)
    {
        if(!(node = MAP.$(node))) {
            return;
        }
        
        var theMap;
        var mapCentre;
        var initialZoom;
        var theMarkers;
        
        var removeBackground= function(){
            node.style.backgroundImage = '';
            return;
        };
        
        var setCentreAndZoom = function(node) {
            var exp = new RegExp(/.*center=([\+|-]?\d*\.?\d*),([\+|-]?\d*\.?\d*).*zoom=(\d*)/);
            var result;
            if(result = node.style.backgroundImage.match(exp)){
                mapCentre = new GLatLng(result[1], result[2]);
                initialZoom = parseInt(result[3]);
                theMap.setCenter(mapCentre, initialZoom);
            }
            return;
            
        };
        
        var addMarkers = function(node) {
            theMarkers = new storeMarkerList(node, theMap);
            theMarkers.addMarkersToMap();
            return;
        };
        
        var initialize = function(node) {
            theMap = new GMap2(node, {logoPassive: true});    
            setCentreAndZoom(node);
            theMap.enableScrollWheelZoom();            
            theMap.addControl(new GLargeMapControl());
            theMap.addControl(new GScaleControl());
            theMap.addControl(new GMapTypeControl());
            
            addMarkers(node);
            
            setTimeout('document.getElementById("' + node.id + '").style.backgroundImage="";', 1000);
        };
        
        initialize(node);
        return;
    }    
 
    function maps(container){   
    
        var activate = function (container) {
            if (!(container = MAP.$(container))) {
                return;
            } 
            
            if (!GBrowserIsCompatible())
            {
                return;
            }  
            
            var countryMaps = new Array;
            var mapNodes = MAP.getElementsByClassName('aGoogleMap','div',container);
            for(var i = 0; i < mapNodes.length; i++)
            {
                countryMaps[i] = new countryMap(mapNodes[i]);
            }
            return;     
        };
        
        
        activate(container);
        return;
    }
    
    window['MAP']['maps'] = maps;    

})();

function MapsAPILoaded () {
    var theMaps = new MAP.maps(MAP.$('stores'));
    return;
};

MAP.addEvent(window,'load',function(W3CEvent) {
    var apiKey = siteGoogleMapsAPIKey;
    
    if (!apiKey || apiKey == '')
    {
        alert('Define the apiKey first of all!');
        return;
    }
    var googleMapsScript = document.createElement('script');
    googleMapsScript.setAttribute('src', 'http://maps.google.com/maps?file=api&v=2.x&async=2&key=' + apiKey + '&callback=MapsAPILoaded');
    googleMapsScript.setAttribute('type', 'text/javascript');
    document.documentElement.firstChild.appendChild(googleMapsScript);

 return;
});

