var markers;
var maxxIcon_grey;
var maxxIcon_red;
var object_id = 0;

var map;
var geocoder;

function initMap(){
	map = new GMap2(document.getElementById('map'));
	map.addControl(new GSmallZoomControl3D());
	
	geocoder = new GClientGeocoder();
	
	maxxIcon_red = new GIcon();
	maxxIcon_red.image = "/images/maxx-map-marker.png";
	maxxIcon_red.iconSize = new GSize(19, 25);
	maxxIcon_red.iconAnchor = new GPoint(14, 25);
	maxxIcon_red.infoWindowAnchor = new GPoint(14, 14);
	
	maxxIcon_grey = new GIcon();
	maxxIcon_grey.image = "/images/maxx-map-marker-grijs.png";
	maxxIcon_grey.iconSize = new GSize(19, 25);
	maxxIcon_grey.iconAnchor = new GPoint(14, 25);
	maxxIcon_grey.infoWindowAnchor = new GPoint(14, 14);
}

function initHomeMap(address, zoom){
	initMap();
	
	geocoder.getLatLng(
		address,
		function(point) {
			map.setCenter(point, zoom);

			$.ajax({
				url : "/ajax/get_markers.php",
				type: "GET",
				dataType : "text",        					
 				complete : setMarkers
 			});
		}
	);
}


function initObjectMap(address, objectPoint){
	initMap();
	
	geocoder.getLatLng(
		address +", Nederland",
		function(point) {
			map.setCenter(point, 15);

			$.ajax({
				url : "/ajax/get_markers.php",
				type: "GET",
				dataType : "text",        					
				complete : setMarkers
			});
		}
	);
	
	var marker = new GMarker(objectPoint, {icon:maxxIcon_red});
	map.addOverlay(marker);
}


function setMarkers(xhr, status){
	eval("markers = "+ xhr.responseText);

	for(var i=0; i < markers.length; i++)
	{
		
		if(markers[i][3] == "" || markers[i][4] == ""){
			getLongLat(markers[i], maxxIcon_red);
		}
		else{
			if(object_id > 0){
				if(markers[i][0] != object_id){
					setMarker(markers[i], maxxIcon_grey);
				}
				else{
					setMarker(markers[i], maxxIcon_red);
				}
			}
			else{
				setMarker(markers[i], maxxIcon_red);
			}
		}
	}
}


function getLongLat(address, markerIcon){
	geocoder.getLatLng(								    	
		address[1],
		function(point) {
			if(point){
				$.ajax({
					url : "/ajax/upd_coord.php?id="+ address[0] +"&long="+ point.x +"&lat="+ point.y,
					type: "GET",
					dataType : "text"
				});

				var marker = new GMarker(point,{icon:markerIcon});
				map.addOverlay(marker);
				GEvent.addListener(marker, "click", function() {
					location.href = address[5];
				});
			}
		}
	);
}


function setMarker(q, markerIcon){
	if(q[3] != "" && q[4] != ""){
		var marker = new GMarker(new GPoint(q[3], q[4]), {icon:markerIcon});
		map.addOverlay(marker);
		GEvent.addListener(marker, "click", function() {
			location.href = q[5];
		});
	}
}