(function($, module){

//-------------
// MAPSTRACTION
//-------------

	function addAPI(element, api) {
	    var me = this;
        if (GMap2) {
            if (GBrowserIsCompatible()) {
                this.maps[api] = new GMap2(element);

                GEvent.addListener(this.maps[api], 'click', function(marker,location) {
                    // If the user puts their own Google markers directly on the map
                    // then there is no location and this event should not fire.
                    if ( location ) {
                        me.clickHandler(location.y,location.x,location,me);
                    }
                });

                GEvent.addListener(this.maps[api], 'moveend', function() {
                    me.moveendHandler(me);
                });
                
                this.loaded[this.api] = true;
	            var loadHandlers = this.onload[this.api];
	            while(loadHandlers.length > 0){
		            var fn = loadHandlers.pop();
		            fn();
	            }
            }
            else {
                alert('browser not compatible with Google Maps');
            }
        }
        else {
            alert(api + ' map script not imported');
        }
	}
	
	function setCenterAndZoom(point, zoom) {
        var map = this.maps[this.api];
        map.setCenter(point.toGoogle(), zoom);
	}
	
	function getBounds() {
        var map = this.maps[this.api];
        var ne, sw, nw, se;
        var gbox = map.getBounds();
        sw = gbox.getSouthWest();
        ne = gbox.getNorthEast();
        return new $.BoundingBox(sw.lat(), sw.lng(), ne.lat(), ne.lng());
	}
	
	function addMarker(marker, old) {
	    var map = this.maps[this.api];
        var gpin = marker.toGoogle();
        marker.setChild(gpin);
        map.addOverlay(gpin);
        if (!old) {
            this.markers.push(marker);
        }
    }
    
    function addOverlay(url, autoCenterAndZoom) {
        var map = this.maps[this.api];
        var geoXML = new GGeoXml(url);
        map.addOverlay(geoXML, function() {
            if(autoCenterAndZoom) {
                geoXML.gotoDefaultViewport(map);
            }
        });
    }
    
    // Register
	$.registerModule(module, {
		addAPI              : addAPI,
		setCenterAndZoom    : setCenterAndZoom,
		getBounds           : getBounds,
		addMarker           : addMarker,
		addOverlay          : addOverlay
	});

})(mxn, 'mapstraction.google');