ErmJS.Controls.GoogleMap = new Class({
    initialize: function(arguments) {
        this.loadFunctions = [];
        this.mapTarget = arguments.mapTarget;
        this.centrePoint = arguments.centrePoint;
        this.zoom = arguments.zoom;
        this.maximumZoom = arguments.maxZoom;
        this.minimumZoom = arguments.minZoom;
        window.addEvent("domready",this.makeMap.bind(this));
        window.addEvent("unload",function() {
        	GUnload();
        });
        this.BluePin = this.makePin("blue","newpin");
        this.tinyBluePin = this.makeTinyPin("blue","newpin");
        this.RedPin = this.makePin("red","newpin");
        this.BlueHouse = this.makePin("blue","house");
        this.RedHouse = this.makePin("red","house");        
    },
    addEvent: function(stage,func) {
        this.loadFunctions.push(func);
    },
    makeMap: function() {
        
        var mapTypes = G_DEFAULT_MAP_TYPES;
        for(var i = 0; i < mapTypes.length; i++){
	        mapTypes[i].getMaximumResolution = function(latlng){ return this.maximumZoom;}.bind(this);
	        mapTypes[i].getMinimumResolution = function(latlng){ return this.minimumZoom;}.bind(this);
        }

        this.map = new GMap2(this.mapTarget, {
            "mapTypes": mapTypes
        });
        
        GEvent.addListener(this.map, "load", function() {

            //this.CopyrightCheckInstance = this.CopyrightCheck.periodical(100,this);

            this.loadFunctions.each(function(f) {
                f.run();
            });
        }.bind(this));
        this.map.setCenter(new GLatLng(this.centrePoint.Latitude, this.centrePoint.Longitude),this.zoom);
    },
    CopyrightCheck: function() {
        // This is to format the copyright text- in our smaller maps it sometimes runs out of the container, which
        // looks bad. 
        var c = this.map.getCurrentMapType().getCopyrights(this.map.getBounds(),this.map.getZoom());
        
        if (c.length > 0) {
            $clear(this.CopyrightCheckInstance);
            var lookfor = c[0].copyrightTexts[0];
            if (lookfor.split(" ").length > 1) {
                lookfor = lookfor.split(" ")[0];
            }
            var cRight = this.map.getContainer().getLast();
            
            if (cRight != null && cRight.getChildren().length > 0) {
                cRight = cRight.getChildren()[1];
                var containerSize = this.map.getContainer().getSize();
                var copyrightSize = cRight.getParent().getSize();
                if (copyrightSize.x > containerSize.x - 70) {
                    cRight.set("html",cRight.get("html").replace(lookfor,"<br/>" +lookfor));
                }
            }
            
            
        }
    },
    makePin: function(color,tpe) {
	    var baseIcon = new GIcon(G_DEFAULT_ICON);
	    baseIcon.image = "http://www.easyroommate.com/images/buttons/maps/" + color + tpe +".png";
	    baseIcon.shadow = "http://www.easyroommate.com/images/buttons/maps/"+ tpe +"_back.png";
	    if (tpe == "pin") {
		    baseIcon.iconSize = new GSize(23, 42);
		    baseIcon.shadowSize = new GSize(41, 42);
		    baseIcon.iconAnchor = new GPoint(4, 40);
		    baseIcon.imageMap = [0,0 , 23,0 , 23,42 , 0,42];
		    baseIcon.infoWindowAnchor = new GPoint(9, 2);
	    } else if (tpe=="house") {
		    baseIcon.iconSize = new GSize(32, 34);
		    baseIcon.shadowSize = new GSize(47, 32);
		    baseIcon.iconAnchor = new GPoint(17, 33);
		    baseIcon.imageMap = [0,0 , 34,0 , 34,32 , 0,34];
		    baseIcon.infoWindowAnchor = new GPoint(9, 2);
	    } else {
	        baseIcon.iconSize = new GSize(23, 31);
		    baseIcon.shadowSize = new GSize(39, 31);
		    baseIcon.iconAnchor = new GPoint(12, 30);
		    baseIcon.imageMap = [0,0 , 23,0 , 23,31 , 0,31];
		    baseIcon.infoWindowAnchor = new GPoint(9, 2);
	    }
        return new GIcon(baseIcon);
    },
    makeTinyPin: function(color) {
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.image = "http://www.easyroommate.com/images/buttons/maps/" + color + "newpin_small.png";
        baseIcon.shadow = "http://www.easyroommate.com/images/buttons/maps/newpin_small_back.png";
        baseIcon.iconSize = new GSize(16, 22);
		baseIcon.imageMap = [0,0 , 22,0 , 22,16 , 0,16];
        baseIcon.shadowSize = new GSize(28, 22);
        baseIcon.iconAnchor = new GPoint(9, 22);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        return new GIcon(baseIcon);
    },
    getBearingBetweenPoints: function(latlng1,latlng2) {
        var lat1 = latlng1.lat() * Math.PI / 180;
        var lat2 = latlng2.lat() * Math.PI / 180;
        var dLon = (latlng2.lng()-latlng1.lng()) * Math.PI / 180;

        var y = Math.sin(dLon) * Math.cos(lat2);
        var x = Math.cos(lat1)*Math.sin(lat2) -
                Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
        var brng = (Math.atan2(y, x)* 180 / Math.PI) % 360;
        return brng;


    }
});


/* 
 * MooTools and Google Maps confuse each other with the implementation of initialize()
 * in a class, so we have to do this one Moo-less.
 */

ErmJS.Controls.LightMarkers = function() {
//This will the pseudo-marker objects
this.layer = null;
//This will hold the layer DOM object
this.node = null;
}
ErmJS.Controls.LightMarkers.prototype = new GOverlay();
ErmJS.Controls.LightMarkers.prototype.initialize = function(map) {
	this.map = map;
	this.node = new Element("div");
	this.map.getPane(G_MAP_MARKER_PANE).adopt(this.node);
	this.shadowZIndex = this.map.getPane(G_MAP_MARKER_PANE).getStyle("z-index").toInt() + 1;
	this.pinZIndex = this.shadowZIndex + 1;
	this.markers = [];
	this.redraw(true);

};
ErmJS.Controls.LightMarkers.prototype.addMarkers = function(markers) {
	this.markers.extend(markers);
	this.markers.sort(function(a,b){
		return a.point.Latitude - b.point.Latitude
	})
};
ErmJS.Controls.LightMarkers.prototype.redraw= function(force, newMarkers){

	if (force == true || newMarkers != null) {
		var mapSize = this.map.getSize();
		// We're creating some bounds that are twice the size of the map in every direction- this
		// is as far as the user can pan.
		var boundsObj = {
			NorthEast: this.map.fromContainerPixelToLatLng(new GPoint(mapSize.width * 2,0-mapSize.height)),
			SouthWest: this.map.fromContainerPixelToLatLng(new GPoint(0-mapSize.width,mapSize.height * 2))
		};
		var visibleMarkers;
		if (force == true) {
			visibleMarkers = this.markers.filter(function(marker){
				if (marker.point.Latitude <= boundsObj.NorthEast.lat() && marker.point.Latitude >= boundsObj.SouthWest.lat() &&
				marker.point.Longitude >= boundsObj.SouthWest.lng() &&
				marker.point.Longitude <= boundsObj.NorthEast.lng()) {
					return true;
				}
				else {
					return false;
				}
			})
			
		}
		else {
			visibleMarkers = newMarkers;
			visibleMarkers.sort(function(a,b){
				return a.point.Latitude - b.point.Latitude
			})
		}
		var i = visibleMarkers.length;
		var textArray = [];
		while (i--) {
			var divPixel = this.map.fromLatLngToDivPixel(new GLatLng(visibleMarkers[i].point.Latitude, visibleMarkers[i].point.Longitude));
			textArray.push("<div id='" + visibleMarkers[i].id + "' class='lightpin" + visibleMarkers[i].color + "' style='left:" + divPixel.x + "px;top: " + divPixel.y + "px; z-index:" + this.pinZIndex + "'></div>");
			if ($(document.body).hasClass("ie6") == false) {
				textArray.push("<div class='lightpinshadow' style='left:" + divPixel.x + "px;top: " + divPixel.y + "px; z-index:" + this.shadowZIndex + "'></div>");
			}
		}
		if (force == true) {
			this.node.innerHTML = textArray.join('');
		}
		else {
			this.node.innerHTML += textArray.join('');
		}
	}
}
ErmJS.Controls.LightMarkers.prototype.getNode = function() {
	return this.node;
}

