if (Object.isUndefined(GoogleMaps)) { var GoogleMaps = {conf:false} };
GoogleMaps.map;
GoogleMaps.markerIcon;
GoogleMaps.fromAddress;
GoogleMaps.name;
GoogleMaps.address;
GoogleMaps.startLat;
GoogleMaps.startLng;
GoogleMaps.isLoaded = false;
GoogleMaps.startMarker = false;
GoogleMaps.mapControls = {};
GoogleMaps.editStarted = false;
PbLib.module.load('loader');

GoogleMaps.addMarker = function (markerInfo, routeInfo)
{
	GoogleMaps.map.addOverlay(GoogleMaps.createMarker(new GLatLng(markerInfo.lat, markerInfo.lng), markerInfo, routeInfo));
}

GoogleMaps.selectRelation = function ()
{
	var info = GoogleMaps.currentMessage;
	var openerWindow = PbLib.dialog.getOpener();
	var element = openerWindow.$(GoogleMaps.conf.elementid);

	if (openerWindow.$(element.id + '-inner') == undefined) {
		element.up('div')
				.appendChild(new Element('ul', {'id': element.id + '-inner', 'style': 'list-style: none; margin-left: 0;'}))
				.appendChild(new Element('li').update(info.searchrow.infowindow))
				.appendChild(new Element('input', {type: 'hidden', name: 'formdata[' + element.id + ']', value: info.relationid}));
	} else {
		var input = openerWindow.$(element.id + '-inner').down('input');

		if (input.value != info.relationid) {
			input.value = info.relationid;
			input.up('li').update(info.searchrow.infowindow).appendChild(input);
		}
	}

	PbLib.destroyDialog();
}

GoogleMaps.createMarker = function (point, markerInfo, routeInfo)
{
	var markerOptions = {};
	if (GoogleMaps.markerIcon) markerOptions.icon = GoogleMaps.markerIcon;

	var marker = new GMarker(point, markerOptions);
	marker.value = markerInfo.name;

	if (GoogleMaps.conf.showinfowindow != 0) {
		GEvent.addListener(marker, "click", function() {
			GoogleMaps.showInfoWindow(point, markerInfo, routeInfo);
		});
	}

	return marker;
}

GoogleMaps.removeMarker = function (marker)
{
	return GoogleMaps.map.removeOverlay(marker);
}

GoogleMaps.setNewCenter = function (point, zoomlevel, maptype)
{
	return GoogleMaps.map.setCenter(point, parseInt(zoomlevel), maptype);
}

GoogleMaps.wheelevent = function(e)
{
	var event = e || window.event;
	if (event.preventDefault){
		event.preventDefault()
	}
	event.returnValue = false;
}

GoogleMaps.calculateRoute = function(endLat, endLng, name, address)
{
	PbLib.startLoader('');
	GoogleMaps.map.closeInfoWindow();
	GoogleMaps.name = unescape(name);
	GoogleMaps.address = address;
	GoogleMaps.direction.load("from: " + GoogleMaps.startLat + ',' + GoogleMaps.startLng + " to: " + endLat + ',' + endLng,
								{"locale": $F('country'), getPolyline:true, getSteps:true});
	PbLib.stopLoader();
}

GoogleMaps.handleErrors = function()
{
	if (GoogleMaps.direction.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + GoogleMaps.direction.getStatus().code);
	} else if (GoogleMaps.direction.getStatus().code == G_GEO_SERVER_ERROR) {
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + GoogleMaps.direction.getStatus().code);
	} else if (GoogleMaps.direction.getStatus().code == G_GEO_MISSING_QUERY) {
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + GoogleMaps.direction.getStatus().code);
	} else if (GoogleMaps.direction.getStatus().code == G_GEO_BAD_KEY) {
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + GoogleMaps.direction.getStatus().code);
	} else if (GoogleMaps.direction.getStatus().code == G_GEO_BAD_REQUEST) {
		alert("A directions request could not be successfully parsed.\n Error code: " + GoogleMaps.direction.getStatus().code);
	} else {
		alert("An unknown error occurred.");
	}
}

GoogleMaps.copyPolyline = function(polyLine)
{
	var pLinePoints = Array();
	for (var n = 0; n < polyLine.getVertexCount(); n++) {
		pLinePoints.push(polyLine.getVertex(n));
	}
	return new GPolyline(pLinePoints, '#F7098A');
}

GoogleMaps.handleLoad = function()
{
	PbLib.startLoader('');
	if (GoogleMaps.directionPoly) GoogleMaps.map.removeOverlay(GoogleMaps.directionPoly);
	GoogleMaps.directionPoly = GoogleMaps.direction.getPolyline();
	GoogleMaps.setNewCenter(GoogleMaps.directionPoly.getBounds().getCenter(), GoogleMaps.map.getBoundsZoomLevel(GoogleMaps.directionPoly.getBounds()));
	GoogleMaps.map.addOverlay(GoogleMaps.directionPoly);
	if (GoogleMaps.conf.routeoptions > 1) {
		$('routebox').childElements().each(function(child){child.remove();})
		$('routebox').setStyle({'height': (GoogleMaps.conf.height - $('tablinks_informationwindow').getHeight()) + 'px'})
			.show()
			.update(table = new Element('table', {'class':'routedescription'}).update(tbody = new Element('tbody')))
			.scrollTop = 0;
		var route = GoogleMaps.direction.getRoute(0);

		var editAddress = function(buttonElement)
			{
				var oringinalAddress = $('routestart').innerHTML;
				$('routestart').update(new Element('input', {'type': 'text', 'value': oringinalAddress, 'id': 'routestart_edit'}));
				buttonElement.insert({'before': new Element('img', {'src': PbLib.getNewURI('ui/uibase/icons/16/view.png')})
						.observe('click', function(event)
						{
							GoogleMaps.handleEdit();
						})
					});
				$('routestart_edit').insert({'before': new Element('text').update(PbLib.g('Start address:'))});
				$('routestart_edit').observe('change', function(event)
				{
					GoogleMaps.handleEdit();
				});
				$('routestart_edit').focus();
				Event.observe(window, 'keydown', function (event)
				{
					if (event.keyCode == 13) {
						GoogleMaps.handleEdit();
					}
				});
				buttonElement.hide();
			};

		tbody.insert({top: new Element('tr', {'class': 'fromaddress'})
				.insert(new Element('th').update(new Element('img', {'src': PbLib.getNewURI('files/mod_googlemaps/icons/flag_green16.png')})))
				.insert(new Element('th', {'id': 'routestart'}).update(route.getStartGeocode().address))
				.insert(new Element('th', {'class': 'print edit', 'id': 'buttonbox'})
					.insert((editButton = new Element('img', {'src': PbLib.getNewURI('ui/uibase/icons/16/edit.png')}))
						.observe("click", function(event) { editAddress(event.element()); }))
					.insert(new Element('img', {'src': PbLib.getNewURI('ui/uibase/icons/16/printer.png')})
						.observe("click", function(){PbLib.createDialog('http://maps.google.nl/maps?saddr=' + route.getStep(0).getLatLng().toUrlValue() + '&daddr=' + route.getEndLatLng().toUrlValue() + '&f=d&ie=UTF8&t=p&pw=2', '75%', '75%');})))})
			.insert({bottom: new Element('tr').insert(new Element('td', {'colspan':'3'}).update(route.getSummaryHtml()))});

		editAddress(editButton);

		var numberOfSteps = route.getNumSteps();
		for (var i = 0; i < route.getNumSteps(); i++) {
			step = route.getStep(i);
			tbody.insert({bottom: row = new Element('tr', {'class': 'clickable'})
				.insert(new Element('td').update(i + 1))
				.insert(new Element('td').update(step.getDescriptionHtml()))
				.insert(new Element('td', {'class':'distance'}).update(step.getDistance().html))
			});
			if (i == (numberOfSteps - 1)) row.addClassName('last');
			(function (myStep, stepNumber) {
				Event.observe(row, 'click', function()
				{
					PbLib.startLoader('');
					GoogleMaps.map.closeInfoWindow();

					GoogleMaps.map.openInfoWindow(
						myStep.getLatLng(),
						'<div id="detailmap" style="width:' + (GoogleMaps.conf.detailmapwidth ? GoogleMaps.conf.detailmapwidth : 250) + 'px; height:' + (GoogleMaps.conf.detailmapheight ? GoogleMaps.conf.detailmapheight : 250) + 'px;"></div>'
					);

					var detailmap = new GMap2($("detailmap"));
					var CopyrightDiv = $("detailmap").firstChild.nextSibling;
					var CopyrightImg = $("detailmap").firstChild.nextSibling.nextSibling;
					CopyrightDiv.style.display = "none";
					CopyrightImg.style.display = "none";

					detailmap.addControl(new GSmallMapControl());
					detailmap.setCenter(myStep.getLatLng(), detailmap.getBoundsZoomLevel(new GLatLngBounds(myStep.getLatLng(), myStep.getLatLng())));

					detailmap.addOverlay(GoogleMaps.copyPolyline(GoogleMaps.directionPoly));
					PbLib.stopLoader();
				});
			})(step, (i + 1));
		}
		tbody.insert({bottom: new Element('tr', {'class':'toaddress'})
			.insert(new Element('th').update(new Element('img', {'src':GoogleMaps.conf.icon.url})))
			.insert(new Element('th', {'colSpan':'2'}).update(GoogleMaps.name +  '<br />' + GoogleMaps.address))
		});
		$('tablinks_informationwindow_route').show();
		showTabinformationwindow('route');
	}
	PbLib.stopLoader();
}

GoogleMaps.handleEdit = function(e)
{
	if (!GoogleMaps.editStarted) {
		PbLib.startLoader('');
		GoogleMaps.editStarted = true;
		var address = $F('routestart_edit');
		$('routestart').update(address);
		$('buttonbox').down().remove();
		$('buttonbox').down().show();
		new Ajax.Request(PbLib.getNewURI('l/googlemaps/getcoordinates'), {
			'asynchronous': false,
			'parameters': {
							'name': address,
							'country': $F('country')
						},
			'onSuccess': function (response)
			{
				response = response.responseText.evalJSON();
				var route = GoogleMaps.direction.getRoute(0);
				var endLat = route.getEndGeocode().Point.coordinates[1];
				var endLng = route.getEndGeocode().Point.coordinates[0];
				GoogleMaps.startMarker.setLatLng(new GLatLng(response.lat, response.lng));
				GoogleMaps.startLat = response.lat;
				GoogleMaps.startLng = response.lng;
				GoogleMaps.calculateRoute(endLat, endLng, escape(GoogleMaps.name), GoogleMaps.address);
				PbLib.stopLoader();
				Event.stopObserving(window, 'keydown');
				GoogleMaps.editStarted = false;
			}
		});
		PbLib.stopLoader();
	}
	GoogleMaps.editStarted = false;
}

GoogleMaps.checkOverview = function()
{
	if (GoogleMaps.mapControls.goverviewmapcontrol.getOverviewMap()) {
		setTimeout("GoogleMaps.mapControls.goverviewmapcontrol.getOverviewMap().setMapType(eval(GoogleMaps.conf.defaultmaptype))", 5);
	} else {
		setTimeout("GoogleMaps.checkOverview()", 10);
	}
}

GoogleMaps.prepair = function ()
{
	var relationMap = $("googlemaps");
	if (GBrowserIsCompatible()) {
		if (!GoogleMaps.conf.defaultnotvisible) {
			GoogleMaps.map = new GMap2(relationMap);
			relationMap.setStyle({'overflow':'hidden'});
			if (GoogleMaps.conf.maptypecontrol == 1) {
				GoogleMaps.map.addControl(new GMapTypeControl());
			} else if (GoogleMaps.conf.maptypecontrol == 2) {
				GoogleMaps.map.addControl(new GHierarchicalMapTypeControl());
			}
			if (GoogleMaps.conf.zoomcontrol == 1) {
				GoogleMaps.map.addControl(new GSmallMapControl());
			} else if (GoogleMaps.conf.zoomcontrol == 2) {
				GoogleMaps.map.addControl(new GLargeMapControl());
			}
			if (GoogleMaps.conf.overviewmapcontrol) {
				GoogleMaps.mapControls.goverviewmapcontrol = new GOverviewMapControl();
				GoogleMaps.map.addControl(GoogleMaps.mapControls.goverviewmapcontrol);
				setTimeout("GoogleMaps.checkOverview()", 10);
			}
			if (GoogleMaps.conf.scalecontrol) {
				GoogleMaps.map.addControl(new GScaleControl());
			}
			if (!GoogleMaps.conf.draggable && !GoogleMaps.conf.doubleclick && !GoogleMaps.conf.overviewmapcontrol) {
				GoogleMaps.map.disableDragging();
			} else if (!GoogleMaps.conf.draggable) {
				GEvent.addListener(GoogleMaps.map, "dragstart", function(){
					GoogleMaps.currentPosition = GoogleMaps.map.getCenter();
					GoogleMaps.currentZoomlevel = GoogleMaps.map.getZoom();
				});
				GEvent.addListener(GoogleMaps.map, "dragend", function(){
					GoogleMaps.setNewCenter(GoogleMaps.currentPosition, GoogleMaps.currentZoomlevel);
				});
			}
			if (GoogleMaps.conf.doubleclick) {
				GoogleMaps.map.enableDoubleClickZoom();
			} else {
				GoogleMaps.map.disableDoubleClickZoom();
			}
			if (!GoogleMaps.conf.showinfowindow) {
				GoogleMaps.map.disableInfoWindow();
			}
			GoogleMaps.markerIcon = new GIcon();
			if (!GoogleMaps.conf.icon) {
				GoogleMaps.conf.icon = {
					url : PbLib.getNewURI('files/mod_googlemaps') + '/img/icon_gmap_procurios.png',
					width : 17,
					height : 20
				};
			}
			if (GoogleMaps.conf.icon) {
				if (GoogleMaps.conf.icon.url && GoogleMaps.conf.icon.width && GoogleMaps.conf.icon.height) {
					GoogleMaps.markerIcon.image = GoogleMaps.conf.icon.url;
					if (GoogleMaps.conf.shadow) {
						GoogleMaps.markerIcon.shadow = GoogleMaps.conf.shadow.url;
						GoogleMaps.markerIcon.shadowSize = new GSize(GoogleMaps.conf.shadow.width, GoogleMaps.conf.shadow.height);
					}

					GoogleMaps.markerIcon.iconSize = new GSize(GoogleMaps.conf.icon.width, GoogleMaps.conf.icon.height);
					if (GoogleMaps.conf.anchorpoint) {
						if (GoogleMaps.conf.anchorpoint == 'centre') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint((GoogleMaps.conf.icon.width / 2), (GoogleMaps.conf.icon.height / 2));
						} else if (GoogleMaps.conf.anchorpoint == 'topleft') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint(0, 0);
						} else if (GoogleMaps.conf.anchorpoint == 'leftcentre') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint(0, (GoogleMaps.conf.icon.height / 2));
						} else if (GoogleMaps.conf.anchorpoint == 'bottomleft') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint(0, GoogleMaps.conf.icon.height);
						} else if (GoogleMaps.conf.anchorpoint == 'bottomcentre') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint((GoogleMaps.conf.icon.width / 2), GoogleMaps.conf.icon.height);
						} else if (GoogleMaps.conf.anchorpoint == 'bottomright') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint(GoogleMaps.conf.icon.width, GoogleMaps.conf.icon.height);
						} else if (GoogleMaps.conf.anchorpoint == 'rightcentre') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint(GoogleMaps.conf.icon.width, (GoogleMaps.conf.icon.height / 2));
						} else if (GoogleMaps.conf.anchorpoint == 'topright') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint(GoogleMaps.conf.icon.width, 0);
						} else if (GoogleMaps.conf.anchorpoint == 'topcentre') {
							GoogleMaps.markerIcon.iconAnchor = new GPoint((GoogleMaps.conf.icon.width / 2), 0);
						}
					}
				}
			}
			if (GoogleMaps.conf.scrollwheelzoom) {
				GoogleMaps.map.enableScrollWheelZoom();
				GEvent.addDomListener(GoogleMaps.map.getContainer(), "DOMMouseScroll", GoogleMaps.wheelevent);
				GoogleMaps.map.getContainer().onmousewheel = GoogleMaps.wheelevent;
			}
			if (GoogleMaps.conf.routeoptions > 0) {
				if (!GoogleMaps.direction) {
					GoogleMaps.direction = new GDirections();
					GoogleMaps.directionPoly;
					GEvent.addListener(GoogleMaps.direction, "error", GoogleMaps.handleErrors);
					GEvent.addListener(GoogleMaps.direction, "load", GoogleMaps.handleLoad);
				}
			}
			GoogleMaps.setNewCenter(new GLatLng(GoogleMaps.conf.lat, GoogleMaps.conf.lng), GoogleMaps.conf.zoomlevel, eval(GoogleMaps.conf.defaultmaptype));
			return true;
		} else {
			return false;
		}
	} else {
		relationMap.innerHTML = 'Sorry, your browser is not compatable with google maps';
	}
}

GoogleMaps.showInfoWindow = function (point, message, routeInfo)
{
	if (GoogleMaps.conf.relationPicker == true) {
		GoogleMaps.currentMessage = message;
	}
	GoogleMaps.map.openInfoWindowHtml(point,
			'<div class="google-infowindow">' +
			message.infowindow +
			(GoogleMaps.conf.routeoptions > 0 && !Object.isUndefined(routeInfo) ? "<br /><a href=\"#\" onclick=\"GoogleMaps.calculateRoute('" + message.lat + "', '" + message.lng + "', '" + escape(message.searchrow.infowindow) + "', '" + message.address + "')\">Route</a>" : "") +
			(GoogleMaps.conf.relationPicker == true && !Object.isUndefined(message.name) ? "<br /><br /><button onclick=\"GoogleMaps.selectRelation()\"><span class='inner-button'>" + GoogleMaps.conf.pickerButtonTitle + "</span></button>" : "") +
			'</div>');
}

GoogleMaps.handleSubmit = function()
{
	GoogleMaps.fromAddress = $F('googlemapsearch').strip();
	$('googlemapsearch').value = GoogleMaps.fromAddress;

	if (GoogleMaps.isLoaded) {
		GoogleMaps.map.closeInfoWindow();

		if (GoogleMaps.conf.routeoptions > 1) {
			$('routebox').childElements().each(function(childElement){childElement.remove();});
		}
	}
	if (!GoogleMaps.fromAddress.empty() && GoogleMaps.fromAddress != PbLib.g('Address, postcode or town')) {
		PbLib.startLoader('');
		new Ajax.Request(PbLib.getNewURI('l/googlemaps/getnearestpoint'), {
			asynchronous: false,
			parameters: {
							'address': GoogleMaps.fromAddress,
							'relation': GoogleMaps.conf.type == 'relation' ? GoogleMaps.conf.relationid : GoogleMaps.conf.relationselectionid,
							'max': GoogleMaps.conf.maxresults,
							'relationtype': GoogleMaps.conf.relationtypeid,
							'addresstype': GoogleMaps.conf.addresstypeid,
							'infowindowrow': GoogleMaps.conf.infowindowrow,
							'searchresultrow': GoogleMaps.conf.searchresultrow,
							'allowmoreresults': 1,
							'country': $F('country'),
							'type': GoogleMaps.conf.type
						},
			onSuccess: function (response) {
				if ($('tablinks_informationwindow_route')) { $('tablinks_informationwindow_route').hide(); }
				if ($('tablinks_informationwindow_searchoptions')) { $('tablinks_informationwindow_searchoptions').hide(); }
				if ($('tablinks_informationwindow_searchresult')) { $('tablinks_informationwindow_searchresult').hide(); }
				if ($('tablinks_informationwindow_search')) { $('tablinks_informationwindow_search').hide(); }
				response = response.responseText.evalJSON();
				if (!GoogleMaps.isLoaded) {
					$('googlemaps').setStyle({
						'width':parseInt(GoogleMaps.conf.width) + 'px',
						'height':parseInt(GoogleMaps.conf.height) + 'px'
						}).show();
					GoogleMaps.conf.defaultvisible = true;
					GoogleMaps.isLoaded = GoogleMaps.prepair();
				}
				$('tablinks_informationwindow_search').show();
				if (!response.multipleresult) {
					$('tablinks_informationwindow_searchresult').show();
					$('search_result_box').childElements().each(function(childElement){childElement.remove();});
					$('search_result_box').setStyle({'height': (GoogleMaps.conf.height - $('tablinks_informationwindow').getHeight()) + 'px'});
					var table = new Element('table', {'class': 'searchresult'});
					if (!response.error) {
						GoogleMaps.map.clearOverlays();
						GoogleMaps.startLat = response.lat;
						GoogleMaps.startLng = response.lng;
						if (GoogleMaps.conf.maxresults > 1) {
							table.insert(new Element('thead').insert(new Element('tr').insert(new Element('th').update(GoogleMaps.conf.nameheadtext)).insert(new Element('th', {'class': 'distance'}).update(GoogleMaps.conf.distanceheadtext))));
							table.insert(body = new Element('tbody'));
							table.insert(new Element('tfoot').insert(new Element('tr').insert(new Element('th', {'colspan': '2'}).update(GoogleMaps.conf.distancedescription))));
							var square = new GLatLngBounds(new GLatLng(response.lat, response.lng));
							response.message.each(function(message){
								square.extend(new GLatLng(message.lat, message.lng));
								GoogleMaps.addMarker(message, response);
								body.insert({bottom: row = new Element('tr').insert(new Element('td').update(message.searchrow.infowindow)).insert(new Element('td', {'class': 'distance'}).update(message.distance + ' km'))});
								row.addClassName('clickable');
								Event.observe(row, 'click', function(){
									$$('table.searchresult .active').each(function(element){element.removeClassName('active')});
									this.addClassName('active');
									GoogleMaps.showInfoWindow(new GLatLng(message.lat, message.lng), message, response);
								});
							});
							var icon = new GIcon();
							icon.image = PbLib.getNewURI('files/mod_googlemaps/icons/flag_green16.png');
							icon.iconSize = new GSize(16, 16);
							icon.iconAnchor = new GPoint(8, 16);
							var options = {};
							options.icon = icon;
							GoogleMaps.startMarker = new GMarker(new GLatLng(response.lat, response.lng), options);
							GoogleMaps.map.addOverlay(GoogleMaps.startMarker);

							GoogleMaps.setNewCenter(square.getCenter(), GoogleMaps.map.getBoundsZoomLevel(square));
							$('search_result_box').insert({top: new Element('span').update(GoogleMaps.conf.searchresultexplanation)});
						} else {
							response.message.each(function(message){
								GoogleMaps.calculateRoute(message.lat, message.lng, escape(message.name), message.address);
								GoogleMaps.addMarker(message, response);
								var icon = new GIcon();
								icon.image = PbLib.getNewURI('files/mod_googlemaps/icons/flag_green16.png');
								icon.iconSize = new GSize(16, 16);
								icon.iconAnchor = new GPoint(8, 16);
								var options = {};
								options.icon = icon;
								GoogleMaps.startMarker = new GMarker(new GLatLng(response.lat, response.lng), options);
								GoogleMaps.map.addOverlay(GoogleMaps.startMarker);
							});
						}
					} else {
						table.update(new Element('tbody').update(new Element('tr').update(new Element('td').update(response.message))));
					}
					$('search_result_box').insert({'bottom': table});
					showTabinformationwindow('searchresult');
				} else {
					$('tablinks_informationwindow_searchoptions').show();
					$('option_box').childElements().each(function(childElement){childElement.remove();});
					var table = new Element('table', {'class': 'searchoptions'});
					var body = new Element('tbody');

					table.insert(new Element('thead').insert(new Element('tr').insert(new Element('th', {'class': 'option'}).update(GoogleMaps.conf.optionsheadtext))));
					table.insert(body);
					response.options.each(function(option){
						body.insert({bottom: row = new Element('tr', {'class':'clickable'}).insert(new Element('td').update(option))});
						Event.observe(row, 'click', function(){
							$('googlemapsearch').value = option;
							GoogleMaps.handleSubmit()});
					});
					$('option_box').insert({top: new Element('span').update(GoogleMaps.conf.optionresultexplanation)}).insert(table);
					showTabinformationwindow('searchoptions');
				}
				PbLib.stopLoader();
			}
		});
	} else if (!$F('namesearch').strip().empty()) {
		GoogleMaps.showFindRelation();
	}
}

GoogleMaps.showFindRelation = function(relationId)
{
	PbLib.startLoader('');
	if (relationId) {
		new Ajax.Request(PbLib.getNewURI('l/googlemaps/getselectedrelation'), {
			parameters: {
							'relation': relationId,
							'relationtype': GoogleMaps.conf.relationtypeid,
							'addresstype': GoogleMaps.conf.addresstypeid,
							'infowindowrow': GoogleMaps.conf.infowindowrow
						},
			onSuccess: function(response){
				var markerInfo = response.responseText.evalJSON();
				GoogleMaps.map.clearOverlays();
				if (markerInfo.lat) {
					if (GoogleMaps.conf.autopan) {
						var square = new GLatLngBounds(new GLatLng(markerInfo.lat, markerInfo.lng));
					}
					GoogleMaps.addMarker(markerInfo);
					GoogleMaps.showInfoWindow(new GLatLng(markerInfo.lat, markerInfo.lng), markerInfo);

					if (GoogleMaps.conf.autopan) {
						GoogleMaps.setNewCenter(square.getCenter(), GoogleMaps.map.getBoundsZoomLevel(square));
					} else {
						GoogleMaps.setNewCenter(new GLatLng(GoogleMaps.conf.lat, GoogleMaps.conf.lng), GoogleMaps.conf.zoomlevel);
					}
				}
				PbLib.stopLoader();
			}
		});
	} else {
		if (GoogleMaps.conf.type == 'relation') {
			var url = PbLib.getNewURI('l/googlemaps/findrelations/' + GoogleMaps.conf.relationid)
		} else {
			var url = PbLib.getNewURI('l/googlemaps/findrelations/' + GoogleMaps.conf.relationselectionid)
		}
		new Ajax.Request(url, {
			'parameters': {
							'relation': GoogleMaps.conf.type == 'relation' ? GoogleMaps.conf.relationid : GoogleMaps.conf.relationselectionid,
							'relationname': $F('namesearch').strip(),
							'relationtype': GoogleMaps.conf.relationtypeid,
							'addresstype': GoogleMaps.conf.addresstypeid,
							'infowindowrow': GoogleMaps.conf.infowindowrow,
							'searchresultrow': GoogleMaps.conf.searchresultrow,
							'type': GoogleMaps.conf.type
						},
			'onSuccess': function(response) {
				if ($('tablinks_informationwindow_route')) { $('tablinks_informationwindow_route').hide(); }
				if ($('tablinks_informationwindow_searchoptions')) { $('tablinks_informationwindow_searchoptions').hide(); }
				if ($('tablinks_informationwindow_searchresult')) { $('tablinks_informationwindow_searchresult').hide(); }
				if ($('tablinks_informationwindow_search')) { $('tablinks_informationwindow_search').hide(); }
				response = response.responseText.evalJSON();
				if (!GoogleMaps.isLoaded) {
					$('googlemaps').setStyle({
						'width':parseInt(GoogleMaps.conf.width) + 'px',
						'height':parseInt(GoogleMaps.conf.height) + 'px'
						}).show();
					GoogleMaps.conf.defaultvisible = true;
					GoogleMaps.isLoaded = GoogleMaps.prepair();
				}
				$('tablinks_informationwindow_search').show();
				$('tablinks_informationwindow_searchresult').show();
				$('search_result_box').childElements().each(function(childElement){childElement.remove();});
				$('search_result_box').setStyle({'height': (GoogleMaps.conf.height - $('tablinks_informationwindow').getHeight()) + 'px'});
				var table = new Element('table', {'class': 'searchresult'});
				if (!response.error) {
					GoogleMaps.map.clearOverlays();
					table.insert(new Element('thead').insert(new Element('tr').insert(new Element('th').update(GoogleMaps.conf.nameheadtext))));
					table.insert(body = new Element('tbody'));
					var square = 'first';
					response.message.each(function(message){
						if (square == 'first') {
							square = new GLatLngBounds(new GLatLng(message.lat, message.lng));
						} else {
							square.extend(new GLatLng(message.lat, message.lng));
						}
						GoogleMaps.addMarker(message);
						body.insert({bottom: row = new Element('tr').insert(new Element('td').update(message.searchrow.infowindow))});
						row.addClassName('clickable');
						row.observe('click', function(event){
							$$('table.searchresult .active').each(function(element){element.removeClassName('active')});
							this.addClassName('active');
							GoogleMaps.showInfoWindow(new GLatLng(message.lat, message.lng), message);
						});
					});
					GoogleMaps.setNewCenter(square.getCenter(), GoogleMaps.map.getBoundsZoomLevel(square));
					$('search_result_box').insert({top: new Element('span').update(GoogleMaps.conf.searchresultexplanation)});
				} else {
					table.update(new Element('tbody').update(new Element('tr').update(new Element('td').update(response.message))));
				}
				$('search_result_box').insert({'bottom': table});
				showTabinformationwindow('searchresult');
				PbLib.stopLoader();
			}
		});
	}
}

GoogleMaps.getRelations = function () {
	if (GoogleMaps.conf.type == 'relation') {
		var url = GoogleMaps.conf.url + '/' + GoogleMaps.conf.relationid
	} else {
		var url = GoogleMaps.conf.url + '/' + GoogleMaps.conf.relationselectionid
	}
	new Ajax.Request(url, {
		'parameters': {
						'relation': GoogleMaps.conf.type == 'relation' ? GoogleMaps.conf.relationid : GoogleMaps.conf.relationselectionid,
						'relationtype': GoogleMaps.conf.relationtypeid,
						'addresstype': GoogleMaps.conf.addresstypeid,
						'infowindowrow': GoogleMaps.conf.infowindowrow,
						'searchresultrow': GoogleMaps.conf.searchresultrow,
						'type': GoogleMaps.conf.type
					},
		'onSuccess': function(response){
			var square = new GLatLngBounds();
			response.responseText.evalJSON().each(function(markerInfo){
				if (GoogleMaps.conf.autopan) {
					square.extend(new GLatLng(markerInfo.lat, markerInfo.lng));
				}
				GoogleMaps.addMarker(markerInfo);
			});
			if (GoogleMaps.conf.autopan) {
				GoogleMaps.setNewCenter(square.getCenter(), GoogleMaps.map.getBoundsZoomLevel(square));
			} else {
				GoogleMaps.setNewCenter(new GLatLng(GoogleMaps.conf.lat, GoogleMaps.conf.lng), GoogleMaps.conf.zoomlevel);
			}
		}
	});
}

document.observe ("dom:loaded", function()
{
	if ($('tablinks_informationwindow_search')) {$('tablinks_informationwindow_search').hide();}
	if ($('tablinks_informationwindow_searchresult')) {$('tablinks_informationwindow_searchresult').hide();}
	if ($('tablinks_informationwindow_searchoptions')) {$('tablinks_informationwindow_searchoptions').hide();}
	if ($('tablinks_informationwindow_route')) {$('tablinks_informationwindow_route').hide();}
	GoogleMaps.isLoaded = GoogleMaps.prepair();
	if (GoogleMaps.isLoaded) {
		if (GoogleMaps.conf.url && !GoogleMaps.conf.address) {
			GoogleMaps.getRelations();
		}
	}

	if (GoogleMaps.conf.issearchable && $('searchform')) {
		Event.observe($('searchform'), 'submit', function(event) {
			Event.stop(event);
			GoogleMaps.handleSubmit();
		});

		if (GoogleMaps.conf.showrelationselectbox && $('searchform')) {
			$('relationselect').observe('change', function(event) {
				if ($F('relationselect') > 0) {
					GoogleMaps.showFindRelation($F('relationselect'));
				}
				Event.stop(event);
			});
		}
		if (GoogleMaps.conf.address) {
			GoogleMaps.handleSubmit();
		}
		if (GoogleMaps.conf.relationName) {
			$('googlemapsearch').value = '';
			GoogleMaps.handleSubmit();
		}
		if (GoogleMaps.conf.showrelationbutton == 1) {
			Event.observe($('showrelationbutton'), 'click', function(event) {
				if ($('tablinks_informationwindow_search')) {
					$('tablinks_informationwindow_search').hide();
				}
				if ($('tablinks_informationwindow_searchresult')) {
					$('tablinks_informationwindow_searchresult').hide();
				}
				if ($('tablinks_informationwindow_route')) {
					$('tablinks_informationwindow_route').hide();
				}
				$('googlemapsearch').value = '';
				if (!GoogleMaps.isLoaded) {
					$('googlemaps').setStyle({
						'width':parseInt(GoogleMaps.conf.width) + 'px',
						'height':parseInt(GoogleMaps.conf.height) + 'px'
						}).show();
					GoogleMaps.conf.defaultvisible = true;
					GoogleMaps.isLoaded = GoogleMaps.prepair();
				}
				GoogleMaps.map.clearOverlays();
				GoogleMaps.getRelations();
			});
		}
	} else if ($('search_submit')) {
		$('search_submit').observe('click', function(event){Event.stop(event)});
	}

	Event.observe(window, 'unload', function()
	{
		if (GoogleMaps.isLoaded) {
			GoogleMaps.map.clearOverlays();
			GEvent.clearInstanceListeners(GoogleMaps.map.getContainer());
			GUnload();
		}
	})
})
