
var dirn; 
var eol;
var points;
var map;
var route;
      	     
      
var rules = {
	'.go' : function(el) {
		el.onclick = function() {
			$('path').className='showpath';
			$('path').innerHTML='';
					
			var req = 'from: ' + $F('from') + ' to: ' + $F('to');
			 var startpoint = $F("from");
        	 var endpoint   = $F("to");
	//		dirn.load(req , {getSteps:true});
			dirn.loadFromWaypoints([startpoint,endpoint],{
          			locale:'DE',
          			getPolyline:true,
          			getSteps:true
          		});
		}
	},
	'.input' : function(el) {
		el.onfocus = function() {
			Element.hide('path');
			Element.hide('out');
			
		
		}
	
	
	},
	'#out' : function(el) {
		el.style.display='none';
 		
		el.onclick = function() {

     	setTimeout(function(){$('iframe').src='./out/getGPX.php';},400);
   			var params = 'to=' 
   				+ encodeURIComponent($F('to')) 
   				+ '&copy='
   				+ encodeURIComponent(dirn.getCopyrightsHtml()) 
   				+ '&descr='+ encodeURIComponent('Route from: ' + $F('from') + ' to: ' + $F('to'));
			for (var j=0; j<route.getNumSteps(); j++) {
            	var step = route.getStep(j);
                var point = step.getLatLng();
                params += '&n[]='+j+'&&x[]=' +  point.x + '&y[]=' + point.y + '&name[]=' + encodeURIComponent(step.getDescriptionHtml());
         }
       
         new Ajax.Updater('dbg', './genGPX.php', {
		    		parameters:params, 	
					evalScripts:true, 
					asynchronous:true,
					onComplete:function() {
						$('path').className='showtodo';
						$('path').innerHTML='<img src="./img/gpsbabel.jpg" /><br />Jetzt kommen folgende Schritte:<ul><li>abspeichern der Datei</li><li><code>gpsbabel</code> oder <code>mapsource</code> starten</li><li><code>route.gmx</code> auf das Garmin laden.</li></ul>Viel Spa&szlig; bei der Fahrt nach '+ $F('to') + ' !';
						self.location = './getGPX.php';	
					}
				  }		
			   );	
			}
	}
 };


Event.observe(window, 'load', init_app);
Event.observe(window, 'unload', GUnload);


function init_app(event) {
  Behaviour.register(rules);
  Behaviour.apply(rules);
  if (GBrowserIsCompatible()) {
      map = new GMap2($("map"));
      var lat = $('lat').value;
      var lng = $F('lng');
		  var pt = new GPoint(lat,lng);
		//  console.log(lat);
          map.setCenter(new GLatLng(lat,lng),7);
      dirn = new GDirections(map);
      GEvent.addListener(dirn,"error", function() {
        Element.hide('path');
        Element.hide('out');
        map.clearOverlays();
        alert("Das geht nicht.");
      });
		var startpoint = $F("from");
        	 var endpoint   = $F("to");
		/*	 dirn.loadFromWaypoints([startpoint,endpoint],{
          			locale:'DE',
          			getPolyline:true,
          			getSteps:true
          		});
      */
     

      // ========== launch the custom Panel creator a millisecond after the GDirections finishes loading ==========
      // == The delay is required in case we rely on GDirections to perform the initial setCenter ==
      GEvent.addListener(dirn,"load", function() {
      	Effect.BlindDown('path');
      	Effect.Appear('out');
      	
        setTimeout('customPanel(map,"map",dirn,$("path"))', 100);
      });

    }
}
 
 
  // ============ custom direction panel ===============
      function customPanel(map,mapname,dirn,div) {
        var html = "";
      
        // ===== local functions =====

        // === waypoint banner ===
        function waypoint(point, type, address) {
          var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
          html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
          html += '  <tr style="cursor: pointer;" onclick='+target+'>';
         // html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
         // html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
          //html += '    </td>';
          html += '    <td style="vertical-align: middle; width: 100%;">';
          html +=        address;
          html += '    </td>';
          html += '  </tr>';
          html += '</table>';
        }

        // === route distance ===
        function routeDistance(dist) {
//          html += '<div style="text-align: right; padding-bottom: 0.3em;">' + dist + '</div>';
        }      

        // === step detail ===
        function detail(point, num, description, dist) {
          var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
          html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
          html += '  <tr style="cursor: pointer;" onclick='+target+'>';
          html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
          html += '      <a href="javascript:void(0)"> '+num+'. </a>';
          html += '    </td>';
          html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
          html +=        description;
          html += '    </td>';
          html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
          html +=        dist;
          html += '    </td>';
          html += '  </tr>';
          html += '</table>';
        }

        // === Copyright tag ===
        function copyright(text) {
          html += '<div style="font-size: 0.86em;">' + text + "</div>";
        }
        

        // === read through the GRoutes and GSteps ===

        for (var i=0; i<dirn.getNumRoutes(); i++) {
          if (i==0) {
            var type="play";
          } else {
            var type="pause";
          }
          route = dirn.getRoute(i);
          var geocode = route.getStartGeocode();
          var point = route.getStep(0).getLatLng();
          // === Waypoint at the start of each GRoute
          waypoint(point, type, geocode.address);
          routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");

          for (var j=0; j<route.getNumSteps(); j++) {
            var step = route.getStep(j);
            // === detail lines for each step ===
            detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
          }
        }
        
        // === the final destination waypoint ===   
        var geocode = route.getEndGeocode();
        var point = route.getEndLatLng();
        waypoint(point, "stop", geocode.address);
                 
        // === the copyright text ===
        copyright(dirn.getCopyrightsHtml());

        // === drop the whole thing into the target div
        div.innerHTML = html;

      } // ============ end of customPanel function ===========

