var overviewMapControl; 
var browserType;
var map;
var customMarker;
var mapTypeIndex = 0;
var mapWidth = 728;
var mapHeight = 600;
var all_markers = new Array();
var all_locations = new Array();
var all_names = new Array();
var all_levels = new Array();
var notShownMarkerId;
var afterMarkersLoadHandler;
var onDragEndHandler;
var onLocationUnderCustomMarker;

var onCoorsChangeHandler;
var changeStated = false;
var lastUpdateTime;

var getPlaceXCallback;
var getPlaceYCallback;
var getScaleCallback;
var getPlaceNameCallback;
var getContextPathCallback;

// Show all resources by default
var resourcesTypeId = 0;
var baseIcon;

// === Some cookie parameters ===
var cookiename = "maptype";  // name for this cookie
var expiredays = 365;          // number of days before cookie expiry

if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {
   browserType= "gecko"
}

// ================================================================
// === Define the function thats going to process the JSON file ===
process_it = function (doc) {
    var contextPath = Gallery.contextPath;
      
    // === Parse the JSON document ===
    // jsonData.empty(); 
	jsonData = eval("(" + doc + ")");
	HINTS_LOCATIONS = [];

    // === Plot the markers ===
	for (var i = 0; i < jsonData.length; i++) {
		var point = new GLatLng(jsonData[i].x, jsonData[i].y);
		var marker = createMarker(point, jsonData[i], contextPath);
		map.addOverlay(marker);
		//$('markersCnt').innerHTML = i+1 + '/' + jsonData.length;
	}

    // === Add marker hints ===
	var disallowLocationEdit = document.getElementById('geo_upl_frame') == null;
	for (var i = 0; i < jsonData.length; i++) {
		var point = new GLatLng(jsonData[i].x, jsonData[i].y);
		var marker = createMarker(point, jsonData[i], contextPath);
		/*
		 * Remember all overlays
		 */
		all_markers[i] = marker;
		all_locations[i] = jsonData[i].location_id;
		all_names[i] = jsonData[i].caption;
		all_levels[i] = jsonData[i].level;
		
		map.addOverlay(marker);
		var allowLocationEdit = jsonData[i].canEdit;
		if (disallowLocationEdit) {
			allowLocationEdit = false;
		}
		HINTS_LOCATIONS[jsonData[i].location_id] = 
			getLocationHint(jsonData[i].level, jsonData[i].place_id, jsonData[i].caption, jsonData[i].cnt_users, 
				jsonData[i].cnt_photos, jsonData[i].cnt_videos, jsonData[i].cnt_blogs, jsonData[i].canAdd, allowLocationEdit, 
				contextPath);
	}
	locationHints = new THints (HINTS_LOCATIONS, HINTS_CFG);
	if (customMarker != null) {
		map.addOverlay(customMarker);
	}
	if (afterMarkersLoadHandler != null) {
		afterMarkersLoadHandler();
		afterMarkersLoadHandler = null;
	}
};


/**
 * Create base icon
 */
function getBaseIcon(point, jsonDataElement, contextPath) {
	if (!baseIcon) {
		baseIcon = new GIcon();
		baseIcon.iconSize=new GSize(56,47);
		baseIcon.shadowSize=new GSize(56,47);
		baseIcon.iconAnchor=new GPoint(28,47);
		baseIcon.infoWindowAnchor=new GPoint(28,0);
	    baseIcon.infoShadowAnchor = new GPoint(28,47);
		baseIcon.shadow = "http://www.zamnoy.com/img/icon/map/shadow_pointer.png";	
	}
    return baseIcon;
}

/**
 * A function to create the marker and set up the hint window
 */
function createMarker(point, jsonDataElement, contextPath) {
	baseIcon = getBaseIcon();
	var icon;
	var transparent = "";

	var shortContextPath;
	var index = contextPath.indexOf('/c/');
	if (index != -1) {
		shortContextPath = contextPath.substring(0, index + 1);
	} else {
		shortContextPath = contextPath;	
	}	
	
	if (resourcesTypeId == 0) {
		if (jsonDataElement.cnt_users || + jsonDataElement.cnt_photos 
			|| jsonDataElement.cnt_videos || jsonDataElement.cnt_blogs) {
			transparent = "";
		} else {
			transparent = "_transparent";
		}
		baseIcon.shadow = "http://www.zamnoy.com/img/icon/map/shadow_pointer"+transparent+".png";
	
		if (jsonDataElement.level == 1) { 
			icon = new GIcon(baseIcon, shortContextPath + "img/icon/map/country_pointer"+transparent+".png");
		} else if (jsonDataElement.level == 2) {
			icon = new GIcon(baseIcon, shortContextPath + "img/icon/map/region_pointer"+transparent+".png");
		} else if (jsonDataElement.level == 3) {
			icon = new GIcon(baseIcon, shortContextPath + "img/icon/map/town_pointer"+transparent+".png");
		} else {
			icon = new GIcon(baseIcon, shortContextPath + "img/icon/map/place_pointer"+transparent+".png");
		}
		
		 
	} else if (resourcesTypeId == 1) { 
		icon = new GIcon(baseIcon, shortContextPath+"img/icon/map/resources_pointer.png");
	} else if (resourcesTypeId == 2) {
		icon = new GIcon(baseIcon, shortContextPath+"img/icon/map/photo_pointer.png");
	} else if (resourcesTypeId == 3) {
		icon = new GIcon(baseIcon, shortContextPath+"img/icon/map/video_pointer.png");
	} else if (resourcesTypeId == 4) {
		icon = new GIcon(baseIcon, shortContextPath+"img/icon/map/articles_pointer.png");
	} else if (resourcesTypeId == 5) {
		icon = new GIcon(baseIcon, shortContextPath+"img/icon/map/people_pointer.png");
	} else if (resourcesTypeId == 6) {
		icon = new GIcon(baseIcon, shortContextPath+"img/icon/map/online_pointer.png");
	}

	var marker = new GMarker(point, icon);

	var allowLocationClick = document.getElementById('geo_upl_frame') != null;
	if (allowLocationClick) {
		GEvent.addListener(marker, "click", function () {
			document.location = contextPath + 'place/'+jsonDataElement.level+'/' + jsonDataElement.place_id;
		});
	}	
	GEvent.addListener(marker, "mouseover", function () {
		locationHints.show(jsonDataElement.location_id, this.marker);
	});
	GEvent.addListener(marker, "mouseout", function () {
		locationHints.hide();
	});
	return marker;
}

function loadLabels(levelId, placeId, contextPath) {
	fetchLabels(levelId, placeId, true, contextPath);
}  
function updateLabels(levelId, placeId, contextPath) {
	if (notShownMarkerId != null) {
		fetchLabels(levelId, placeId, true, contextPath);
	} else {
	 	fetchLabels(levelId, placeId, false, contextPath);
	}
}  
function fetchLabels(levelId, placeId, force, contextPath) {
	// Do not refresh labels for zoom level <=2
	if (force || map.getZoom()>2) {
	
       	// Clear previous markers
       	map.clearOverlays();
       	//var swPixel = proj.fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom()); 
       	//var nePixel = proj.fromLatLngToPixel(map.getBounds().getNorthEast(),map.getZoom()); 
       	//var swLatLng = proj.fromPixelToLatLng(new GPoint(swPixel.x+100, swPixel.y+20) ,map.getZoom()); 
       	//var neLatLng = proj.fromPixelToLatLng(new GPoint(nePixel.x-20, nePixel.y-20) ,map.getZoom()); 
       	var swLatLng = map.getBounds().getSouthWest();
       	var neLatLng = map.getBounds().getNorthEast(); 
		var url = contextPath + 'ajax/geoLabelsData?swlat=' + swLatLng.lat() 
			+ '&swlng=' + swLatLng.lng() + '&nelat=' + neLatLng.lat() 
			+ '&nelng=' + neLatLng.lng() + '&zoom=' + map.getZoom()
			+ '&type=' + resourcesTypeId;
		if (notShownMarkerId != null) {
			url = url + "&notShownMarkerId=" + notShownMarkerId;
		}
		if (levelId != null) {
			url = url + "&levelId=" + levelId;
		}
		if (placeId != null) {
			url = url + "&placeId=" + placeId;
		}
		url = url + "&time=" + getTimeMs();
		//$("markersUrl").innerHTML = url;
		Gallery.contextPath = contextPath;
		GDownloadUrl(url, process_it);
	}
}

/**
 * Show google map
 */
function showGoogleMap(placeX, placeY, scale, placeName, levelId, placeId, contextPath) {
	if (GBrowserIsCompatible()) {

		if (placeName == null) {
			var placeX = getPlaceXCallback();	
			var placeY = getPlaceYCallback();
			var scale = getScaleCallback();
			var placeName = getPlaceNameCallback();
			var contextPath = getContextPathCallback();
		}

		// === Look for the cookie ===
		if (document.cookie.length>0) {
			cookieStart = document.cookie.indexOf(cookiename + "=");
			if (cookieStart!=-1) {
				cookieStart += cookiename.length+1; 
				cookieEnd=document.cookie.indexOf(";",cookieStart);
				if (cookieEnd==-1) {
					cookieEnd=document.cookie.length;
				}
				cookietext = document.cookie.substring(cookieStart,cookieEnd);
				// == split the cookie text and create the variables ==
				bits = cookietext.split("|");
				mapTypeIndex = parseInt(bits[0]);
				try {
					mapWidth = parseInt(bits[1]);
					mapHeight = parseInt(bits[2]);
					if (resourcesTypeId!=-1) {
						resourcesTypeId = parseInt(bits[3]);
					}
				} catch (err) {}
				
				if (!resourcesTypeId || resourcesTypeId==-1) {
					resourcesTypeId = 0;
				}
			} 
		}
		
		// Adjust map size
		var mapElem = document.getElementById("map");
		mapElem.style.width = mapWidth + "px";
		mapElem.style.height = mapHeight + "px";
		
		// TODO
		getMapSwitchers(mapHeight);
		
		// Adjust resources type
		checkMapResourcesRadioControl();

      	// Display the map
		map = new GMap2(mapElem);
		map.setCenter(new GLatLng(placeX, placeY), scale, map.getMapTypes()[mapTypeIndex]);
		// addControl() must be always called after setCenter() !
		if (overviewMapControl == null) {
		 	overviewMapControl = new GOverviewMapControl()
		}
		map.addControl(overviewMapControl);
		
		var mapTypeControl = new GMapTypeControl();
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 0));
		var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 0));
		map.addControl(mapTypeControl, topRight);
		map.addControl(new GLargeMapControl());
		var proj = new GMercatorProjection(scale); 
		
		// ====== Restricting the range of Zoom Levels =====
		// Get the list of map types      
		var mt = map.getMapTypes();
		// Overwrite the getMinimumResolution() and getMaximumResolution() methods
		for (var i=0; i<mt.length; i++) {
			mt[i].getMinimumResolution = function() {return 1;}
			mt[i].getMaximumResolution = function() {return 19;}
      	}
		
		// Add zoom listener
		GEvent.addListener(map, "zoomend", function () {
			proj = new GMercatorProjection(scale);
			if (resourcesTypeId != 6) {
				loadLabels(levelId, placeId, contextPath);
			}
			storeCurrentZoom();
			//updateDebugInfo();
		});
		
		// Add move listener
		GEvent.addListener(map, "moveend", function () {
			if (resourcesTypeId != 6) {
				updateLabels(levelId, placeId, contextPath);
			}
		});
		
   
	    // arrays to hold copies of the markers and html used by the side_bar
    	// because the function closure trick doesnt work there
    	var HINTS_LOCATIONS = {};
		var locationHints = new THints (HINTS_LOCATIONS, HINTS_CFG);
		var jsonData =[];
		var gmarkers = [];
		var htmls = [];
		var i = 0;

      // This function picks up the click and opens the corresponding info window
		function myclick(i) {
			//locationHints.show(jsonData[i].location_id, this);
			//gmarkers[i].openInfoWindowHtml(htmls[i]);
		}

      
      // ================================================================
      // === Fetch the JSON data file ====
        //updateDebugInfo();
		// Load labels
		loadLabels(levelId, placeId, contextPath);
        
      // ================================================================
      startTrackCoorsChange();
	} else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}
}

// === Set the cookie before exiting ===
function GMapUnload() {

	if (map) {
		var mapElem = document.getElementById("map");
		if (mapElem) {
			if (mapWidth>0 && mapHeight>0) {
				mapTypeIndex = 0;
				for (var i=0;i<map.getMapTypes().length;i++) {
					if (map.getCurrentMapType() == map.getMapTypes()[i]) {
					  mapTypeIndex = i;
					}
				}
				
				var cookietext = cookiename+"=" + mapTypeIndex + "|" + mapWidth + "|" + mapHeight + "|" + resourcesTypeId;
				cookietext += ";path=/";
				if (expiredays) {
					var exdate=new Date();
					exdate.setDate(exdate.getDate()+expiredays);
					cookietext += ";expires="+exdate.toGMTString();
				}

				// == write the cookie ==
				document.cookie=cookietext;
			}
		}
		// == Call GUnload() on exit ==
		GUnload();
	}
}

/**
 * Hide div element
 */
function hideDiv(divName) {
  if (browserType == "gecko" )
     document.poppedLayer = 
         eval('document.getElementById(divName)');
  else if (browserType == "ie")
     document.poppedLayer = 
        eval('document.getElementById(divName)');
  else
     document.poppedLayer =   
        eval('document.layers[divName]');
  document.poppedLayer.style.visibility = "hidden";
}

/**
 * Show div element
 */
function showDiv(divName) {
  if (browserType == "gecko" )
     document.poppedLayer = 
         eval('document.getElementById(divName)');
  else if (browserType == "ie")
     document.poppedLayer = 
        eval('document.getElementById(divName)');
  else
     document.poppedLayer = 
         eval('document.layers[divName]');
  document.poppedLayer.style.visibility = "visible";
}

/**
 * Resize map
 */
function resizeMapBlock(width, height, contextPath) {

	// Unfold block
	var googleMapElem = document.getElementById('googleMap');
	var isOpen = getFoldedBlockCookieValue(googleMapElem.id);
	if (isOpen == 'closed') {
		makeFoldingAction(googleMapElem, false, contextPath, 10);
	}
	
	// Adjust size
	var mapElem = document.getElementById('map');
	if (mapElem.clientHeight != height || mapElem.clientWidth != width) {
		mapElem.style.height = height + "px";
		mapElem.style.width = width + "px";
			
		// Update map size
		if (map) {
			var mapCenter = map.getCenter();
			map.checkResize();
			map.setCenter(mapCenter);
		}
	}
	
	mapWidth = width;
	mapHeight = height;
	
	getMapSwitchers(mapHeight);
}

function getMapSwitchers(height) {

 if (height == 300) {
	 	hideIt('mapLink1');hideIt('spanLink2');showIt('mapLink2');showIt('spanLink1');
	 } else {
	 	hideIt('mapLink2');hideIt('spanLink1');showIt('mapLink1');showIt('spanLink2');
	 }
}

/**
 * Add location click event handler
 */
function addLocationClick(newCoords, notToggleButtons) {
		
	if (notToggleButtons == null) {
		showIt("cancelLink");
		showIt("moveMarkerToCenterLink");
		hideme("mainBlocksArea");
		
		hideIt("map.buttonsCaption");
		hideIt("addPhotoLink");
		hideIt("addVideoLink");	
		hideIt("addArticleLink");		
		hideIt("addLocationLink");
	}

	// Calculate new marker place
	var coords;
	if (newCoords != null) {	
		coords = newCoords;
	} else {	
	 	coords = new GLatLng(map.getCenter().lat()-
				(map.getBounds().getNorthEast().lat() - map.getBounds().getSouthWest().lat())/3, 
				map.getCenter().lng());
		setCoordInputs(coords);
	}
	
	// Add draggable custom marker
	var blueIcon = new GIcon(getBaseIcon(),  "/img/icon/map/new_pointer.png");
	customMarker = new GMarker(coords, {draggable: true, icon:blueIcon});
	
	GEvent.addListener(customMarker, "dragstart", function() {
		map.closeInfoWindow();
	});
	GEvent.addListener(customMarker, "dragend", function() {
		var locIndex = getLocationUnderCustomMarker();
		var result = 'false';
		if (locIndex != null && onLocationUnderCustomMarker != null) {
			result = onLocationUnderCustomMarker(locIndex);
		}
		if (result != 'true') {
			var markerLatLng = customMarker.getPoint();
			map.setCenter(markerLatLng, map.getZoom());		
			setCoordInputs(markerLatLng);
			if (onDragEndHandler) {
				onDragEndHandler();
			}
			//customMarker.openInfoWindowHtml(markerLatLng.lat() + ","+ markerLatLng.lng());
		}		
	});
	map.addOverlay(customMarker);
	if (newCoords == null) {
		if (resourcesTypeId != 0) {
			customMarker.openInfoWindowHtml("<strong>Максимально приблизьте карту и поместите маркер на нужное место</strong><br /><em>Совет:</em> установите показывать всё на карте - возможно это место уже существует");
		} else {
			customMarker.openInfoWindowHtml("<strong>Максимально приблизьте карту<br />и поместите маркер на нужное место</strong>");
		}
	}
}

/**
 * Cancel location click event handler
 */
function cancelClick() {
	try {
		window.stop();
	} catch (err) {}
	
	try {
		window.document.execCommand('Stop');
	} catch (err) {}
	
	cleanAddResourceForm();
	hideIt("cancelLink");
	hideIt("moveMarkerToCenterLink");
	
	showme("mainBlocksArea");

	showIt("map.buttonsCaption");
	showIt("addPhotoLink");
	showIt("addVideoLink");	
	showIt("addArticleLink");		
	showIt("addLocationLink");
	
	map.removeOverlay(customMarker);	
	customMarker = null;
	
	var up = document.getElementById('upload_progress');
	
	if (up) {
		up.style.display = 'none';
	}
	
	IGNORE_UNLOAD = true;
}

function setCoordInputs(coords) {
	var elX = $("placeBean.x");
	var elY = $("placeBean.y");
	if (elX == null) {
		elX = $("x");
		elY = $("y");
	}
	elX.value = coords.lat();
	elY.value = coords.lng();
	storeCurrentZoom();
}

function storeCurrentZoom() {
	var elScale = $("placeBean.scale");
	if (elScale == null) {
		elScale = $("scale");
	}
	if (elScale != null) {
		elScale.value = map.getZoom();
	}
}

function redirectToLocation(level, id, contextPath) {
	document.location = contextPath + 'place/' + level + '/' + id;
}

function redirectToLocationById(locationId, contextPath) {
	document.location = contextPath + 'locredirect/' + locationId;
}

function cleanAddResourceForm() {
	$("addResourceForm").innerHTML = '';
	var errEl = document.getElementById("errorMsg");
	if (errEl != null) {
		errEl.innerHTML = "";
	}
}

function hideLocationAddForm() {
	cleanAllErrors();
	
	hideme('locationAddFormId');
}

function showLocationAddForm() {
	showme('locationAddFormId');
}

function makeDraggable(locationId) {
	for (var i = 0; i < all_locations.length; i++) {
		if (all_locations[i] == locationId) {
			notShownMarkerId = all_locations[i];
			map.removeOverlay(all_markers[i]);
			addLocationClick(all_markers[i].getPoint());
			break;
		}
	}
}

function reloadMapOverlays(contextPath) {
	map.clearOverlays();
	loadLabels(contextPath);
}

function showChoosenMap(contextPath) {
	if (!checkCoords('placeBean.x', 'placeBean.y')) {
		return;
	}
	resourcesTypeId = -1;
	var name =  document.getElementById("placeBean.placeName").value;
	if (name == '') {
		name = document.getElementById("geoName").value;
	}
	var x = document.getElementById("placeBean.x").value;
	var y = document.getElementById("placeBean.y").value;
	var scale = parseInt(document.getElementById("placeBean.scale").value);

	afterMarkersLoadHandler = function() {
		hideme('showLocationLink');
		var coords = new GLatLng(x, y);
		addLocationClick(coords, true);
		showme('coordsLabel');
		showme('coordsHolder');

		if (document.getElementById("geoLocationHolder").style.display != 'none') {
			var locNameEl = document.getElementById("geoName");
			var locIdEl = document.getElementById("locationId");
			document.getElementById("placeBean.parentLocationId").value = locIdEl.value;
			document.getElementById("placeBean.parentGeoName").value = locNameEl.value;
		}	
	};
	onDragEndHandler = function() {
		var elMapUsed = document.getElementById("mapUsed");
		if (elMapUsed.value != 'true') {
			elMapUsed.value = 'true';
			document.getElementById("customLocation").value = 'true';		
			showHiddenPlaceInputs();			
		}
	}
	onCoorsChangeHandler = function() {
		var x = document.getElementById("placeBean.x").value;
		var y = document.getElementById("placeBean.y").value;
		if ((x!='') && (y!='') && isFloat(x) && isFloat(y)) {
			var coords = new GLatLng(x, y);
			customMarker.setPoint(coords);
			map.setCenter(coords);
			onDragEndHandler();
		}
	}
	customMarker = null;
	showme("map");		

	loadMap(x, y, scale, name, contextPath);
	showme("moveMarkerToCenterLink");
}

function cleanCoords(notShowLocLinks) {
	/*if (label != null) {
		document.getElementById("geoNameLabelText").innerHTML = label;
	}*/
	hideme('map');
	hideme("moveMarkerToCenterLink");

	var parName = document.getElementById("placeBean.parentGeoName").value;
	var parId = document.getElementById("placeBean.parentLocationId").value;
	document.getElementById("locationId").value = parId;
	document.getElementById("geoName").value = parName;

	document.getElementById("mapUsed").value = 'false';
	document.getElementById("customLocation").value = 'false';
	
	hideme('coordsLabel');
	hideme('coordsHolder');	
	hideme('pl_name');
	//hideme('placeNameLabel');
	//hideme('placeNameHolder');
	hideme('pl_type');
	//hideme('placeTypeLabel');
	//hideme('placeTypeHolder');
	hideme('parentLocationLabel');
	hideme('parentLocationHolder');
	hideme('geoParamsSeparator');

	if (notShowLocLinks == null || notShowLocLinks == false) {
		showme('geoLocationLabel');
		showme('geoLocationHolder');
		showme('showLocationLink');
	}
}

function showLocationOnMap(locElem, contextPath) {
	resourcesTypeId = -1;
	if (typeof contextPath != "undefined") {
		root = contextPath;
	}
	var url = 'my/ajax/locgeometry';
	if (typeof root != "undefined"){
		url = root + url;
	}	
	var locationId = document.getElementById(locElem).value;
	/*
	 * Load location geometry
	 */
	AjaxRequest.post({
		'url':url,
		'parameters':{
			'locationId':locationId
		},
		"onSuccess":			
			function (req) {
				var geometry = eval("(" + req.responseText + ")");
				document.getElementById("placeBean.x").value = geometry.x;
				document.getElementById("placeBean.y").value = geometry.y;
				document.getElementById("placeBean.scale").value = geometry.scale;
									
				showChoosenMap(contextPath);
			},
		"onLoading":function() { 
			showLoadingProgress(document.getElementById("defaultDisplayElement")); 
		},
		"onComplete": function() { hideLoadingProgress(); },
		"onError": function (req) { 
			hideLoadingProgress(); 
			alert("Ошибка...");	
		}			
	});
	return false;
}

function onCoorsChange(coordElId) {
	changeStated = false;
	lastUpdateTime = getTimeMs();
	
	var coordEl = document.getElementById(coordElId);
	var coordValue = coordEl.value;
	if (coordValue.indexOf(",") != -1) {
		coordValue = coordValue.replace(",", ".");
		coordEl.value = coordValue;
	}
	while (coordValue.indexOf(" ") != -1) {
		coordValue = coordValue.replace(" ", "");
		coordEl.value = coordValue;
	}
	var validEl = document.getElementById(coordElId + "_val");
	var minValue;
	var maxValue;
	if (coordElId.indexOf('y') != -1) {
		minValue = -180;
		maxValue = 180;
	} else {
		minValue = -90;
		maxValue = 90;	
	}
	if (coordValue == "") {
		validEl.innerHTML = "";
	} else if (isFloat(coordValue) && (parseFloat(coordValue) >= minValue) && (parseFloat(coordValue) <= maxValue)) {
		validEl.innerHTML = "<span class='valid'>+</span>";
		changeStated = true;
	} else {
		validEl.innerHTML = "<span class='invalid'>!</span>";
	}
	var mapUsedEl = document.getElementById("mapUsed");
	if (mapUsedEl != null && mapUsedEl.value != 'true') {
		mapUsedEl.value = 'true';
		var customLocationEl = document.getElementById("customLocation");
		customLocationEl.value = 'true';
		showHiddenPlaceInputs();
	}
}

function getTimeMs() {
	return (new Date()).getTime();
}

function checkCoordsChange() {
	if (changeStated) {
		if ((getTimeMs()-lastUpdateTime) > 3000) {
			onCoorsChangeHandler();
			changeStated = false;
		}
	}
	setTimeout("checkCoordsChange()", 1500);
}

function startTrackCoorsChange() {
	if (onCoorsChangeHandler != null) {
		setTimeout("checkCoordsChange()", 1500);
	}
}

function isFloat(t) {
	return +t==t;
}

function showAddToLocationForm(uri, contextPath) {
	if (customMarker != null) {
		cancelClick();
	}
	Gallery.loadSimpleContent(uri, 'addResourceForm', contextPath);
}

function getLocationUnderCustomMarker() {
	var locationInxex;
	var proj = new GMercatorProjection(20);
	var pixel = proj.fromLatLngToPixel(customMarker.getLatLng(), map.getZoom());
	var x = pixel.x;
	var y = pixel.y;

	for (var i = 0; i < all_markers.length; i++) {
		var pixel = proj.fromLatLngToPixel(all_markers[i].getLatLng(), map.getZoom());
		var underX = pixel.x;
		var underY = pixel.y;
		if (Math.abs(underX - x) < 10 && Math.abs(underY - y) < 10) {
			locationInxex = i;
			break;
		}
	}
	return locationInxex;
}

/**
 * Change map resources displaying type click action listener
 */
function changeMapResourcesTypeClick(levelId, placeId, typeId, contextPath) {
	var f = document.getElementById('mapViewOrderForm');
	if (f != null) {
		for (var i=0, size= f.mapView.length; i < size; i++) { 
			if (f.mapView[i].id) {
				var l = document.getElementById(f.mapView[i].id + '.label');
				if (l != null) {
					if ( (f.mapView[i].checked)) {
						l.className = "decoredText1";
						resourcesTypeId = typeId;
						fetchLabels(levelId, placeId, true, contextPath);
					} else {
						l.className = "";
					}
				}
			}
		}
	}
}

/**
 * Check and highlight radio button 
 */
function checkMapResourcesRadioControl() {
	var f = document.getElementById('mapViewOrderForm');
	if (f != null && resourcesTypeId != null && f.mapView[resourcesTypeId].id != null) {
		var l = document.getElementById(f.mapView[resourcesTypeId].id + '.label');
		l.className = "decoredText1";
		f.mapView[resourcesTypeId].checked = true;
	}
}

function showHiddenPlaceInputs() {
	showme('pl_name');
	//showme('placeNameLabel');
	//showme('placeNameHolder');
	showme('pl_type');
	//showme('placeTypeLabel');
	//showme('placeTypeHolder');
	showme('parentLocationLabel');
	showme('parentLocationHolder');
	showme('geoParamsSeparator');
	hideme('geoLocationLabel');
	hideme('geoLocationHolder');
}

function checkCoords(xElName, yElName) {
	var clEl = document.getElementById("customLocation");
	if (clEl != null && clEl.value != 'true') {
		return true;
	}	
	var xEl = document.getElementById(xElName);
	var yEl = document.getElementById(yElName);
	var x = xEl.value;
	var y = yEl.value;	
	var xIsValid = true;
	var yIsValid = true;		
	if (x != "" && !isFloat(x)) {
		xIsValid = false;
	}
	if (y != "" && !isFloat(y)) {
		yIsValid = false;
	}
	var result = true;
	if (!xIsValid && !yIsValid) {
		alert('Поля Х и Y содержат числа недопустимого формата');
		result = false;
	} else if (!xIsValid || !yIsValid) {
		var fieldName;
		if (!xIsValid) {
			fieldName = "X";
		} else {
			fieldName = "Y";
		}
		alert('Поле ' + fieldName + ' содержит число недопустимого формата');
		result = false;
	} else {
		if (parseFloat(x) < -90 || parseFloat(x) > 90) {
			alert('Координата Х должна быть в диапазоне от -90 до +90 градусов');
			result = false;
		} else if (parseFloat(y) < -180 || parseFloat(y) > 180) {
			alert('Координата Y должна быть в диапазоне от -180 до +180 градусов');
			result = false;		
		}
	}
	return result;
}

function loadMap(placeX, placeY, scale, placeName, contextPath) {
	getPlaceXCallback = function() { return placeX; };
	getPlaceYCallback = function() { return placeY; };
	getScaleCallback = function() { return scale; };
	getPlaceNameCallback = function() { return placeName; };
	getContextPathCallback = function() { return contextPath; };
	google.load('maps', '2', {'language' : 'ru', 'callback': showGoogleMap});
}

function removeMarker() {
	map.removeOverlay(customMarker);	
	customMarker = null; 
}