// Icons

var baseIcon = new GIcon();
baseIcon.shadow = "/bkRestaurantMapPlugin/images/marker_shadow.png";
baseIcon.image = "/bkRestaurantMapPlugin/images/marker.png";
baseIcon.iconSize = new GSize(75, 65);
baseIcon.shadowSize = new GSize(75, 65);
baseIcon.iconAnchor = new GPoint(17, 64);
baseIcon.infoWindowAnchor = new GPoint(19, 5);

var startIcon = new GIcon();
startIcon.shadow = "/bkRestaurantMapPlugin/images/marker_shadow.png";
startIcon.image = "/bkRestaurantMapPlugin/images/marker_start.png";
startIcon.iconSize = new GSize(75, 65);
startIcon.shadowSize = new GSize(75, 65);
startIcon.iconAnchor = new GPoint(17, 64);
startIcon.infoWindowAnchor = new GPoint(19, 5);


var specialIcon = new GIcon();
specialIcon.shadow = "/bkRestaurantMapPlugin/images/marker_stadion_shadow.png";
specialIcon.image = "/bkRestaurantMapPlugin/images/marker_stadion.png";
specialIcon.iconSize = new GSize(99, 75);
specialIcon.shadowSize = new GSize(99, 75);
specialIcon.iconAnchor = new GPoint(39, 73);
specialIcon.infoWindowAnchor = new GPoint(40, 5);

function initialize(latitude, longitude, zoom) {
	if (GBrowserIsCompatible()) {
		var location = new GLatLng(latitude, longitude);
		
		map = new GMap2(document.getElementById("map_canvas"));
		
		map.setCenter(location, zoom);
		map.removeMapType(G_HYBRID_MAP);
		map.removeMapType(G_SATELLITE_MAP);
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		map.firstRun = true;
		
		mgr = new MarkerManager(map);
		routingmgr = new MarkerManager(map);
		specialmgr = new MarkerManager(map);
		routingmgr.hide();
		
		map.allMarkers = [];
		map.specialMarkers = [];

		if($('type') !== null && $('type').value == 'map') {
			specialmgr.addMarker(createSpecialMarker(location, $('specialMarker').value, specialIcon),1);
		};
		
		new Ajax.Request($('initMarkers').value, {
			onSuccess: function(transport) {
				objects = transport.responseJSON;
				if(objects != null) {
					for(i in objects) {
						if(typeof(objects[i]) == 'object') {
//							var latlng = new GLatLng(objects[i].longitude, objects[i].latitude);
							var latlng = new GLatLng(objects[i].latitude, objects[i].longitude);
							map.allMarkers[objects[i].id] = createMarker(latlng, objects[i].id);
							mgr.addMarker(map.allMarkers[objects[i].id], 1);
						}
					}
				};
				
				if($('type') !== null && $('type').value == 'route') {
					if($('routingFrom') !== null && $('routingTo') !== null) {
						if($('specialMarker') !== null) {
							calculateDirection($('routingFrom').value, $('routingTo').value, $('specialMarker').value, true);
						} else {
							calculateDirection($('routingFrom').value, $('routingTo').value);
						}
					}
				}
			}
		});
		 
	}

	Event.observe($('jumpToForm'), 'submit', function(event) {		
		event.stop();
		jumpTo();
		return false;
	});
	Event.observe($('jumpToButton'), 'click', function(event) {		
		event.stop();
		jumpTo();
		return false;
	});
}

function getLatlng(to) {
	new Ajax.Request($('translate').value + '?address='+ encodeURI(to), {
		onSuccess: function(transport) {
			var result = transport.responseJSON;
			if(result != '') {
				return new GLatLng(result.latitude, result.longitude);
			} else {
				return false;
			}
		}
	});
}

function showContent(url, storeId) {
	var hideRouteBit = '';
	if(routingmgr.visible()) {
		hideRouteBit = '&hideRoute=true';
	};
	new Ajax.Request(url +'?storeId='+ storeId + hideRouteBit, {
		onSuccess: function(transport) {
			$('storeInfoGroup').replace(transport.responseText);
			map.getExtInfoWindow().resize();
		},
		evalScripts: true
	});
}

function show(view, storeId, hideRoute) {
	showContent($(view+"Overview").value, storeId, hideRoute);
}

function createMarker(point, storeId) {
	markerOptions = { icon:baseIcon };
	var marker = new GMarker(point, markerOptions);

	GEvent.addListener(marker, "click", function() {
		marker.openExtInfoWindow(
			map,
			"custom_info_window_red_simple",
			"<div id='storeInfoBox'>Loading...</div>",
			{
				ajaxUrl: $('simpleOverview').value + "?storeId="+ storeId,
				beakOffset: 5,
				ajaxCallback: function() {
					if(routingmgr.visible() && $('routeLink') !== null) {
						$('routeLink').style.visibility = 'hidden';
					};
				}
			}
		);
	});
	return marker;
}

function createSpecialMarker(point, specialKey, specialIcon) {
	if(specialIcon === undefined) {
		specialIcon = baseIcon;
	}
	markerOptions = { icon:specialIcon, clickable: false };
	var marker = new GMarker(point, markerOptions );
	map.specialMarkers[specialKey] = marker;
	return marker;
}

function jumpTo() {	
	new Ajax.Request($('translate').value + '?address='+ encodeURI($('jumpTo').value), {
		onSuccess: function(transport) {
			result = transport.responseJSON;
			if(result != '') {
				map.closeExtInfoWindow();
				map.setZoom(11);
				map.panTo(new GLatLng(result['latitude'], result['longitude']));
			}
		}
	});
}


function closePrint() {
	
	routingmgr.clearMarkers();
	routingmgr.hide();
	map.clearOverlays();
	mgr.show();
	map.directionsContainer.clear();
	$('wrapper').removeChild($('printLink'));

	
	
}

function calculateDirection(fromParam, toParam, storeId, isSpecial) {
	if(fromParam === undefined && toParam === undefined) {	
		var from = $('routeFrom').value;
		var to = $('routeTo').value;
		var storeId = $('storeId').value;
	} else {
		var from = fromParam;
		var to = toParam;
		var storeId = storeId;
		var isSpecial = isSpecial;
	}
	map.clearOverlays();
	new Ajax.Request($('translate').value + '?address='+ encodeURI(from), {
		onSuccess: function(transport) {
			var result = transport.responseJSON;
			if(result != '') {
				if(from != '' && to != '') {
					if(typeof(map.directionsContainer)=='object') {
						map.directionsContainer.clear();
					};
					var directions = new GDirections(map);
					map.directionsContainer = directions;
					directions.load("from: " + from + " to: " + to);
					
					GEvent.addListener(directions, "addoverlay", function() {
						directions.getMarker(0).hide();
						directions.getMarker(1).hide();

						if(map.firstRun == true && $('specialMarker') !== null && $('specialMarker').value == 'bayern') {
							map.firstRun = false;
						} else {
							mgr.hide();
						}
						
						routingmgr.show();
						showPrintLink(from, to);
						
						if(isSpecial) {
							routingmgr.addMarker(createSpecialMarker(directions.getMarker(0).getLatLng(), storeId, startIcon), 1);
							routingmgr.addMarker(createSpecialMarker(directions.getMarker(1).getLatLng(), storeId, specialIcon), 1);
						} else {
							routingmgr.addMarker(createSpecialMarker(directions.getMarker(0).getLatLng(), storeId, startIcon), 1);
							routingmgr.addMarker(map.allMarkers[storeId], 1);
						}
					});
					
					GEvent.addListener(directions, "error", function() {
						showRoutingError(from);
					});
					
					
				}
			}
		}
	});
}

function showDirectionStart() {
	Event.observe($('routeForm'), 'submit', function(event) {
		event.stop();
		calculateDirection();
		return false;
	});
	map.getExtInfoWindow().resize();
}

function showPrintLink(from, to) {
	map.closeExtInfoWindow();
	if(!$('printLink')) {
		var printWrapper = new Element('div', {'id': 'printLink'});
		Wrapper = new Element('div', {'id': 'printLink'});
		$('wrapper').appendChild(printWrapper);
	}
	$('printLink').update('<span class="removeButton"><a href="javascript:closePrint(\''+ from +'\', \''+ to +'\');">Routenansicht schließen</a></span><span class="printButton"><a href="javascript:showPrint(\''+ from +'\', \''+ to +'\');">Route drucken</a></span>');

}

function showPrint(from, to) {
	window.open('http://maps.google.com/maps?f=d&source=s_d&saddr='+ from +'&daddr='+ to +'&hl=de&mra=ls&ie=UTF8&t=h&z='+ map.getZoom() +'&pw=2', 'printWindow');
}

function showRoutingError(search) {
	mgr.show();
	
	var link = new Layer($('routeError').value, {
			width: 		243,
			topOffset:	200,
			leftOffset:	null,
			overlay:	true,
			objBody:	$$('body')[0],
			centerOffset: true,
			select: true
		});
	
}

function hideRoutingError() {
	// Wird aufgerufen um das Routinglayer zu schließen
	mgr.show();
}