var MapObject = null;
var MapBaseObject = null;
var MapBaseLocation = null;
var MapGeocoder = null;
var MapFoundPlaces = [];
var MapRouter = null;
var MapRoutePoints = [];
var MapRouteID = null;
var MapObjects = new Array();
var MapLanguage = 'en';

function MapGoToStep(step) {
	$('#mapcontrol').show();
	$('#mapcontrol .step').hide();
	$('#mapcontrol #mapstep' + step).show();
}

function MapLoadApi(language, location) {
	MapLanguage = language;
	MapBaseObject = location;
	Map24.loadApi( ["core_api", "wrapper_api"] , MapApiLoaded);
}

function MapApiLoaded() {
	MapObject = Map24.MapApplication;
	MapObject.init({
		NodeName: "maparea"
	});
	MapObject.Map.addListener("Map24.Event.MapViewChanged", MapViewChanged);
	MapObject.Map.addListener( "Map24.Event.MapClick", MapClicked );  
	MapSetPosition();
	MapGoToStep(1);
	$('#mapfound').change(MapShow);
	$('#mapfrom').focus(function() {
		$(this).filter("[@value='" + Text.MapDefaultLocation + "']").val('');
	}).blur(function() {
		$(this).filter("[@value='']").val(Text.MapDefaultLocation);
	}).val(Text.MapDefaultLocation);
	$('#mapinfo').hide();
	$('#maproute').show();
	if (typeof MapBaseObject.Objects == 'object') {
		for (var i = 0; i < MapBaseObject.Objects.length; i++) {
			MapObjects[i] = new Map24.Location(MapBaseObject.Objects[i]);
			MapObjects[i].commit();
			MapDebug('Creating: ' + MapBaseObject.Objects[i].Description + '<br>');
		}
	}
	MapBaseLocation = new Map24.Location(MapBaseObject);
    MapBaseLocation.commit();
    MapBaseLocation.show();
}

function MapViewChanged(e) {
	var DiffX = e.ClipRect.TopLeft.Longitude - e.ClipRect.LowerRight.Longitude;
	var DiffY = e.ClipRect.TopLeft.Latitude - e.ClipRect.LowerRight.Latitude;
	var Distance = Math.sqrt(DiffX * DiffX + DiffY * DiffY);
	for (var i = 0; i < MapObjects.length; i++) {
		if (Distance < 1.8) {
			MapObjects[i].show();
			MapDebug('Show: ' + i + '<br>');
		} else {
			MapObjects[i].hide();
			MapDebug('Hide: ' + i + '<br>');
		}
	}
	MapDebug('Dist: ' + Distance + '<br>');
}

function MapClicked(e){
	MapDebug('Position: ' + "Longitude: " + e.Coordinate.Longitude + ", Latitude: " + e.Coordinate.Latitude + '<br>');
}

function MapSetPosition() {
	MapObject.center({
		Longitude: MapBaseObject.CenterLongitude,
		Latitude: MapBaseObject.CenterLatitude,
    	MinimumWidth: MapBaseObject.Zoom
	});
}

function MapSearch() {
	var start = $("#mapfrom[value!='" + Text.MapDefaultLocation + "']").val();
	start = (typeof start == 'undefined' ? '' : Map24.trim(start));
	if (start == "") {
		MapError(Text.MapErrorNoLocation);
		return;
	}
	if (MapGeocoder == null)
		MapGeocoder = new Map24.GeocoderServiceStub();
	MapGeocoder.geocode({ 
		SearchText: start, 
		CallbackFunction: MapPrintFoundPlaces
	});
}
function MapPrintFoundPlaces(locations) {
	var city = null;
	var zip = null;
	var street = null;
	var houseNo = null;
	var result = "";

	for (var i = 0; i < MapFoundPlaces.length; i++) {
	    MapFoundPlaces[i].remove();
	}
	MapFoundPlaces = locations;

	if (MapFoundPlaces.length == 0) {
		MapError('Nie znaleziono adresu');
	}
	
	for (var i = 0; i < MapFoundPlaces.length; i++) {
		city = MapFoundPlaces[i].getCity();
		zip = MapFoundPlaces[i].getZip();
		street = MapFoundPlaces[i].getStreet();
		houseNo = MapFoundPlaces[i].getHouseNo();
		zip == null ? zip = "": zip = ""+zip;
		city == null ? city = "": city = " "+city;
		street == null ? street = "": street = ", "+street;
		houseNo == null ? houseNo = "": houseNo = " "+houseNo;
		result += '<option value="'+i+'">'+zip+city+street+houseNo+'</option>';
	    MapFoundPlaces[i].SymbolId = 20958;
		MapFoundPlaces[i].commit();
	}

	$('#mapfound').html(result).get(0).selectedIndex = 0;

	if (MapFoundPlaces.length == 1)
		MapRoute();
	else
		MapShow();

	MapGoToStep(2);
}

function MapShow() {
	var start = $('#mapfound').val();
	if (typeof start != undefined) {
		for (var i = 0; i < MapFoundPlaces.length; i++) {
		    MapFoundPlaces[i].hide();
		}
		MapObject.center({
			Longitude: MapFoundPlaces[start].getLongitude(),
			Latitude: MapFoundPlaces[start].getLatitude()
		});
		MapDebug(MapFoundPlaces[start].getLongitude() + ', ' + MapFoundPlaces[start].getLatitude() + '<br>');
	    MapFoundPlaces[start].show();
	}
}

function MapRoute() {
	var start = $('#mapfound').val();
	if (typeof start != undefined) {
		if (MapRouter == null)
			MapRouter = new Map24.RoutingServiceStub();
		if (MapRouteID != null)
			MapRouter.removeRoute({RouteId: MapRouteID});
		MapRouter.calculateRoute({
			Start: MapFoundPlaces[start],
			Destination: MapBaseLocation,
			DescriptionLanguage: MapLanguage,
			CalculationMode: 'Shortest',
			CallbackFunction: MapPrintRoute,
			ShowRoute: false
		});
	}
}
function MapPrintRoute(route) {
	MapRouteID = route.RouteID;
	MapRouter.showRoute( {
		RouteId: MapRouteID,
		Color: ['#518800', 125]
	});
	var totalTime = ((route.TotalTime)/(60*60) ).toPrecision(3);
	totalTime = Math.floor(totalTime) + ':' + Math.round((totalTime - Math.floor(totalTime)) * 60);
	var totalLength = (route.TotalLength/1000) 
	var div_content = '';     
	div_content += '<div class="description"><span>' + Text.MapTotalTime + ':</span> ' + totalTime + ' h</div>';
	div_content += '<div class="description"><span>' + Text.MapTotalLength + ':</span> ' + totalLength + ' km</div>';
	div_content += '<div class="route">';
	
	//Iterate through the route segments and output the step-by-step textual description of the route
	for(var i = 0; i < route.Segments.length; i++){
		if( typeof route.Segments[i].Coordinates != "undefined" ) {
		
		//Access the longitudes and latitudes of the route segment's coordinates array
		var longitudes = route.Segments[i].Coordinates.Longitudes.toString().split("|");
		var latitudes = route.Segments[i].Coordinates.Latitudes.toString().split("|");
		
		//Get the longitude and latitude in the center of the route segment.
		//These values are needed for centering on a route segment. 
		var centerLon = longitudes[parseInt(longitudes.length / 2)];
		var centerLat = latitudes[parseInt(latitudes.length / 2)];
		}
	
		//For each route segment add the route description and the button for centering on the segment
		for(var j = 0; j < route.Segments[i].Descriptions.length; j++){
		//The route description contains tags for further evaluation. For example, the [M24_STREET] tag is used 
		//to denote a street in the description. Add the following line of code to replace these tags by a blank:
		div_content += '<a href="javascript:MapSegmentCenter('+centerLon+', '+centerLat+');" class="step"><span class="stepnumber">' + (i+1) + '</span> ' + route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '') + '</a>'
		}
	}
	$('#maproute').html(div_content);
}

function MapSegmentCenter(longitude, latitude) {
	MapObject.center({
		Longitude: longitude,
		Latitude: latitude,
    	MinimumWidth: 3034
	});
}

  function centerOnSegment (centerLon, centerLat){
  	//Center on the given variable
  }

function MapError(message) {
	$('#maperrorinfo').text(message);
	MapGoToStep('error');
}

function MapDebug(message) {
//	var debug = document.getElementById('mapdebug');
//	if (debug) {
//		debug.innerHTML = debug.innerHTML + message;
//	}
}

