// JavaScript Document
var http_request = false;
   function makeBUSRequest(url, parameters) {
	  
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
   
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function CalbusContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('calc_bus').innerHTML = result;  
			 norm_btn();
			if (document.getElementById("tprice_all")) {
    			document.getElementById("bv_off").innerHTML = "<input name='bereken2' id='button_calc' type='button' value='Bevestig Offerte' onclick='checkstart()'    />";
				} else {
				document.getElementById("bv_off").innerHTML = "";
				}
				
         } else {
			 norm_btn();
            alert('Er heeft zich een probleem bevonden in de aanvraag.');
         }
      }
   }
   

    var currentcheck = 'none';
	var des = '';
	
	var setstart = 0;
	var setend = 0;
	var calc = 0;
	var que = 0;
	var currunning = "";

     //Declare global variables
    var geocoder = null;
    var router = null;
    var routePoints = [];
    var routePointsCount = null;
    var geocodedPointsCount = null;
    var routeID = null;
    var viaLocs = new Array();
    var startLoc = null;
    var destLoc = null;
	
	var des_t = "";
	var des_k = "";
	var s_t = "";
	var s_k = "";

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

    function map24ApiLoaded(){
     Map24.MapApplication.init( { NodeName: "maparea" } );
    }

    function startRouting(){
		
		
		if (currentcheck == 'start'){
	document.getElementById("cstart").innerHTML = " <img src='/pix/ajax-loader(2).gif' width='10' height='10' />";
	
	setend = 0;
	calc = 0;
	currunning = 'start';
	document.getElementById("btn_calc").innerHTML = "<div style='float:left; width:25px;'> <img src='/_files/images/calc_load.gif' height='19' width='19' /></div><div id='statdiv'  style='float:left; height:19px; line-height:19px; vertical-align:middle;'> Vertrek Valideren </div>";
		}
		if (currentcheck == 'end') {
			
	document.getElementById("cend").innerHTML = " <img src='/pix/ajax-loader(2).gif' width='10' height='10' />";
	
	currunning = 'end';
	setend = 0
	calc = 0;
	document.getElementById("btn_calc").innerHTML =  " <div style='float:left; width:25px;'> <img src='/_files/images/calc_load.gif' height='19' width='19' /></div><div  id='statdiv'  style='float:left; height:19px; line-height:19px; vertical-align:middle;'> Retour Valideren</div>";
			
		}
		if (currentcheck == 'calc') {
			currunning = 'calc'
	document.getElementById("btn_calc").innerHTML = "<div style='float:left; width:25px;'> <img src='/_files/images/calc_load.gif' height='19' width='19' /></div><div  id='statdiv' style='float:left; height:19px; line-height:19px; vertical-align:middle;'>  Offerte Berekenen </div>";
		}
		
		
		act_btn()
     //Initializealert('Active'); the array for storing route points
     routePoints = {};
     //Initialize the counter for geocoded addresses
     geocodedPointsCount = 0;

     //Retrieve start and destination of the route from the input fields
     var start = Map24.trim( 'hamweg 3 horst' );
     var destination = Map24.trim(  $v(des) );

var vias = [];
     for( var i=0; i < 4; i++ ){
      if( Map24.trim( $v( "via_"+i ) ) != "" )
       vias.push( $v("via_"+i) );
     }

       //Create a counter that contains the number of route points
     routePointsCount = 2 + vias.length;

     //Create a geocoder stub
     if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();

     //Geocode the start address of the route
     geocoder.geocode({
      SearchText: start,
      CallbackFunction: setRoutePoint,
      CallbackParameters: {position: "start"}
     });

     //Geocode the destination address of the route.
     geocoder.geocode({
      SearchText: destination,
      CallbackFunction: setRoutePoint,
      CallbackParameters: {position: "destination"}
     });

     //Geocode the via points.
     for( var i=0; i < vias.length; i++ ) {
      geocoder.geocode({
       SearchText: vias[i],
       CallbackFunction: setRoutePoint,
       //Specify the position in the array of via points in the CallbackParameters field
       //with an additional parameter (index).
       CallbackParameters: { position: "via", index: i }
      });
     }
   }

   //Callback function that is called when the geocoding result is available.
   //The locations parameter contains an array with multiple alternative geocoding results.
   //The params parameter passes the value of CallbackParameters that specifies which route
   //end point is returned (start or destination point).
   function setRoutePoint(locations, params){

    //Check if the geocoded address is a via point.
    if( params.position == "via") {
     //Check if via points were provided in the request at all.
     if( typeof routePoints[ "via" ] == "undefined")
      routePoints[ "via" ] = [];
      //Store the via point
      routePoints[ params.position ][ params.index ] = locations[0];
     }
     else
      //Store the geocoded start or destination point
      routePoints[ params.position ] = locations[0];

     //Increment the counter for geocoded addresses
     geocodedPointsCount++;

     //If all addresses are geocoded successfully, this function calls the calculateRoute() function.
     if( geocodedPointsCount == routePointsCount ) {
      calculateRoute();
     }
    }
if (currunning == 'start') {
	document.getElementById("cstart").innerHTML = "<img src='/pix/del.png' height='10' width='10'  />";
}
	if (currunning == 'end') {
	document.getElementById("cend").innerHTML = "<img src='/pix/del.png' height='10' width='10'  />";
	}
    //Calculate the route. The via points are added in the ViaPoints field.
    function calculateRoute() {

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

     //Calculate the route.
     router.calculateRoute({
      Start: routePoints["start"],
      Destination: routePoints["destination"],
      ViaPoints: routePoints["via"],
      CallbackFunction: displayRoute,
      //The ShowRoute parameter is set to false, the route is not shown automatically.
      //This is necessary if you want to change the default color used for showing the route.
      //To show the route call the Map24.RoutingServiceStub.showRoute() function in the callback function.
      ShowRoute: false
     });
    }

     
    //Callback function used to access the calculated route of type Map24.WebServices.Route
    //and to print a detailed route description.
    function displayRoute( route ){
     //Remember the routeId. It is used e.g. to hide the route.
  
    //Access the assumed time needed for traversing the route in hours
    var totalTime = ((route.TotalTime)/(60*60) ).toPrecision(3)
    //Access the total lenght of the route in kilometers
    var totalLength = (route.TotalLength/1000)
	

	

	
		var sstrt = "";
	var estrt = "";
	var place = "";
	var street = "";
	
    for(var i = 0; i < route.Segments.length; i++){
     for(var j = 0; j < route.Segments[i].Descriptions.length; j++){
		 if (i == 0)  {
      sstrt = (i) + ". " + route.Segments[i].Descriptions[j].Text + "<br />";
		 }else if (i == route.Segments.length-1)  {
      estrt = (i) + ". " + route.Segments[i].Descriptions[j].Text + "<br />";
		 }
    }
   }
   findadress(estrt) ;

	 clearInterval(dotval);
	
	 clearInterval(intval);
	if (currunning == 'start') {
		document.getElementById("cstart").innerHTML = "<img src='/pix/check.png' height='10' width='10'  /> ";
		setstart = 1
		s_t = totalTime;
		s_k = totalLength;
		setTimeout(checkend, 500);
	}
	if (currunning == 'end') {
		document.getElementById("cend").innerHTML = "<img src='/pix/check.png' height='10' width='10'  /> ";
		setend = 1
		des_t = totalTime;
		des_k = totalLength;
		setTimeout(calcbusroute, 500);
	}
	if (currunning == 'calc') {
			document.getElementById("calc_load").innerHTML = "";
	}
	
   if (setstart == 1 && setend == 1 && calc == 1) {
	
	var time_v = ''
	var time_a = '';
	var pick_v = '';
	var pick_a = '';
	var r_time = des_t;
	r_km = des_k;
	var s_time  = s_t ;
	s_km =  s_k ;
	
	
	if (document.getElementById('v_radio_aankomst').checked == true){
		time_v = document.getElementById('v_time_aankomst').value;
		pick_v = 'a'
	
	}else {
		pick_v = 'v'
		time_v = document.getElementById('v_time_vertrek').value;
	} 
	
	
	
	if (document.getElementById('r_radio_aankomst').checked == true){
		time_a = document.getElementById('r_time_aankomst').value;
		pick_a = 'a';
	} else {
		pick_a = 'v';
		time_a = document.getElementById('r_time_vertrek').value;
	}
	
	if (document.getElementById('v_radio_retour').checked == true){
		var rtype = 1 ;
	}else{
		var rtype = 0 ;
	}
	
	 var poststr1 = "ttime=" + encodeURI( totalLength ) +
	  				"&thour=" + encodeURI( totalTime )		+
					"&vtime=" + encodeURI( time_v ) +
					"&btime=" + encodeURI( time_a ) +
					"&vdate=" + encodeURI(document.getElementById('alternate_vertrek').value ) +
					"&bdate=" + encodeURI(document.getElementById('alternate_retour').value ) +
					"&admin=" + encodeURI(document.getElementById('name').value ) +
					"&v_pick=" + encodeURI( pick_v ) +
					"&r_pick=" + encodeURI( pick_a ) +
					"&tper=" + encodeURI(document.getElementById('personen').value )+
					"&backt=" +  encodeURI(r_time)  +
					"&backd=" + encodeURI(r_km) +
					"&startt="  + encodeURI(s_time) +
					"&startk=" + encodeURI(s_km)  +
					"&rtype=" + encodeURI(rtype) ;
    makeBUSRequest('buscheck/actions.php', poststr1);
	http_request.onreadystatechange = CalbusContents;
   }
 
   
   
   
	  	 router.removeRoute({RouteId: routeID});
  		 startLoc.remove();
  		 destLoc.remove();
   
   for(var i = 0; i < routePointsCount-2; i++){
    viaLocs[i].remove();
   }
   
   
   currunning = "";

  }

		

  //Remove route
  function removeRoute(routeID) {
   router.removeRoute({RouteId: routeID});
   startLoc.remove();
   destLoc.remove();
   
   for(var i = 0; i < routePointsCount-2; i++){
    viaLocs[i].remove();
   }

  }

  //Helper function for accessing the div specified in the id parameter.
  //The function checks first if the div contains  akbaridesign content.
  function $v( id ) {
   return (document.getElementById( id ).value != "undefined") ?
   document.getElementById( id ).value : "";
  }

	function checkstart(){
		
		if (s_km == null) {
			currentcheck = "start";
			des = 'sdes';
			startRouting()
		}else {
			checkend();
		}
	}
	
	function checkend(){
		
		
		if ( r_km == null ){
			currentcheck = "end";
			des = 'bestemming_des';
			startRouting()
		} else {
			setend = 1
			calcbusroute();
		}
	
	}
	

	function calcbusroute(){
			document.getElementById('via_0').value = document.getElementById('sdes').value;
			calc = 1;
			currentcheck = 'calc';
			startRouting()
	}
	
	function act_btn(){
		timer();
		document.getElementById("btn_calc").style.display = 'block';
		document.getElementById("btndiv").innerHTML = ""
		document.getElementById("calc_bus").innerHTML = ""
		
		
	}
	
	function norm_btn(){
		document.getElementById("btn_calc").style.display = 'none';
		document.getElementById("btndiv").innerHTML = "<input name='bereken2' id='button_calc' type='button' value='Bereken offerte' onclick='checkstart()'    /><span id='bv_off'></span>"
		
	}
	
	var r_km ;
	var s_km ; 
	var intval=""
	var dotval=""
	var inint = 0;
	var dotint = 0;
	var dottemp = "";
	var totdot = "";
	
	function checktime(){
		if (inint == 0) {
		 startRouting();
		 inint = 1;
		 dottemp += '(!)';
		}else{
			norm_btn();
		}
	}
	
	function timer(){
		intval= setInterval("checktime()",8000)
		dotval= setInterval("dots()",1000)
		dottemp = document.getElementById("statdiv").innerHTML;
	}
   
   
   function dots(){
	   if (dotint == 0){
		   dotint = 1;
		   totdot = ".";
		   document.getElementById("statdiv").innerHTML = (dottemp + totdot);
	   }else if (dotint == 1){
		   dotint = 2;
		   totdot = "..";
		   document.getElementById("statdiv").innerHTML = dottemp + totdot;
	   }else if (dotint == 2){
		  totdot = "...";
		   dotint = 0;
		   document.getElementById("statdiv").innerHTML = dottemp + totdot;
	   }
	   
   }
/////////////// Bus Calculate
