var map;
var mmgr = false; 
var polys = [];
var points = [];
var line = [];
var offices = [];
var objects = [];
var regions = []; 
var region_id;
var current_marker;
var poly;
var contextmenu;

function loadMap() {    
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mapka"));
		map.setCenter(new GLatLng(office_lat, office_lng), 12);
		map.setUIToDefault();

		show_offices();
		show_objects(); 
		
		contextmenu = document.createElement("div");
		contextmenu.id = 'context_menu';

		contextmenu.innerHTML =	'<p><a href="#" onclick="centerMap();">Centruj mapę</a></p>'
							+ '<p><a href="#" onclick="zoomIn();">Przybliż</a></p>'
							+ '<p><a href="#" onclick="zoomOut();">Oddal</a></p>'
							+ '<p class="sep" /><p><a href="#" onclick="findPlace();">Gdzie jestem?</a></p>'; 

		map.getContainer().appendChild(contextmenu);

		GEvent.addListener(map, 'singlerightclick', function(marker, point) {
			if (current_marker)
				map.removeOverlay(current_marker); 
			clickedPixel = marker;
			
			var point2 = map.fromContainerPixelToLatLng(marker);
			current_marker = new GMarker(point2, {icon:curr_p});
			map.addOverlay(current_marker); 

			var x = marker.x;
			var y = marker.y;
			if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
			if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
			var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
			pos.apply(contextmenu);
			contextmenu.style.visibility = 'visible';
		});
		
		GEvent.addListener(map, 'click', function(marker, point) {
			if (current_marker)
				map.removeOverlay(current_marker); 
			contextmenu.style.visibility = 'hidden';
		});
		
		/*GEvent.addListener(map, 'dblclick', function(marker, point) {
			$('#mapka').addClass('fullscreen');
		});	*/	
		
		GEvent.addListener(map, 'movestart', function(marker, point) {
			if (current_marker) 
				map.removeOverlay(current_marker); 
			contextmenu.style.visibility = 'hidden';
		});

		geocoder = new GClientGeocoder();
		
		show_region(region_id);
		
		if (region_id == 9) { // Trojmiasto
			show_region(31); // North
			show_region(32); // South
		} 
	}
}	

GMarker.prototype.openAjaxInfoWindow = function(office_id) {
	var marker = this;
	GDownloadUrl('/gmaps_ajax.php?action=get_info&office_id=' + office_id + '&lang=' + lang, function(info, response_code) {
		if (response_code == 200) {
			marker.openInfoWindowHtml(info);
		} else {
			alert('Nie można pobrać opisu...');
		}
	}); 
}

function panToOffice(id) {
	map.panTo( new GLatLng(offices[id].lat, offices[id].lng) );
	offices[id].openAjaxInfoWindow(offices[id].office_id); 
	return false;
}

function panToObject(id) {
	map.panTo( new GLatLng(objects[id].lat, objects[id].lng) );
	openObjectInfoWindow(id); 
}

function openObjectInfoWindow(object_id) {
	var marker = objects[object_id];
	GDownloadUrl('/gmaps_ajax.php?action=get_object_info&object_id=' + object_id, function(info, response_code) {
		if (response_code == 200) {
			marker.openInfoWindowHtml(info);
		} else {
			alert('Nie można pobrać opisu...');
		}
	}); 
}

function openObjectEditWindow(object_id) {
	GDownloadUrl('gmaps_ajax.php?action=get_object_info&object_id=' + object_id, function(content, response_code) {
		if (response_code == 200) {
			objects[object_id].openInfoWindowHtml( content );
		} else {
			alert('Nie można pobrać opisu...');
		}
	}); 	
}

function addOffice(id, lat, lng, min_zoom, max_zoom, office_id) { 
	var marker = new GMarker(new GLatLng(lat, lng), { icon:office_icon } );
	marker.id = id;
	marker.lat = lat;
	marker.lng = lng;
	marker.office_id = office_id;
	marker.min_zoom = min_zoom;
	marker.max_zoom = max_zoom;
	marker.change = false;
	marker.cat = 'office';
	
	map.addOverlay(marker); 
	//mmgr.addMarker(marker, min_zoom, max_zoom);

	GEvent.addListener(marker, 'click', function() {
		marker.openAjaxInfoWindow(office_id);
	});	
	
	GEvent.addListener(marker,'dragstart',function() {
		//setActiveMarker(marker);
		marker.closeInfoWindow(); 
	});
	
	GEvent.addListener(marker,'dragend',function() {
		if (marker.change == true) {
			var point = marker.getLatLng();
			marker.lat = point.lat().toFixed(8);
			marker.lng = point.lng().toFixed(8);		
			editMarker(id);
		} else {	
			marker.setLatLng( new GLatLng(lat, lng) );
			marker.openAjaxInfoWindow(office_id);
		}
	});  
	
	offices[id] = marker;
}

function show_offices() { 
	GDownloadUrl('/gmaps_ajax.php?action=get_offices&region_id=' + region_id + '&promoted=' + promoted, function(dane, response_code) {
		if (response_code == 200) {
			var xml = GXml.parse(dane);
			var markery = xml.documentElement.getElementsByTagName("office");
			
			for (var i=0; i<markery.length; i++) {
				var id			=	parseInt(markery[i].getAttribute("id"));
				var lat			=	parseFloat(markery[i].getAttribute("lat"));
				var lng			=	parseFloat(markery[i].getAttribute("lng"));
				var min_zoom	=	markery[i].getAttribute("min_zoom");
				var max_zoom	=	markery[i].getAttribute("max_zoom");
				var office_id	=	markery[i].getAttribute("office_id");
				addOffice(id, lat, lng, min_zoom, max_zoom, office_id);
			}
		} else {
			//alert('Nie można pobrać danych.');
		}
	});
}

function show_objects() { 
	GDownloadUrl('/gmaps_ajax.php?action=get_objects&region_id=' + region_id, function(dane, response_code) {
		if (response_code == 200) {
			var xml = GXml.parse(dane);
			var markery = xml.documentElement.getElementsByTagName("object");
			var bounds = new GLatLngBounds();

			for (var i=0; i < markery.length; i++) {
				var id			=	parseInt(markery[i].getAttribute("id"));
				var lat			=	parseFloat(markery[i].getAttribute("lat"));
				var lng			=	parseFloat(markery[i].getAttribute("lng"));
				var min_zoom	=	markery[i].getAttribute("min_zoom");
				var max_zoom	=	markery[i].getAttribute("max_zoom");
				var icon		=	markery[i].getAttribute("icon");
				addObject(id, lat, lng, min_zoom, max_zoom, icon);
			}
		} else {
			//alert('Nie mogłem pobrać danych.');
		}
	});
}

function importanceOrder(marker) {  
	return marker.importance*1000000;  
}

function addObject(id, lat, lng, min_zoom, max_zoom, type) { 
	var ikonka = new GIcon();
	switch (type) {
		case 'airport': ikonka = airport_icon; break;
		case 'railway': ikonka = railway_icon; break;
		case 'pks': ikonka = pks_icon; break;
		case 'subway': ikonka = subway_icon; break;
		case 'pkin': ikonka = pkin_icon; break;
		case 'neptun': ikonka = neptun_icon; break;
		case 'panorama_raclawicka': ikonka = panorama_raclawicka_icon; break;
		case 'sukiennice': ikonka = sukiennice_icon; break;
		case 'laweczka_tuwima': ikonka = laweczka_tuwima_icon; break;
		case 'kosciol_mariacki': ikonka = kosciol_mariacki_icon; break;
		case 'spodek': ikonka = spodek_icon; break;
		case 'mtp': ikonka = mtp_icon; break;
		default: ikonka = default_icon;
	}
	
	var object = new GMarker(new GLatLng(lat, lng), { icon: ikonka, zIndexProcess:importanceOrder } );
	object.importance = id; 
	object.id = id;
	object.lat = lat;
	object.lng = lng;
	object.min_zoom = min_zoom;
	object.max_zoom = max_zoom;
	object.change = false;
	object.cat = 'object';
	map.addOverlay(object); 

	GEvent.addListener(object, 'click', function() {
		openObjectInfoWindow(id);
	});	
	
	GEvent.addListener(object, 'dragstart', function() {
		object.closeInfoWindow(); 
	});	

	GEvent.addListener(object,'dragend',function() {
		if (object.change == true) {
			var point = object.getLatLng();
			object.lat = point.lat().toFixed(8);
			object.lng = point.lng().toFixed(8);		
			editObject(id);
		} else {	
			object.setLatLng( new GLatLng(lat, lng) );
			openObjectInfoWindow(id);
		}
	}); 
	objects[id] = object;
}

function centerMap() {
	var point = map.fromContainerPixelToLatLng(clickedPixel)
	map.setCenter(point);
	map.removeOverlay(current_marker);
	contextmenu.style.visibility = "hidden";
}

function zoomIn() {
	var point = map.fromContainerPixelToLatLng(clickedPixel);
	map.removeOverlay(current_marker);
	contextmenu.style.visibility = "hidden";
	map.zoomIn(point, true);
}

function zoomOut() {
	var point = map.fromContainerPixelToLatLng(clickedPixel);
	map.removeOverlay(current_marker);
	contextmenu.style.visibility = "hidden";
	map.zoomOut(point, true);
}

function findPlace() {
	var point = map.fromContainerPixelToLatLng(clickedPixel)
	
	map.removeOverlay(current_marker);
	contextmenu.style.visibility = "hidden";

	geocoder.getLocations(point, function(response) {
		if (!response || response.Status.code != 200) {
			alert('Nie udało się ustalić adresu!');
		} else {
			map.setCenter(point);
			var address	= response.Placemark[0].address;
			var latlng	= new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);
			
			var text = '<div class="found_place"><p class="title">Szczegóły klikniętego punktu:</p><p>Współrzędne:' + latlng + '</p><p>Adres: ' + address + '</p></div>';

			var marker = new GMarker(latlng, { icon:question_icon });
			map.addOverlay(marker); 			
			marker.openInfoWindowHtml(text);
			
			GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(text);
			});	
		}
	});
}

function show_region(region, arrange) {
	GDownloadUrl('/gmaps_ajax.php?action=get_region_bounds&region_id=' + region, function(dane, response_code) {
		if (response_code == 200) { 
			var xml = GXml.parse(dane);
			var points = xml.documentElement.getElementsByTagName("point");
			var lat, lng;
			var bounds = new GLatLngBounds();

			for (var i = 0; i < points.length; i++) {
				lat = parseFloat(points[i].getAttribute("lat"));
				lng = parseFloat(points[i].getAttribute("lng"));
				line.push( new GLatLng(lat, lng) ); 
				if (arrange != 0)
					bounds.extend( new GLatLng(lat, lng) );
			}	
			
			poly = new GPolyline(line, '#FF0000', 5, 0.6);
			line = [];
			
			poly.cat = 'regions';
			regions.push(poly);
			//map.addOverlay(poly);	

			if (poly.getVertexCount() > 2) {
				first_lat = poly.getVertex(0).lat();
				first_lng = poly.getVertex(0).lng();
				
				last_lat = poly.getVertex(poly.getVertexCount() - 1).lat();
				last_lng = poly.getVertex(poly.getVertexCount() - 1).lng();
				
				if (first_lat == last_lat && first_lng == last_lng) { 
					var new_zoom = map.getBoundsZoomLevel(bounds);
					var new_point = bounds.getCenter();
					if (arrange != 0)
						map.setCenter(new_point, new_zoom);	
				} 
			}
				
			polys[region] = poly;			
			map.addOverlay(polys[region]);				
		} else {
			//alert('Error in show_region()...');
		}
	});
}

function showAddress() {
	var address = document.getElementById("search_address").value;
	geocoder.getLatLng(
		address,
		function(latlng) {
			if (!latlng) {
				alert(address + " not found");
			} else {
				var address = $('#search_address').val();
				var info = '<p class="italic">' + address + '</p>';
				var marker = new GMarker(latlng, { icon:info_icon });
				
				GEvent.addListener(marker, 'click', function() {
					marker.openInfoWindowHtml(info);
				});	
				
				map.addOverlay(marker);
				marker.openInfoWindowHtml(info);
				
				map.setCenter(latlng, 13);
			}
		}
	);
}

$( function(){
	$(document).click( function(e){
		if ($(e.target).parent().attr('class') != 'select_office' && $(e.target).parent().parent().attr('class') != 'select_office'){
			$('#biura').hide();
		}
		if ($(e.target).parent().attr('class') != 'select_district' && $(e.target).parent().parent().attr('class') != 'select_district'){
			$('#district').hide();
		}		
	});
	
	$('#pane').jScrollPane({scrollbarWidth:17, scrollbarMargin:10});
	$('#biura').hide();
	//$('#district').hide();
	
	$('#pane p').click( function() {
		$('#biura').hide();
	});

	$("div.select_office").click( function() {
		if ($('#biura').is(':hidden'))
			$('#biura').show();
		else
			$('#biura').hide();
	}); 
	
	$("div.select_district").click( function() {
		if ($('#district').is(':hidden'))
			$('#district').show();
		else
			$('#district').hide();
	}); 	

	$('#search_address').click( function() {
		if ($(this).val() == 'Miasto, ulica numer' || $(this).val() == 'City, street number') {
			$(this).removeClass('empty');
			$(this).val('');
		}	
	});
	 
	$('#search_address').blur( function() {
		if ($(this).val() == '') {
			$(this).addClass('empty');
			if (lang == 'pl')
				$(this).val('Miasto, ulica numer');
			else
				$(this).val('City, street number');
		}
	});			
	
	$('#show_address').click( function() {
		showAddress( $('#search_address').val() );
	});
});
