 var geocoder = null;
 var router = null;
 var routePoints = [];
 var routeID = null;
 var startPointAltern = new Array();
 var destPointAltern = new Array();
 var startLoc = null;
 var destLoc = null;
 var outOfArea = null;
 var startCounty = null;
 var orgHTML = null;

 function goMap24() {
	Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );  

	orgHTML = document.getElementById('fp_result').innerHTML;
 }

 function map24ApiLoaded(){

/*	Map24.MapApplication.setStartMapView( {
		UpperLeftLongitude: 700,
		UpperLeftLatitude: 3500,
		LowerRightLongitude: 400,
		LowerRightLatitude: 2700
	});
*/
	Map24.MapApplication.init( { NodeName: "map" } );
 }

 function startRouting(){				//Geocode given start and destination points by click on button.

	pageTracker._trackPageview('Taxirechner.html - startGeocoding');

	routePoints = {};								//Init array for storing route points

	if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();

	var start = Map24.trim( $v('start_strasse') + ' ' + $v('start_ort') );	// + $v('start_plz') + ' ' 
	var destination = Map24.trim( $v('ziel_strasse') + ' ' + $v('ziel_ort') );  // + $v('ziel_plz') + ' ' 

	if( start == "" ) { alert("Bitte geben Sie den Startpunkt der Tour ein!"); return; }
	if( destination == "" ) { alert("Bitte geben Sie das Ziel der Tour ein!"); return; }

		wait = "<option>...Ihr Startpunkt wird geprueft...</option>";
		if( Map24.Browser.IE )	{		
			document.getElementById("geocodingresultsStart").outerHTML ='<select name="printGeocodingResult" class="ortswahl_select"  id="geocodingresultsStart">'+wait+'</select>';
			document.getElementById("geocodingresultsDestination").outerHTML ='<select name="printGeocodingResult" class="ortswahl_select"  id="geocodingresultsDestination">'+wait+'</select>';
		} else {document.getElementById("geocodingresultsStart").innerHTML = wait;
			document.getElementById("geocodingresultsDestination").innerHTML = wait;
	 	}

	geocoder.geocode({				//Geocode the start address of the route
		SearchText: start,
		MaxNoOfAlternatives: 25,
		CallbackFunction: printGeocodingResult,
		Language: "de",
		Country: "DE",
		CallbackParameters: {position: "start"}
	});

	geocoder.geocode({
		SearchText: destination,
		MaxNoOfAlternatives: 25,
		Language: "de",
		Country: "DE",
		CallbackFunction: printGeocodingResult,
		CallbackParameters: {position: "destination"}
	});


}

 function printGeocodingResult( locs, params ){	//Called when geocode result for start or dest available. Prints all alternative geocoded addr for start and dest points
						//in two lists to select one from each for route calc. (locs array contains geocoded addr).
	var county = null;
	var city = null;
	var zip = null;
	var street = null;
	var houseNo = null;
	var state = null;
	var option = "";
	var result = "";
	var index = 0;

	for( var i=0; i<locs.length; i++ ){			//Iterate through the array of geocoded addresses

		country	= locs[i].getCountry();			//Access the fields of the geocoded address
		county	= locs[i].getCounty();
		city	= locs[i].getCity();
		zip	= locs[i].getZip();
		street	= locs[i].getStreet();
		houseNo	= locs[i].getHouseNo();
		state	= locs[i].getState();
     
		state	== county? county = null : "";		//Clean county if duplicate with state or city.
		city	== county? county = null : "";

		city	== null? city = "": city = " "+city;	//Empty field isn't shown in result list - otherwise, field's value is shown with added notes.
		zip	== null? zip = "": zip = ""+zip;
		street	== null? street = "": street = ""+street;
		houseNo	== null? houseNo = "": houseNo = " "+houseNo;
		county	== null? county = "": county = ", "+county;
		state	== null? state = "": state = ""+state;

		option = "<option>"+street+houseNo+" * "+zip+city+" ("+state+county+")</option>";
	
		if (result.indexOf(option) == -1)  {		//Add non duplicated, geocoded address to result list and store data in a list 
			result += option;
			params.position == "start" ? startPointAltern[index] = locs[i] : destPointAltern[index] = locs[i];
			index++;     	
		}
	}

	if (params.position=="start") {		//Print alternative geocoded addresses for start and dest point in a list
        
		if( Map24.Browser.IE )			//Show geocoded alternatives for the start point in a list
			document.getElementById("geocodingresultsStart").outerHTML ='<select name="printGeocodingResult" class="ortswahl_select"  id="geocodingresultsStart">'+result+'</select>';
		else	document.getElementById("geocodingresultsStart").innerHTML = result;

	} else {
      
		if( Map24.Browser.IE )
        		document.getElementById("geocodingresultsDestination").outerHTML ='<select name="printGeocodingResult" class="ortswahl_select" id="geocodingresultsDestination">'+result+'</select>';
		else	document.getElementById("geocodingresultsDestination").innerHTML = result;
	}

	document.getElementById("box1").style.visibility = "hidden";
	document.getElementById("box1").style.display = "none";

	document.getElementById("geocodingResults").style.display = "block";
	document.getElementById("geocodingResults").style.visibility = "visible";
	document.getElementById("fp1").style.backgroundColor="#FFDFE4";
	document.getElementById("fp2").style.backgroundColor="#FFDFE4";

	pageTracker._trackPageview('Taxirechner.html - showGeocoding');
 }

 function setRoutePoints(){					//Called after click. Accesses selected start and dest from list and init route calc.

	document.getElementById('fp_result').innerHTML = orgHTML;			//reset html to default

	var start = document.forms["start"]["geocodingresultsStart"].selectedIndex;		//Get index of selected start and destination
	var dest = document.forms["dest"]["geocodingresultsDestination"].selectedIndex;

	if (startPointAltern[start].getLongitude() != destPointAltern[dest].getLongitude() || startPointAltern[start].getLatitude() != destPointAltern[dest].getLatitude() ) {
			routePoints["start"] = startPointAltern[start];				//Store selected route points in routePoints array
			routePoints["destination"] = destPointAltern[dest];
	} else {	
			alert ("Start- und Zielpunkt sind identisch. Keine Berechnung möglich."); return;
	}

	document.getElementById('div_vhb').innerHTML = "<strong> *** Fahrtkosten werden berechnet *** </strong>";

	if (startPointAltern[start].getCounty()) {
		startPointAltern[start].getCounty() != destPointAltern[dest].getCounty() ? outOfArea = 1 : outOfArea = -1;
		startCounty = startPointAltern[start].getCounty();
	} else {
		startPointAltern[start].getState() != destPointAltern[dest].getState() ? outOfArea = 1 : outOfArea = -1;
		startCounty = startPointAltern[start].getCity();
	}

	if (startPointAltern[start].getState() == "Hessen")	startCounty = startPointAltern[start].getCounty() + ' : ' + startPointAltern[start].getCity();

	calculateRoute();
 }

 function calculateRoute() { //alert(destination);

	if( router == null ) router = new Map24.RoutingServiceStub();	//Create a routing service stub

	router.calculateRoute({
		Start: routePoints["start"],
		Destination: routePoints["destination"],

		CallbackFunction: displayRoute,

		ShowRoute: false	//ShowRoute param is set to false, the route isn't shown automatically. This is necessary if you want to change default color for showing route.
					//To show route call Map24.RoutingServiceStub.showRoute() function in callback function.
	});
 }


 function displayRoute( route ){    	//Accesses calculated route of type Map24.WebServices.Route - Shows route on map, adds location marks at start and dest. points, 
					//prints detailed route descript and provides a button next to each entry in route descript that allows to center on a route segment.

	div_min = (route.TotalTime / 60).toFixed(0); 	    			//data ready for html
	div_km = (route.TotalLength / 1000).toFixed(0);

	u = 'tcalc.php?' + escape(startCounty) + '--' + (route.TotalLength/1000).toFixed(1) + '--' + outOfArea ;  //alert(u);
	get( u , 'getPHPValues');
 }

 function displayHTML (min, km){		//Called after php calculation.

	pageTracker._trackEvent('Taxirechner', 'Result' + outOfArea, PHPVal[0] + ' : '+ startCounty, km);
	pageTracker._trackPageview('_Response ' + PHPVal[0] + startCounty);
	pageTracker._trackPageview('Taxirechner.html - Result');

	var HTMLzu = ""; //(22 - 6 Uhr bzw. Sa/So/Feiertag: &nbsp;&nbsp;" ;
	PHPVal[3] ? HTMLzu = HTMLzu + "" + PHPVal[3] + ": &nbsp;&nbsp;" : HTMLzu = HTMLzu + "Nachts bzw. Sonn-/Feiertags: &nbsp;&nbsp;";
	PHPVal[2] == 0 ? HTMLzu = HTMLzu + "<i>kein Zuschlag</i>" : HTMLzu = HTMLzu + " ca.&nbsp;&nbsp; + " + PHPVal[2] + ",- EUR";
//	PHPVal[4] == 0 ? HTMLzu = HTMLzu + "<br>Großraumtaxi:  &nbsp;&nbsp; <i>kein Zuschlag</i>" : HTMLzu = HTMLzu + "<br>Großraumtaxi: &nbsp;&nbsp; ca. &nbsp;&nbsp;" + PHPVal[3] + ",- EUR";


	var HTMLmessage = "";
	if(PHPVal[0] < 1) HTMLmessage = " * Durchschnittswert (kein Regional-Tarif gefunden) <br>";
	if(outOfArea > 0) HTMLmessage = HTMLmessage + "** Preis frei verhandelbar, da kein Pflichtfahrgebiet.";
	
	document.getElementById("div_vhb").innerHTML = HTMLmessage + "&nbsp;" ;

	document.getElementById('div_zeit').innerHTML = "ca. " + min + " Minuten";
	document.getElementById('div_laenge').innerHTML = "ca. " + km + " km";  //alert ('div: ' + PHPVal[1]);
	document.getElementById('div_preis').innerHTML = "ca. &nbsp;&nbsp;" + PHPVal[1] + ",- EUR  (Normal-Tarif bis zu 4 Personen)";
	document.getElementById('div_preis_zu').innerHTML = HTMLzu;

	document.getElementById("alert").style.display = "block"; 
	document.getElementById("alert").style.visibility = "visible";

	document.getElementById('fp1').style.backgroundColor='#FEFBE1';
	document.getElementById('fp2').style.backgroundColor='#FEFBE1';

	document.getElementById('foot1').style.visibility='visible';
	document.getElementById('foot2').style.visibility='visible';
	
 }

 function removeRoute(routeID) {				//Removes a route. After that, a new route can be calculated.

	document.getElementById('fp_result').innerHTML = orgHTML;			//reset html to default

	document.getElementById("geocodingResults").style.display = "none"; 
	document.getElementById("geocodingResults").style.visibility = "hidden";

	document.getElementById("box1").style.display = "block"; 
	document.getElementById("box1").style.visibility = "visible";
 }
    
 function $v( id ) { 		//Helper for accessing html-tag specified in id parameter. Checks first if html-tag contains content.
	return (document.getElementById( id ).value != "undefined") ? document.getElementById( id ).value : ""; 
 }

 function get(url, callback_function, return_xml){

	var http_request = false;

	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 	http_request.overrideMimeType('text/xml; charset= iso-8859-1');

	} else if(window.ActiveXObject) {
		try {		http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {	try {	http_request = new ActiveXObject("Microsoft.XMLHTTP");	} catch (e) {}
		}
	}
	if (!http_request) {
		pageTracker._trackPageview('Taxirechner.html - noRequest');
		alert('Leider unterstützt Ihr Browser diese Funktion nicht.');
		return false;
	} else {
		pageTracker._trackPageview('Taxirechner.html - Request');
	}
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {	(return_xml) ?  eval(callback_function + '(http_request.responseXML)') :  eval(callback_function + '(http_request.responseText)');
			} else {				alert('Problem: ' + http_request.status + ')');
			}
		}
	}
	http_request.open('GET', url, true);
	http_request.send(null);
 }

 function getPHPValues ( result ) {

	PHPVal = result.split(';');
	displayHTML(div_min,div_km);

//	alert (unescape('PHP: ' + PHPVal));
 }
