var mapX, mapY, geocoder;
var mapStartZoom = 5;
$(document).ready(function() {
	//loading
	if (mapX && mapY) {
		initializeMap(mapX, mapY);
	}
});

// GOOGLE MAPS

var map;
function initializeMap(x, y, mode) {
	if (!mode) mode = 0;
	if (!x) x = 0;
	if (!y) y = 0;
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mapCanvas"));
		if (!mode) {
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
		}
		if (mode == 2) {
			map.addControl(new GLargeMapControl());
		}

		map.setCenter(new GLatLng(x, y), mapStartZoom);

		if (!mode) {
		GEvent.addListener(map,"click", function(overlay,latlng) {
			if (latlng) {
				map.clearOverlays();
				map.addOverlay(new GMarker(latlng));
				$('#pos').val(latlng);
				//inspire();
			}
		});
		}
	}
}

var marker = new Array();
function addOverlay(x, y, zoom, noclear, pinvar, marks) {
	if (!noclear) map.clearOverlays();
	$('#pos').val('0');

	var imagevar = new GIcon(G_DEFAULT_ICON);
	if (pinvar) {
		imagevar.image = "/i/map/pin_" + pinvar + ".png";
		imagevar.iconSize = new GSize(30, 40);
		imagevar.iconAnchor = new GPoint(15, 37);
		imagevar.shadow = false;
	}
	markerOptions = { icon:imagevar };

	map.setCenter(new GLatLng(x, y), zoom);
	marker[x + y] = new GMarker(new GLatLng(x, y), markerOptions);
	map.addOverlay(marker[x + y]);
	$('#pos').val(new GLatLng(x, y));

	if (marks) {
		GEvent.addListener(marker[x + y], "click", function() {
			marker[x + y].openInfoWindowHtml(marks);
		});
	}
}

// gm end
var destLoading;
function updLocation(text) {
	if (!readyToLocation) return false;
	if (destLoading) {
		destLoading.abort();
	}
	destLoading = $.getJSON('/pg/index/location/' + encodeURI(text), function(data) {
		if (data['lat'] && data['lng']) {
			mapX = data['lat'];
			mapY = data['lng'];
			addOverlay(mapX, mapY, 7);
		}
	});
}
function showAddress(text, zoom) {
	if (geocoder) {
		geocoder.getLatLng(text, function(point) {
			if (point) {
				map.setCenter(point, zoom);
			}
		});
	} else {
		geocoder = new GClientGeocoder();
		showAddress(text, zoom);
	}
}
