// массив всех созданных на странице карт
var gmaps = new Array();

function objectsCount(array)
{
	length = 0;
	for (var object in array) 
	{
		length++;
	}
	return length;
}

function doNothing() {}
function downloadUrl(url, callback) 
{
	var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;

    request.onreadystatechange = 
    	function() 
    	{
    		if (request.readyState == 4) 
    		{
    			request.onreadystatechange = doNothing;
    			callback(request.responseText, request.status);
    		}
    	};

    request.open('GET', url, true);
    request.send(null);
}
  
function NewMarkerControl(controlDiv, map) 
{
	// Set CSS styles for the DIV containing the control
	controlDiv.style.padding = '5px';
	
	// Set CSS for the control border
	var controlUI = document.createElement('DIV');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'solid';
	controlUI.style.borderWidth = '2px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = 'Нажмите, чтобы добавить на карту новую точку';
	controlDiv.appendChild(controlUI);
	
	// Set CSS for the control interior
	var controlText = document.createElement('DIV');
	controlText.style.fontFamily = 'Arial,sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.paddingLeft = '4px';
	controlText.style.paddingRight = '4px';
	controlText.innerHTML = '+Маркер';
	controlUI.appendChild(controlText);

	// Setup the click event listeners: simply set the map to Chicago
	google.maps.event.addDomListener(controlUI, 'click', 
		function() 
		{
			createMarker(map, 'marker' + Math.floor(Math.random()*9999), map.getCenter(), '', true, false);
		}
	);
}

function createMarker(map, markerid, point, description, doShowEd, readonly) 
{
	if (typeof(map.markers[markerid]) != "undefined")
	{
		alert('Попытка создания дубликата маркера!');
		return null;
	}

	var marker = new google.maps.Marker({
		position: point,
		map: map,
		draggable: !readonly
	});
	
	marker.readonly = readonly;
	marker.description = description;
	marker.infowindow = new google.maps.InfoWindow({content: ''});
	marker.infowindow.marker = marker;
	marker.infowindowEd = new google.maps.InfoWindow({content: ''});
	marker.infowindowEd.marker = marker;
	
	marker.id = markerid;
	map.markers[marker.id] = marker; 
	
	google.maps.event.addListener(marker, 'click', 
		function() 
		{
			if (!marker.readonly)
			{
				marker.infowindow.close();
				marker.infowindowEd.setContent('<table width="100%"><tr width="100%"><td width="100%"><textarea rows="5" style="width: 100%;" id="'+marker.id+'mdesc">'+marker.description.replace(/"/g,'&quot;')+'</textarea></td></tr>  <tr><td align="right"><input class="form_elements1" type="button" id="mok" value="ok" onclick="updateMarkerFromInfoWindowEd(\''+marker.map.id+'\',\''+marker.id+'\');"/></td></tr></table>'); 
				marker.infowindowEd.open(map,marker);
			}
			else
			{
				marker.infowindow.open(map,marker);
			}
		}
	);
    google.maps.event.addListener(marker, 'dragend', 
    	function() 
    	{
    		google.maps.event.trigger(marker, 'click');
    	}
    );			
			
	if (doShowEd) google.maps.event.trigger(marker, 'click');
	else 
		showMarkerInfoWindow(map,marker);
	
	if (objectsCount(map.markers) > 1)
		mapZoomAllMarkers(map);
	
	return marker;
}

function updateMarkerFromInfoWindowEd(mapid,markerid)
{
	gmaps[mapid].markers[markerid].description = document.getElementById(gmaps[mapid].markers[markerid].id+'mdesc').value;
	gmaps[mapid].markers[markerid].infowindowEd.close();
	showMarkerInfoWindow(gmaps[mapid], gmaps[mapid].markers[markerid]);
	
    var url = "/gmap/setmarker.html?mapid=" + mapid + "&markerid=" + markerid + "&tablename=" + gmaps[mapid].tablename + "&tablerowid=" + gmaps[mapid].tablerowid + "&description=" + encodeURI(gmaps[mapid].markers[markerid].description) + "&lat=" + gmaps[mapid].markers[markerid].getPosition().lat() + "&lng=" + gmaps[mapid].markers[markerid].getPosition().lng();
    downloadUrl(url, 
    	function(data, responseCode) 
    	{
    		if (responseCode == 200) 
    		{
    			alert(data);
    			//infowindow.close();
    			//document.getElementById("message").innerHTML = "Location added.";
    		}
    	}
    );
}

function showMarkerInfoWindow(map,marker)
{
	marker.infowindow.setContent(marker.description); 
	if (marker.description)
		marker.infowindow.open(map,marker);
}

function createMap(mapid,lat,lng,zoom, tablename,tablerowid)
{
	if (typeof(gmaps[mapid]) != "undefined")
	{
		alert('Попытка создания дубликата карты!');
		return null;
	}
	
	var center = new google.maps.LatLng(lat,lng);
	var options = {
	    zoom: zoom,
	    center: center,
	    mapTypeId: google.maps.MapTypeId.HYBRID,
	    mapTypeControl: true,     
	    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU} 
	   };
	var map = new google.maps.Map(document.getElementById(mapid),options);
	
	var newMarkerControlDiv = document.createElement('DIV');
	var newMarkerControl = new NewMarkerControl(newMarkerControlDiv, map);
	newMarkerControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(newMarkerControlDiv);	
	
	map.markers = new Array();
	
	map.tablename = tablename;
	map.tablerowid = tablerowid;
	
	map.id = mapid;
	gmaps[mapid] = map;
	
	return map;
}

function mapZoomAllMarkers(map)
{
	var bounds = new google.maps.LatLngBounds()
	for (var mi in map.markers) 
		bounds.extend(map.markers[mi].getPosition());
	map.fitBounds(bounds);
}

