/**
	name			gvGMap
	type			class
	description		represents a Google Maps widget
**/
var gvGMap = Class.create();
gvGMap.prototype = {
	initialize: function(obj, pars, input) {
		this.pars = pars;
		this.map = new GMap2(obj);
		this.map.setCenter(new GLatLng(this.pars["lat"], this.pars["lng"]), this.pars["zoom"], this.pars["mode"]);
		
		if (this.pars["shownav"]) this.map.addControl(new GSmallMapControl());
		if (this.pars["showmode"]) this.map.addControl(new GMapTypeControl());
		
		this.inputfield = input;
		this.inputfield.style.display = "none";
		
		this.marker = null;
		
		if (this.inputfield.value != "") {
			var pars = this.inputfield.value.split(",");
			if (pars && pars.length == 2) {
				this.marker = new GMarker(new GLatLng(pars[0], pars[1]), {draggable: true, bouncy: false});
				this.map.addOverlay(this.marker);
				this.map.setCenter(new GLatLng(pars[0], pars[1]));
			}
		}
		
		if (this.marker == null) {
			this.inputfield.value = "";
		}
		
		GEvent.bind(this.map, "click", this, this.handleClick);
	}, 
	
	handleClick: function(marker, point) {
		if (marker) {
			this.map.removeOverlay(marker);
			this.marker = null;
			this.inputfield.value = "";
		}
		
		if (this.marker) {
			this.map.removeOverlay(this.marker);
		}
		
		this.marker = new GMarker(point, {draggable: true, bouncy: false});
		this.map.addOverlay(this.marker);
		this.inputfield.value = this.marker.getPoint().lat() + "," + this.marker.getPoint().lng();
	}
}

/**
	name			loadGoogleMap
	type			function
	params			-
	description		adds Google Maps widget to the page in each div with CSS class "gMap". This function is dependent on the 
					Google Maps API.
**/
function loadGoogleMaps() {
	if (GBrowserIsCompatible()) {
		var el = document.getElementsByClassName("gmap");
	
		el.each(function(node) {
			var t = document.getElementsByClassName("gmap_flags", node);
			
			if (t[0] && t[0].innerHTML) {
				var pars;
				eval("pars = " + t[0].innerHTML);
				
				var w = $(node.id.substring(3, node.id.length));
				if (pars && w) {
					var m = new gvGMap(node, pars, w);
				}
			}
		});
	}
}

/**
	name			loadHandlers
	type			function
	params			-
	description		searches the DOM tree for elements with CSS class "gvFlag". The innerHTML of these elements 
					is used to see if a specific javascript handler should be loaded.
**/
function loadHandlers() {
	var el = document.getElementsByClassName("gvflag");
	
	el.each(function(node) {
		if (node.innerHTML == "GV_LOADFORMGMAPS") { //load Google maps for FormDesigner
			Event.observe(window, "unload", GUnload, false);
			loadGoogleMaps();
		}
	});	
}

Event.observe(window, "load", loadHandlers, false);

Event.observe(window, "load", styleSwitchLoad, false);
Event.observe(window, "unload", styleSwitchUnload, false);