/**
 * Javascript Library File. Contains functions that use Google Maps API.
 * 
 * @author Fon
 * @package FonMaps
 */

// Global variables
var map;
var bounds;
var sWLat;
var sWLng;
var nELat;
var nELng;
var zoom;
var point;
var line;
var listElementAutocompleteObject = null;
var autoListElements = null;
var autoListElementsData = null;
var autoListElementsDataSource = null;
var html = "";
var oMenu = null;

/**
 * Initializes map
 * 
 */
function ShowMeTheMap() {
	// IExplorer height check
	Resize();
	pointIni = new GLatLng(iniLat, iniLng);
	newGMap2(pointIni, iniZoom, G_HYBRID_MAP);
	showNodeList();
	showLangList();
}

/**
 * Specific functions to insert getNearestImmo Control in Google Map
 * 
 */
function GetNearestImmoControl() {
}
GetNearestImmoControl.prototype = new GControl();
GetNearestImmoControl.prototype.initialize = function(map) {
	var container = document.createElement("div");

	var button = document.createElement("img");
	this.setButtonStyle_(button);
	container.appendChild(button);
	button.setAttribute('src', 'img/getrouter.png');
	button.setAttribute('title', JS_NEARESTROUTER);
	GEvent.addDomListener(button, "click", function() {
		getNearestImmoFromCenter();
	});
	map.getContainer().appendChild(container);
	return container;
}
// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
GetNearestImmoControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(84, 26));
}
// Sets the proper CSS for the given button element.
GetNearestImmoControl.prototype.setButtonStyle_ = function(button) {
	button.style.backgroundColor = "transparent";
	button.style.cursor = "pointer";
}

function getIcon() {
	var icon = new GIcon();
	icon.image = "/extension/maps/design/standard/images/mapicon_info.png";
	icon.iconAnchor = new GPoint(0, 0);
	icon.infoWindowAnchor = new GPoint(19, 32);
	icon.iconSize = new GSize(19, 32);
	icon.shadow = "/extension/maps/design/standard/images/mapicon_shadow.png";
	icon.shadowSize = new GSize(22, 20);
	return icon;
}
/*
 */
/**
 * Specific functions to insert getLegend Control in Google Map
 * 
 */
function GetLegendControl() {
}
GetLegendControl.prototype = new GControl();
GetLegendControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	container.setAttribute('id', 'legendButtonContainer');
	button = document.createTextNode(JS_LEGEND_LINK);
	this.setButtonStyle_(container);
	container.appendChild(button);
	GEvent.addDomListener(container, "click", function() {
		showLegend();
	});
	map.getContainer().appendChild(container);
	return container;
}
// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
GetLegendControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(164, 7));
}
// Sets the proper CSS for the given button element.
GetLegendControl.prototype.setButtonStyle_ = function(button) {
	button.style.backgroundColor = "white";
	button.style.padding = "2px";
	button.style.width = "60px";
	button.style.height = "13px";
	button.style.textAlign = "center";
	button.style.border = "1px solid black";
	button.style.cursor = "pointer";
}

/**
 * Specific functions to insert getList Control in Google Map
 * 
 */
function GetListControl() {
}
GetListControl.prototype = new GControl();
GetListControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	container.setAttribute('id', 'listButtonContainer');
	var button = document.createElement("img");
	this.setButtonStyle_(button);
	container.appendChild(button);
	button.setAttribute('src', 'img/list.png');
	button.setAttribute('title', JS_LISTPANEL_TITLE);
	GEvent.addDomListener(button, "click", function() {
		showNodeList();
	});
	map.getContainer().appendChild(container);
	return container;
}
// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
GetListControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(67, 27));
}
// Sets the proper CSS for the given button element.
GetListControl.prototype.setButtonStyle_ = function(button) {
	button.style.backgroundColor = "transparent";
	button.style.cursor = "pointer";
}

/**
 * Erase all points in map
 * 
 */
function clearmap() {
	if (map.getZoom() >= 20) {
		map.clearOverlays();
	}
}

/**
 * Create a Marker
 * 
 */
function createMarker(lat, lng, number, iconNode, countryCode, zoom, addr,
		router_id, nickname, custom) {
	point = new GLatLng(lat, lng);
	var icon = new GIcon();
	if (iconNode == "node_router") {
		if (custom['PERSONALIZED'] == 'True') {
			path = "../img/" + iconNode + "pers" + zoom + "_node.png";
		} else {
			path = "../img/" + iconNode + zoom + "_node.png";
		}
		icon.image = path;
		if (zoom == 19) {
			icon.iconSize = new GSize(400, 400);
			icon.iconAnchor = new GPoint(200, 200);
		}
		if (zoom == 18) {
			icon.iconSize = new GSize(220, 220);
			icon.iconAnchor = new GPoint(110, 110);
		}
		if (zoom == 17) {
			icon.iconSize = new GSize(100, 100);
			icon.iconAnchor = new GPoint(50, 50);
		}
		if (zoom == 16) {
			icon.iconSize = new GSize(58, 58);
			icon.iconAnchor = new GPoint(29, 29);
		}
		if (zoom == 15) {
			icon.iconSize = new GSize(36, 36);
			icon.iconAnchor = new GPoint(18, 18);
		}
		if (zoom == 14) {
			icon.iconSize = new GSize(20, 20);
			icon.iconAnchor = new GPoint(10, 10);
		}
	} else if (iconNode == "node_off") {
		path = "../img/" + iconNode + zoom + "_node.png";
		icon.image = path;
		if (zoom == 19) {
			icon.iconSize = new GSize(400, 400);
			icon.iconAnchor = new GPoint(200, 200);
		}
		if (zoom == 18) {
			icon.iconSize = new GSize(220, 220);
			icon.iconAnchor = new GPoint(110, 110);
		}
		if (zoom == 17) {
			icon.iconSize = new GSize(100, 100);
			icon.iconAnchor = new GPoint(50, 50);
		}
		if (zoom == 16) {
			icon.iconSize = new GSize(58, 58);
			icon.iconAnchor = new GPoint(29, 29);
		}
		if (zoom == 15) {
			icon.iconSize = new GSize(36, 36);
			icon.iconAnchor = new GPoint(18, 18);
		}
		if (zoom == 14) {
			icon.iconSize = new GSize(20, 20);
			icon.iconAnchor = new GPoint(10, 10);
		}
	} else if (iconNode == "country") {
		path = "../img/country2/country_" + countryCode + "_node.png";
		icon.image = path;
		// icon.shadow = "../img/country2/shadow_country_node.png";
		// icon.shadowSize = new GSize(24, 24);
		// icon.shadowAnchor = new GPoint(24, 24);
		icon.iconSize = new GSize(24, 24);
		icon.iconAnchor = new GPoint(12, 12);

	} else if (iconNode == "continent" || iconNode == "city") {
		path = "../img/" + iconNode + "_node.png";
		icon.image = path;
		// icon.shadow =
		// "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		// icon.shadowSize = new GSize(22, 20);
		icon.iconSize = new GSize(24, 24);
		icon.iconAnchor = new GPoint(12, 12);
	} else {
		path = "../img/" + iconNode + "_node.png";
		icon.image = path;
		// icon.shadow =
		// "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		// icon.shadowSize = new GSize(22, 20);
		icon.iconSize = new GSize(16, 16);
		icon.iconAnchor = new GPoint(8, 8);
	}

	var zoomVar = 0;

	if (iconNode == 'continent') {
		zoomVar = 2;
	} else if (iconNode == 'country') {
		zoomVar = 5;
	} else if (iconNode == 'city') {
		zoomVar = 13;
	} else {
		zoomVar = 17;
	}
	var marker = new GMarker(point, {
		icon : getIcon(),
		clickable : true
	});
	if (map.getZoom() >= 14) {
		if (iconNode != 'node_router' && iconNode != 'node_off') {
			GEvent.addListener(marker, "click", function() {

				/*
				 * var contentStatic = ''; contentStatic = nickname+' '+addr;
				 * contentStatic += '<ul class="menu">'; contentStatic += '<li class="menuitem"><a
				 * onclick="javascript:getNearestImmo('+lat+',
				 * '+lng+')">'+JS_NEARESTROUTER+'</a></li>'; contentStatic += '</ul>';
				 * document.getElementById('nodePanelContent').innerHTML =
				 * contentStatic;
				 */

				if (oMenu != null) {
					oMenu.destroy();
				}

				oMenu = new YAHOO.widget.Menu("basicmenu", {
					x : xMousePos,
					y : yMousePos,
					constraintoviewport : true
				});

				/*
				 * if (nickname=='') {
				 * 
				 * oMenu.setItemGroupTitle(JS_NODATA_NICKNAME, 0); } else {
				 * oMenu.setItemGroupTitle(nickname, 0); }
				 * 
				 * 
				 * oMenu.addItem( new YAHOO.widget.MenuItem( addr, {
				 * strongemphasis:true,disabled:true} ) );
				 */
				oMenu.setItemGroupTitle(addr, 0);

				/* if (nickname=='') { */
				oMenu.addItem(new YAHOO.widget.MenuItem(JS_CHANGE_NICKNAME, {
					url : "javascript:openInfPopup('nick');oMenu.destroy();"
				}));
				/* } */

				oMenu.addItem(new YAHOO.widget.MenuItem(JS_NEARESTROUTER, {
					url : "javascript:getNearestImmo('" + lat + "', '" + lng
							+ "');oMenu.destroy();"
				}));

				oMenu.addItem(new YAHOO.widget.MenuItem(JS_CANCEL, {
					url : "javascript:oMenu.destroy();"
				}));

				oMenu.render(document.body);

				oMenu.show();

			});
			GEvent.addListener(marker, "mouseover", function() {
				return overlib(addr + "<br/>" + JS_MOREINFO, FGCOLOR,
						'#FFFFFF', BGCOLOR, '#f8993a', BORDER, 2, RIGHT, ABOVE,
						HAUTO, VAUTO, TEXTSIZE, '10px');
			});
			GEvent.addListener(marker, "mouseout", function() {
				nd();
			});

		} else {
			GEvent
					.addListener(
							marker,
							"click",
							function() {

								/*
								 * var contentStatic = ''; contentStatic =
								 * nickname+' '+addr; contentStatic += '<ul class="menu">';
								 * contentStatic += '<li class="menuitem"><a
								 * onclick="javascript:showCaptivePortal('+router_id+')">'+JS_CAPTIVEPORTAL+'</a></li>';
								 * contentStatic += '</ul>';
								 * document.getElementById('nodePanelContent').innerHTML =
								 * contentStatic;
								 */

								if (oMenu != null) {
									oMenu.destroy();
								}

								oMenu = new YAHOO.widget.Menu("basicmenu", {
									x : xMousePos,
									y : yMousePos,
									constraintoviewport : true
								});

								/*
								 * if (nickname=='') {
								 * 
								 * oMenu.setItemGroupTitle(JS_OWNER_NODATA_NICKNAME,
								 * 0); } else {
								 * oMenu.setItemGroupTitle(JS_OWNER_NICKNAME+nickname,
								 * 0); }
								 * 
								 * 
								 * oMenu.addItem( new YAHOO.widget.MenuItem(
								 * addr, { strongemphasis:true,disabled:true} ) );
								 */

								oMenu.setItemGroupTitle(addr, 0);

								/*
								 * if (nickname=='') { oMenu.addItem( new
								 * YAHOO.widget.MenuItem( JS_CHANGE_NICKNAME, {
								 * url:"javascript:openInfPopup('nick');oMenu.destroy();"} ) ); }
								 */

								if (custom['PERSONALIZED'] == 'True') {
									oMenu
											.addItem(new YAHOO.widget.MenuItem(
													JS_CAPTIVEPORTAL,
													{
														url : "javascript:showCaptivePortal('"
																+ router_id
																+ "');oMenu.destroy();"
													}));
								} else {
									oMenu
											.addItem(new YAHOO.widget.MenuItem(
													JS_CUSTOM_YOURCP,
													{
														url : "javascript:openInfPopup('customize');oMenu.destroy();"
													}));

								}

								oMenu
										.addItem(new YAHOO.widget.MenuItem(
												JS_SENDURL_CP,
												{
													url : "javascript:showSendUrl('"
															+ router_id
															+ "',null,null,null);oMenu.destroy();"
												}));

								oMenu
										.addItem(new YAHOO.widget.MenuItem(
												JS_SENDURL_LOC,
												{
													url : "javascript:showSendUrl(null,'"
															+ lat
															+ "','"
															+ lng
															+ "','"
															+ map.getZoom()
															+ "');oMenu.destroy();"
												}));

								oMenu.addItem(new YAHOO.widget.MenuItem(
										JS_CANCEL, {
											url : "javascript:oMenu.destroy();"
										}));

								oMenu.render(document.body);

								oMenu.show();

							});

			GEvent.addListener(marker, "mouseover", function() {
				return overlib(addr + "<br/>" + JS_MOREINFO, FGCOLOR,
						'#FFFFFF', BGCOLOR, '#f8993a', BORDER, 2, RIGHT, ABOVE,
						HAUTO, VAUTO, TEXTSIZE, '10px');
			});
			GEvent.addListener(marker, "mouseout", function() {
				nd();
			});
		}
	} else {
		GEvent.addListener(marker, "click", function() {
			getMarkersByParent(lat, lng, zoomVar);
		});
		GEvent.addListener(marker, "mouseover", function() {
			return overlib(addr, FGCOLOR, '#FFFFFF', BGCOLOR, '#f8993a',
					BORDER, 2, RIGHT, ABOVE, HAUTO, VAUTO, TEXTSIZE, '10px');
		});
		GEvent.addListener(marker, "mouseout", function() {
			nd();
		});

	}
	return marker;
}

/**
 * Create a Map
 * 
 */
function newGMap2(point, zoom, mapType) {

	// Fill info text
	if (zoom <= 2) {
		document.getElementById('contextualInfoPanelContent2').innerHTML = zoomLevelContinent;
	}
	if (zoom >= 3 && zoom <= 5) {
		document.getElementById('contextualInfoPanelContent2').innerHTML = zoomLevelCountry;
	}
	if (zoom >= 6 && zoom <= 13) {
		document.getElementById('contextualInfoPanelContent2').innerHTML = zoomLevelCity;
	}
	if (zoom >= 14) {
		document.getElementById('contextualInfoPanelContent2').innerHTML = zoomLevelNode;
	}
	document.getElementById('map').innerHTML = '';
	map = null;
	map = new GMap2(document.getElementById("map"), {
		mapTypes : [ G_NORMAL_MAP, G_HYBRID_MAP ]
	});
	geocoder = new GClientGeocoder();
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GetNearestImmoControl());
	map.addControl(new GetListControl());
	map.addControl(new GetLegendControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl())
	map.enableContinuousZoom();
	map.enableDoubleClickZoom();
	map.setCenter(point, zoom);
	map.setMapType(mapType);
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var sWLat = southWest.lat();
	var sWLng = southWest.lng();
	var nELat = northEast.lat();
	var nELng = northEast.lng();
	getMarkers(sWLat, sWLng, nELat, nELng, zoom);
	map.setCenter(point, zoom);
	if (line != null) {
		map.addOverlay(line);
	}
	GEvent.addListener(map, 'zoomend', function() {
		listener();
	});
	GEvent.addListener(map, 'moveend', function() {
		listener();
	});
}

/**
 * Defines a listener
 * 
 */
function listener() {
	if (oMenu != null) {
		oMenu.destroy();
	}
	bounds = map.getBounds();
	southWest = bounds.getSouthWest();
	northEast = bounds.getNorthEast();
	sWLat = southWest.lat();
	sWLng = southWest.lng();
	nELat = northEast.lat();
	nELng = northEast.lng();
	zoom = map.getZoom();
	point = map.getCenter();
	mapType = map.getCurrentMapType();
	GUnload();
	newGMap2(point, zoom, mapType);
}

/**
 * Print markers in map
 * 
 */
function printMarkers(nodes, maxNodes) {
	if (nodes != null) {
		for (i = 0; i < maxNodes; i++) {
			// punto = new GLatLng(nodes[i]['lat'],nodes[i]['lng']);
			map.addOverlay(createMarker(nodes[i]['lat'], nodes[i]['lng'],
					nodes[i]['id'], nodes[i]['type'], nodes[i]['country'], map
							.getZoom(), nodes[i]['address'],
					nodes[i]['routerId'], null/* nodes[i]['nickname'] */,
					nodes[i]['custom']));
		}
	}
}

/**
 * Show a line between 2 points
 * 
 */
function showLineToNearestImmo(markers) {
	if (markers != null) {
		var bounds = new GLatLngBounds;
		nodes = markers.childNodes[0];
		if (nodes != null) {
			if (nodes.nodeName == 'xml') {
				nodes = markers.childNodes[1];
			}
		}
		var start = new Array();
		start['lat'] = nodes.childNodes[0].attributes[3].nodeValue;
		start['lng'] = nodes.childNodes[0].attributes[4].nodeValue;
		start['punto'] = new GLatLng(start['lat'], start['lng']);
		var end = new Array();
		end['id'] = nodes.childNodes[1].attributes[0].nodeValue;
		end['parentId'] = nodes.childNodes[1].attributes[1].nodeValue;
		end['lat'] = nodes.childNodes[1].attributes[3].nodeValue;
		end['lng'] = nodes.childNodes[1].attributes[4].nodeValue;
		end['zoom'] = nodes.childNodes[1].attributes[5].nodeValue;
		end['type'] = nodes.childNodes[1].attributes[2].nodeValue;
		end['punto'] = new GLatLng(end['lat'], end['lng']);
		end['addr'] = nodes.childNodes[1].firstChild.firstChild.nodeValue;
		bounds.extend(new GLatLng(start['lat'], start['lng']));
		bounds.extend(new GLatLng(end['lat'], end['lng']));
		map.removeOverlay(line);
		line = new GPolyline( [ start['punto'], end['punto'] ], "#f68a1d", 6,
				0.90);
		map.addOverlay(line);
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		distanceFromImmo = start['punto'].distanceFrom(end['punto']);
		GEvent.addListener(line, "mouseover", function() {
			return overlib(Math.round(distanceFromImmo) + " mtrs", FGCOLOR,
					'#FFFFFF', BGCOLOR, '#f8993a', BORDER, 2, RIGHT, ABOVE,
					HAUTO, VAUTO, TEXTSIZE, '10px');
		});
		GEvent.addListener(line, "mouseout", function() {
			nd();
		});

		// document.getElementById('nodePanelContent').innerHTML =
		// "<b>"+Math.round(distanceFromImmo)+" mtrs </b>";
	}
}

/**
 * Autocomplete list Event listener
 * 
 */
function autoListElementSelectEventListener(a, b, c) {
	var selectedItem = new String(b[2]);
	var selectedItemData = selectedItem.split(',');
	var selectedItemId = selectedItemData[(selectedItemData.length - 1)];
	var lat = autoListElementsData[selectedItemId][0];
	var lng = autoListElementsData[selectedItemId][1];
	var zoom = autoListElementsData[selectedItemId][2];
	getMarkersByParent(lat, lng, zoom);
}

/**
 * Fills and shows autocomplete List
 * 
 */
function printListMenu(nodes) {
	var center = map.getCenter();
	HTMLText = '<ul>';
	autoListElements = new Array();
	autoListElementsData = new Array();
	if (nodes != null) {
		for (i = 0; i < nodes.length; i++) {
			id = nodes[i]['id'];
			parentId = nodes[i]['parentId'];
			type = nodes[i]['type'];
			lat = nodes[i]['lat'];
			lng = nodes[i]['lng'];
			zoom = nodes[i]['zoom'];
			if (zoom == 20) {
				zoom = 17;
			}
			country = nodes[i]['country'];
			userId = nodes[i]['userId'];
			routerId = nodes[i]['routerId'];
			punto = new GLatLng(lat, lng);
			addr = nodes[i]['address'];
			HTMLText += '<li><a href="javascript:void(0);" onmousedown="javascript:getMarkersByParent('
					+ lat
					+ ','
					+ lng
					+ ','
					+ zoom
					+ ');">'
					+ addr
					+ '</a></li>';
			autoListElements.push(new Array(addr, id));
			autoListElementsData[id] = new Array(lat, lng, zoom);
		}
	}
	HTMLText += '</ul>';
	autoListElementsDataSource = new YAHOO.widget.DS_JSArray(autoListElements);
	listElementAutocompleteObject = new YAHOO.widget.AutoComplete(
			'autoListElementInput', 'listSuggestion',
			autoListElementsDataSource);
	listElementAutocompleteObject.animVert = true;
	listElementAutocompleteObject.animHoriz = true;
	listElementAutocompleteObject.animSpeed = 0.1;
	listElementAutocompleteObject.autoHighlight = false;
	listElementAutocompleteObject.prehighlightClassName = "autoListElementMouseOver";
	listElementAutocompleteObject.useShadow = true;
	listElementAutocompleteObject.formatResult = function(oResultItem, sQuery) {
		var sMarkup = oResultItem[0];
		return (sMarkup);
	};
	document.getElementById('content').innerHTML = HTMLText;
	listElementAutocompleteObject.itemSelectEvent
			.subscribe(autoListElementSelectEventListener);
}

/**
 * Obtains marker's child nodes
 * 
 */
function getMarkersByParent(lat, lng, zoom) {
	lat = new Number(lat);
	lng = new Number(lng);
	zoom = new Number(zoom);
	var punto = new GLatLng(lat, lng);
	mapType = map.getCurrentMapType();
	GUnload();
	newGMap2(punto, zoom + 1, mapType);
}

/**
 * Shows Point Relocation Map
 * 
 */
function showRecenterMap(lat, lng, zoom, address, mapid) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById(mapid), {
			mapTypes : [ G_NORMAL_MAP, G_HYBRID_MAP ]
		});
		map.addControl(new GLargeMapControl());
		geocoder = new GClientGeocoder();
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(lat, lng), 14);
		var marker = new GMarker(new GLatLng(lat, lng), {
			icon : getIcon()
		});
		map.addOverlay(marker);
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		var punto = false;
		if (geocoder && address != '') {
			geocoder.getLatLng(address, function(point) {
				if (!point) {
					alert(address + " " + JS_NOTFOUND);
				} else {
					map.setCenter(point);
					var marker = new GMarker(point, {
						icon : getIcon()
					});
					map.addOverlay(marker);
				}
			});
		}

	} else {
		alert("your browser is not compatible with Maps, get Firefox!")
	}
}

function showRecenterMap2(lat, lng, zoom, address) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"), {
			mapTypes : [ G_NORMAL_MAP, G_HYBRID_MAP ]
		});
		map.addControl(new GLargeMapControl());
		geocoder = new GClientGeocoder();
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(lat, lng));
		var marker = new GMarker(new GLatLng(lat, lng), zoom);
		map.addOverlay(marker);
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		var punto = false;
		GEvent.addListener(map, "click", function() {
			map.clearOverlays();
			if (punto == true) {
				punto = false;
			}
		});
		GEvent.addListener(map, "click", function(overlay, point) {
			map.addOverlay(new GMarker(point));
			var pointNew = point.toString();
			var preLatlongNew = pointNew.split(", ");
			var latitudeNew = preLatlongNew[0].split("(");
			latitude = latitudeNew[1];
			var longitudeNew = preLatlongNew[1].split(")");
			longitude = longitudeNew[0];
			punto = true;
			document.getElementById("latitude").value = point.y;
			document.getElementById("longitude").value = point.x;
		});

		if (geocoder && address != '') {
			geocoder
					.getLatLng(
							address,
							function(point) {
								if (!point) {
									alert(address + " " + JS_NOTFOUND);
								} else {
									map.setCenter(point, 14);

									var marker = new GMarker(point, {
										draggable : true
									});

									GEvent
											.addListener(
													marker,
													"dragstart",
													function() {
														document
																.getElementById("latitude").value = "";
														document
																.getElementById("longitude").value = "";
													});

									GEvent
											.addListener(
													marker,
													"dragend",
													function() {
														var point = marker
																.getPoint();
														document
																.getElementById("latitude").value = point
																.lat();
														document
																.getElementById("longitude").value = point
																.lng();
													});

									map.addOverlay(marker);
								}
							});
		}

	} else {
		alert("your browser is not compatible with Maps, get Firefox!")
	}
}
function showRecenterMap3(lat, lng, zoom, address) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"), {
			mapTypes : [ G_NORMAL_MAP, G_HYBRID_MAP ]
		});
		map.addControl(new GLargeMapControl());
		geocoder = new GClientGeocoder();
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(lat, lng));
		var marker = new GMarker(new GLatLng(lat, lng), zoom);
		map.addOverlay(marker);
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		var punto = false;

		if (geocoder && address != '') {
			geocoder
					.getLatLng(
							address,
							function(point) {
								if (!point) {
									alert(address + " " + JS_NOTFOUND);
								} else {
									map.setCenter(point, 14);

									document.getElementById("latitude").value = point
											.lat();
									document.getElementById("longitude").value = point
											.lng();
									var marker = new GMarker(point, {
										draggable : true
									});

									GEvent
											.addListener(
													marker,
													"dragstart",
													function() {
														document
																.getElementById("latitude").value = "";
														document
																.getElementById("longitude").value = "";
													});

									GEvent
											.addListener(
													marker,
													"dragend",
													function() {
														var point = marker
																.getPoint();
														document
																.getElementById("latitude").value = point
																.lat();
														document
																.getElementById("longitude").value = point
																.lng();
													});

									map.addOverlay(marker);
								}
							});

		}

	} else {
		alert("your browser is not compatible with Maps, get Firefox!")
	}
}

/**
 * Shows My Usage Map
 * 
 */
function showMyUsageMap(numImmos, latlonString) {
	if (GBrowserIsCompatible()) {
		if (numImmos != 0) {
			latGreat = 0;
			lngGreat = 0;
			latMinor = 10000;
			lngMinor = 10000;
			splitCoords = latlonString.split(";");
			for (i = 1; i <= numImmos; i++) {
				splitCoords2 = splitCoords[i - 1].split(",");
				eval('lat' + i + '=splitCoords2[0]-1+1;');
				eval('lng' + i + '=splitCoords2[1]-1+1;');
				eval('if (lat' + i + '>latGreat) { latGreat = lat' + i + '; }');
				eval('if (lng' + i + '>lngGreat) { lngGreat = lng' + i + '; }');
				eval('if (lat' + i + '<latMinor) { latMinor = lat' + i + '; }');
				eval('if (lng' + i + '<lngMinor) { lngMinor = lng' + i + '; }');
			}
			latCenter = ((latGreat - latMinor) / 2) + latMinor;
			lngCenter = ((lngGreat - lngMinor) / 2) + lngMinor;
			zoom = 6;
		} else {
			latCenter = 0;
			lngCenter = 0;
			zoom = 1;
		}
		var bounds = new GLatLngBounds;
		var map = new GMap2(document.getElementById("map"), {
			mapTypes : [ G_NORMAL_MAP, G_HYBRID_MAP ]
		});
		map.addControl(new GSmallMapControl());
		geocoder = new GClientGeocoder();
		map.addControl(new GMapTypeControl());
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		map.setCenter(new GLatLng(0, 0), 0);
		var accumulatedDistance = 0;
		var point = null;
		var npoint = null;
		var line = null;
		var marker = null;
		var lineArray = new Array();
		for (i = 1; i <= numImmos; i++) {
			var icon = new GIcon();
			eval('point = new GLatLng(lat' + i + ', lng' + i + ')');
			bounds.extend(point);
			path = "../img/node_alien_node.png";
			icon.image = path;
			icon.iconSize = new GSize(16, 16);
			icon.iconAnchor = new GPoint(8, 8);
			marker = new GMarker(point, {
				icon : icon,
				clickable : true
			});
			map.addOverlay(marker);
			if (numImmos != 1) {
				if (i == numImmos) {
					next = 1;
				} else {
					next = i + 1;
				}
				eval('npoint = new GLatLng(lat' + next + ', lng' + next + ');');
				lineArray.push(point);
				// line = new GPolyline([point, npoint], "#f68a1d", 6,0.90);
				// if (!document.all) {
				// map.addOverlay(line);
				// }

				accumulatedDistance = accumulatedDistance
						+ point.distanceFrom(npoint);
			}
		}
		lineArray.push(npoint);
		var line = new GPolyline(lineArray, "#f68a1d", 6, 0.90);
		if (!document.all) {
			map.addOverlay(line);
		}
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		// map.openInfoWindow(map.getCenter(),document.createTextNode(Math.round(accumulatedDistance/1000)+"
		// km."));
		var tooltip = document.getElementById("tooltip");
		tooltip.style.zIndex = '999';
		tooltip.style.position = 'absolute';
		tooltip.style.top = '110px';
		tooltip.style.left = '18px';
		tooltip.style.border = '2px #f8993a solid';
		tooltip.style.padding = '4px';
		tooltip.style.backgroundColor = '#fff';
		tooltip.innerHTML = "<b>" + Math.round(accumulatedDistance / 1000)
				+ " km.</b>";

	} else {
		// alert("your browser is not compatible with Google-Maps!")
	}
}

/**
 * Prepares a center point to pass it to getNearestImmo.
 * 
 */
function getNearestImmoFromCenter() {
	var center = map.getCenter();
	var lat = center.lat();
	var lng = center.lng();
	getNearestImmo(lat, lng);
}

var map;
var geocoder;

function load() {
	map = new GMap2(document.getElementById("map{$rnd}"));
	map.setCenter(new GLatLng(34, 0), 1);
	geocoder = new GClientGeocoder();
}

// addAddressToMap() is called when the geocoder returns an
// answer. It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
	map.clearOverlays();
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
				place.Point.coordinates[0]);
		marker = new GMarker(point);
		map.addOverlay(marker);
		marker.openInfoWindowHtml(place.address + '<br>'
				+ '<b>Country code:</b> '
				+ place.AddressDetails.Country.CountryNameCode);
	}
}

// showLocation() is called when you click on the Search button
// in the form. It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
	var address = document.forms[0].q.value;
	geocoder.getLocations(address, addAddressToMap);
}

/*
 */ 
 function $X() {
	var elements = new Array();

	for ( var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);

		if (arguments.length == 1)
			return element;

		elements.push(element);
	}

	return elements;
}
// ]]>
