Ape.Element.routenplanerFalk = function(){
	var that			= this,
		error 			= null,
		map, processor, router;
	
	this.start = function(mymap){
		
		map = mymap;
		// Starte Kartenanzeige
		
		FalkMapConfiguration.mapCoordinateFormat = FalkMapConfiguration.MAP_COORDINATE_FORMAT_WGS_84;
		
		
//		var layerNames = [];
//		for(var i=0; i<FalkMapConfiguration.availableMapLayer.length; ++i){
//			var layerName = FalkMapConfiguration.availableMapLayer[i];
//			layerNames.push(layerName.mapLayerName + " (" +layerName.group+ ")"); 
//		} 
//		alert(layerNames.join(","));

	
	
	
		map.subscribe(FalkMap.MSG_MAP_CLICKED, map_clicked);  
		
//		var mapSwitchControl = new FalkMapSwitchControl("switchcontrol");  
//		mapSwitchControl.setPosition (200, 10, 'left');  
//		map.addMapControl(mapSwitchControl);  
		
      
		ROUTE_HTML_STYLE.push(
			{classname : 'stationcol1',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'stationcol2',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'overviewcol1',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'overviewcol2',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'overviewcol3',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'overviewcol4',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'col1',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'col2',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'col3',styles:[{ key: 'fontSize', value: '11px'}]},
			{classname : 'col4',styles:[{ key: 'fontSize', value: '11px'}]}
		);

		if(this.startRoute === 1){
			requestRoute(map);
		}else{
			//Zentriere die Karte auf Deutschland
			resetMap();
		}
		setBindings();
	};
	function map_clicked(){
		map_zoom_in();
	}
	function map_zoom_in(){
		map.zoomIn();
	}
	function map_zoom_out(){
		map.zoomOut();
	}
	function map_move_left(){
		map.moveMap(100, 0);
	}
	function map_move_right(){
		map.moveMap(-100, 0);
	}
	function map_move_top(){
		map.moveMap(0, 100);
	}
	function map_move_bottom(){
		map.moveMap(0, -100);
	}
	function map_print(){
		//window.print();
		
		window.location.href = window.location.href+'&print=true';
	}
	function map_flag_start(){
   		//map.centerMapToGeocode(router._route.routeEntries[0].geocode.asFalkPoint(), 9); 
   		
		alert('hier zum start springen');
	}
	function map_flag_end(){
		alert('hier zum ziel springen');
	}
	function map_weiterleiten(){
		prompt('Kopieren Sie sich diesen Link, um diese Route zu einem späteren Zeitpunkt wieder laden zu können.', window.location.href);
	}
	function map_switch_map(){
		map.changeMapLayer('MSMAP');
		$(this).parent().children('li').removeClass('aktiv');
		$(this).addClass('aktiv');
	}
	function map_switch_hyb(){
		map.changeMapLayer('MSHYBRID');
		$(this).parent().children('li').removeClass('aktiv');
		$(this).addClass('aktiv');
	}
	function map_switch_sat(){
		map.changeMapLayer('MSAIR');
		$(this).parent().children('li').removeClass('aktiv');
		$(this).addClass('aktiv');
	}
	function setMapOverlayColors(){
		$('.yui-overlay .bd .body').css({background: '#F0EFEC'});
		$('.yui-overlay .ft').remove();
		$('.yui-overlay .hd .header .header_tr').remove();
	}
	function setBindings(){
		
		var contentbereich = $('.wide_col .main_col');
		
		/* map controlls */
		$('.zoom_plus', 	contentbereich).unbind('click').bind('click', 	map_zoom_in);
		$('.zoom_minus', 	contentbereich).unbind('click').bind('click', 	map_zoom_out);
		$('.pfeil_links', 	contentbereich).unbind('click').bind('click', 	map_move_left);
		$('.pfeil_rechts', 	contentbereich).unbind('click').bind('click', 	map_move_right);
		$('.pfeil_hoch', 	contentbereich).unbind('click').bind('click', 	map_move_top);
		$('.pfeil_runter', 	contentbereich).unbind('click').bind('click', 	map_move_bottom);
		$('.print_link').unbind('click').bind('click', 	map_print);
		$('.flagge_start', 	contentbereich).unbind('click').bind('click', 	map_flag_start);
		$('.flagge_ziel', 	contentbereich).unbind('click').bind('click', 	map_flag_end);
		$('.weiterleiten', 	contentbereich).unbind('click').bind('click', 	map_weiterleiten);
		
		$('.mapswitch_map', contentbereich).unbind('click').bind('click', 	map_switch_map);
		$('.mapswitch_hyb', contentbereich).unbind('click').bind('click', 	map_switch_hyb);
		$('.mapswitch_sat', contentbereich).unbind('click').bind('click', 	map_switch_sat);
		
		/* Formular */
		$('.button_change_routetype').unbind('click.changeroutetyoe').bind('click.changeroutetyoe', function(){$('#tab__routenplaner_1').click();});
		$('#newRouteSubmit').unbind('click.submit').bind('click.submit', checkRouteParameters);
		$('#routeDescription').unbind('click.colors').bind('click.colors', setMapOverlayColors);
		$('#falkMap').unbind('mousemove').bind('mousemove', setMapOverlayColors);
		setMapOverlayColors();
		
		$('.switchAdresses').unbind('click.switchAdresses').bind('click.switchAdresses', switchAdresses);
		
		$('#route_option_datechanger').unbind('click.show_routenplaner_kalender').bind('click.show_routenplaner_kalender', showDatePicker);
		
	}
	function showDatePicker(){
		$('#routenplaner_kalender').show();
		
		$('#routenplaner_kalender a.close').unbind('click.hide_routenplaner_kalender').bind('click.hide_routenplaner_kalender', function(){
			$('#routenplaner_kalender').hide();
		});
		
		$('.blaettern_weiter').bind('click', function(){
			
			var number = parseInt($(this).attr('id').split('_').pop());
			var kalenderocunt = 0;
			$('.kalender_routenplaner div').each(function(){
				kalenderocunt++
			});
			
			if(number < kalenderocunt-1){
				$('.kalender_routenplaner div').hide();
			
				$('.kalender_routenplaner #kalender_'+(number+1)).show();
			}
		});
		
		$('.blaettern_zuruck').bind('click', function(){
			
			var number = parseInt($(this).attr('id').split('_').pop());
			if(number > 0){
				$('.kalender_routenplaner div').hide();
			
				$('.kalender_routenplaner #kalender_'+(number-1)).show();
			}
		});
		
		$('.kalender_routenplaner div table tbody tr td a').unbind('click').bind('click.setday', function(){
			
			var day = $(this).html();
			var month = $(this).parent().parent().parent().parent().parent().attr('month');
			var year = $(this).parent().parent().parent().parent().parent().attr('year');
						
			if(day.length < 2){
				day = '0'+day;
			}
			if(month.length < 2){
				month = '0'+month;
			}
			$('#route_option_date').html(day+'.'+month+'.'+year);
			$('#route_option_date_input').val(day+'.'+month+'.'+year);
		});
		
	}
	function checkRouteParameters(){
		
		var startcountry 	= $('#route_start_land').val();  
		var startcity 		= $('#route_start_stadt').val();  
		var startzip 		= $('#route_start_plz').val();  
		var startstreet 	= $('#route_start_street').val();  
		
		var destcountry		= $('#route_ziel_land').val(); 
		var destcity 		= $('#route_ziel_stadt').val(); 
		var destzip 		= $('#route_ziel_plz').val(); 
		var deststreet		= $('#route_ziel_street').val(); 
	
		if((startcity != '' || startzip != '') && (destcity != '' || destzip != '')){
			
		}else{
			alert('Bitte geben Sie für die Start- und Zieladresse jeweils mindestens die Stadt oder PLZ ein.')
			return false;
		}
	}
	function requestRoute(map) {  
		processor = new FalkRouteFlowProcessor(map, "routeDescription", new YAHOO.Custom.Route.RouteHTMLRenderer()); //
		router = processor.getFalkRouter();
 
		var startcountry 	= $('#route_start_land').val();  
		var startcity 		= $('#route_start_stadt').val();  
		var startzip 		= $('#route_start_plz').val();  
		var startstreet 	= $('#route_start_street').val();  
		var startAddress 	= new FalkAddress(startcountry, startcity, startzip, startstreet);  
		
		
		var destcountry		= $('#route_ziel_land').val(); 
		var destcity 		= $('#route_ziel_stadt').val(); 
		var destzip 		= $('#route_ziel_plz').val(); 
		var deststreet		= $('#route_ziel_street').val(); 
		var destAddress 	= new FalkAddress(destcountry, destcity, destzip, deststreet);  
		
		//profile ist nötig für spezialangaben
		//var rp = new RouteProfile(map); 
		var rp = new RouteProfile();

		//schnellste oder kürzeste route
		var route_option_routetype = radioWert(document.routeForm.route_option_routetype);
		switch(route_option_routetype){
			case 'schnell':
				rp.setOptimizationType(RouteProfile.OPT_FASTEST); 
			break;
			case 'kurz':
				rp.setOptimizationType(RouteProfile.OPT_SHORTEST); 
			break;
		}
		router.setRouteProfile(rp);
		
		
		//Datum für reise
		var fd = new FPDate();
		
		fd.parseDate($('#route_option_date').html());
		router.setRoutingDate(fd);
		
		//Uhrzeit für Reise
		router.setRoutingTime(new FPTime($('#route_option_uhrzeit_hour').val(), $('#route_option_uhrzeit_min').val()));
 
		
		//zeit als ankunft oder abfahrtszeit benutzen
		var route_option_planung = radioWert(document.routeForm.route_option_planung);
		switch(route_option_planung){
			case 'abfahrt':
				router.setArrivalTimeSet(false);
			break;
			case 'ankunft':
				router.setArrivalTimeSet(true);
			break;
		}
		
		
		processor.subscribe(FalkRouteFlowProcessor.MSG_ROUTING_ERROR, showError);  
		processor.subscribe(FalkRouteFlowProcessor.MSG_GEOCODING_ERROR, showError); 
		//processor.subscribe(FalkRouteFlowProcessor.MSG_ROUTING_SUCCESSFULL, updateRouteInformation); 
		
		clearError(); 
		
		processor.setRouteColor (FalkRouter.ROUTE_COLOR_BLUE);		
		processor.calcRoute ( [startAddress, destAddress]);	
	} 
	function resetMap(){
		geocode = new FalkPoint(9.223379437790086, 48.72223860481109);  
   		map.centerMapToGeocode(geocode, 9); 
	}
	
	function showError(result) { 
        var o = YDom.get("error"); // error ist die ID eines div elementes 
        if ( !is_null(o) && !is_null(result) && !is_null(result.error) ) { 
        	
        	if(result.error.userText === 'Die Adresse konnte nicht geocodiert werden'){
				$('#tab__routenplaner_1').click();
        		if(	result.geocodeRequest.countryCode 	== $('#route_start_land').val() &&
					result.geocodeRequest.city 			== $('#route_start_stadt').val() &&
					result.geocodeRequest.zip 			== $('#route_start_plz').val() &&
					result.geocodeRequest.street 		== $('#route_start_street').val()
				){
					$('#warnung_start').show();
				}
				if(	result.geocodeRequest.countryCode 	== $('#route_ziel_land').val() &&
					result.geocodeRequest.city 			== $('#route_ziel_stadt').val() &&
					result.geocodeRequest.zip 			== $('#route_ziel_plz').val() &&
					result.geocodeRequest.street 		== $('#route_ziel_street').val()
				){
					$('#warnung_ziel').show();
				}
				resetMap();
        	}else{
        		o.innerHTML = result.error.userText; 
        	}
        } 
	} 

	function clearError() { 
        var o = YDom.get("error"); // error ist die ID eines div elementes 
        if ( !is_null(o) ) { 
                o.innerHTML = ""; 
        } 
	} 


	function showError_geocode(result) {  
		if (result && result.error) {  
			error = result.error.userText;  

			if(error === 'Die Adresse konnte nicht geocodiert werden'){
				$('#tab__routenplaner_1').click();
				
				if(	result.geocodeRequest.countryCode 	== $('#route_start_land').val() &&
					result.geocodeRequest.city 			== $('#route_start_stadt').val() &&
					result.geocodeRequest.zip 			== $('#route_start_plz').val() &&
					result.geocodeRequest.street 		== $('#route_start_street').val()
				){
					$('#warnung_start').show();
				}
				if(	result.geocodeRequest.countryCode 	== $('#route_ziel_land').val() &&
					result.geocodeRequest.city 			== $('#route_ziel_stadt').val() &&
					result.geocodeRequest.zip 			== $('#route_ziel_plz').val() &&
					result.geocodeRequest.street 		== $('#route_ziel_street').val()
				){
					$('#warnung_ziel').show();
				}
				resetMap();
			}
		}  
	} 
	function switchAdresses(){
		var startcountry 	= $('#route_start_land').val();  
		var startcity 		= $('#route_start_stadt').val();  
		var startzip 		= $('#route_start_plz').val();  
		var startstreet 	= $('#route_start_street').val();  
		
		$('#route_start_land').val($('#route_ziel_land').val()); 
		$('#route_start_stadt').val($('#route_ziel_stadt').val()); 
		$('#route_start_plz').val($('#route_ziel_plz').val()); 
		$('#route_start_street').val($('#route_ziel_street').val()); 
		
		
		$('#route_ziel_land').val(startcountry);
		$('#route_ziel_stadt').val(startcity);
		$('#route_ziel_plz').val(startzip);
		$('#route_ziel_street').val(startstreet);
	}
};
/*
function updateRouteInformation(){
	
	if($('#routeDescription .overviewcol2').text() !== '' && $('#routeDescription .overviewcol4').text() !== ''){
	
		var dauer = str_replace(' h', ' Std.', $('#routeDescription .overviewcol2').text());
		var entfernung = parseFloat(str_replace(',', '.', $('#routeDescription .overviewcol4').text()));
		var verbrauch = parseFloat(str_replace(',', '.', $('#route_option_verbrauch').val()));
		var benzinpreis = parseFloat(str_replace(',', '.', $('#route_option_benzinpreis').val()));
		var reisekosten = parseFloat(str_replace(',', '.', $('#route_option_kosten').val()));
		
		var ausgabe_benzin = str_replace('.', ',', extround((entfernung*(verbrauch/100))*benzinpreis, 2));
		if(ausgabe_benzin !== 'NaN'){
			$('#kosten_reise').html( ausgabe_benzin+' € (Verbrauch: '+str_replace('.', ',', extround(entfernung*(verbrauch/100), 2))+' Liter )');
		}
	
		$('#strecke strong').html($('#routeDescription .overviewcol4').text()+", "+dauer);
		
		$('#routeDescription .overviewcol4').parent().parent().parent().remove();
	}
}
*/
function str_replace(search, replace, subject) {
	subject = subject+"";
    return subject.split(search).join(replace);
}
function extround(zahl,n_stelle) {
	zahl = (Math.round(zahl * n_stelle) / n_stelle);
    return zahl;
}
function radioWert(rObj) {
	for (var i=0; i<rObj.length; i++) if (rObj[i].checked) return rObj[i].value;
	return false;
}









YAHOO.namespace("Custom.Route");
/**
* RouteHTMLRenderer extends RouteHTMLRenderer an changes 
* the render overview behavior
*/
YAHOO.Custom.Route.RouteHTMLRenderer = function() {
	YAHOO.Custom.Route.RouteHTMLRenderer.superclass.constructor.call(this);
	this.__name = "ExampleRouteHTMLRenderer";
};
YAHOO.lang.extend(YAHOO.Custom.Route.RouteHTMLRenderer, RouteHTMLRenderer);

/**
* render route overview in my way
* @Overwrite RouteHTMLRenderer._renderOverview
*/
YAHOO.Custom.Route.RouteHTMLRenderer.prototype._renderOverview = function(){
	var template = YAHOO.Custom.Route.RouteHTMLRenderer.HTML_TEMPLATE_OVERVIEW;
	template = template.replace("%VALUE_DURATION%", this.formatDuration(this._route.duration));
	template = template.replace("%VALUE_DISTANCE%", this._route.distance);
	template = template.replace("%VALUE_DEPARTURE%", this._route.departureDate.getDateString());
	template = template.replace("%VALUE_DEPARTURE_TIME%", this._route.departureTime.getFormatedTime());
	template = template.replace("%VALUE_ARRIVAL%", this._route.arrivalDate.getDateString());
	template = template.replace("%VALUE_ARRIVAL_TIME%", this._route.arrivalTime.getFormatedTime());
	
	template = template.replace("%VALUE_TRAVEL_COSTS%", this.calcTravelCosts(this._route.distance));
	
	
	
	var route_option_routetype = radioWert(document.routeForm.route_option_routetype);
	switch(route_option_routetype){
		case 'schnell':
			template = template.replace("%VALUE_ROUTE_OPT%", 'schnellste');
		break;
		case 'kurz':
			template = template.replace("%VALUE_ROUTE_OPT%", 'kürzeste');
		break;
	}
	
	// BEGONE parses the template and replaces HTML content of #routeOverview
	BEGONE.parse( template, YDom.get("routeOverview"), false);
	
	$('.button_change_routetype').unbind('click.changeroutetyoe').bind('click.changeroutetyoe', function(){$('#tab__routenplaner_1').click();});
};

/**
* Template used by YAHOO.Custom.Route.RouteHTMLRenderer._renderOverview
*/
YAHOO.Custom.Route.RouteHTMLRenderer.HTML_TEMPLATE_OVERVIEW = "" +
	"<dt><strong>Strecke:</strong></dt><dd class='trenner'><strong>%VALUE_DISTANCE%</strong></dd> " +
	"<dt class='trenner'><strong>Fahrzeit:</strong></dt><dd class='trenner' ><strong>%VALUE_DURATION%</strong></dd> " +
	
	"<dt>Abfahrt:</dt><dd>%VALUE_DEPARTURE% %VALUE_DEPARTURE_TIME%</dd>"+
	"<dt class='trenner'>Ankunft:</dt><dd class='trenner'>%VALUE_ARRIVAL% %VALUE_ARRIVAL_TIME%</dd>"+
	
	"<dt class='trenner'>Reisekosten:</dt><dd class='trenner'>%VALUE_TRAVEL_COSTS%</dd>"+
	
	"<dt>Routenart:</dt>"+
	"<dd><strong>%VALUE_ROUTE_OPT% <a href='javascript:;' class='button_change_routetype'>Routenart ändern</a></strong></dd>";
	

/**
* add method to calculate travel costs
*/
YAHOO.Custom.Route.RouteHTMLRenderer.prototype.calcTravelCosts = function(distance){
	// your calculation stuff here
	var entfernung = parseFloat(str_replace(',', '.', str_replace(' km', '', distance)));
	var verbrauch = parseFloat(str_replace(',', '.', $('#route_option_verbrauch').val()));
	var benzinpreis = parseFloat(str_replace(',', '.', $('#route_option_benzinpreis').val()));
			
	var ausgabe_benzin = str_replace('.', ',', extround((entfernung*(verbrauch/100))*benzinpreis, 2));
	var travelCosts = '-';
	if(ausgabe_benzin !== 'NaN'){
		travelCosts = ausgabe_benzin+' € (Verbrauch: '+str_replace('.', ',', extround(entfernung*(verbrauch/100), 2))+' Liter )';
	}
	return travelCosts;
}

/**
* add formating of route duration in my way 
*/
YAHOO.Custom.Route.RouteHTMLRenderer.prototype.formatDuration = function(duration){
	if(is_null(duration)){
		return duration;
	}
	try{
		var d = duration.split(":");
		d[0] = parseInt(d[0], 10);
		d[1] = parseInt(d[1], 10);
		if(!is_number(d[0]) || !is_number(d[1]) ){
			return duration;
		}
		var duration = ((d[0] === 0) ? "" : d[0] + " Std. " ) + d[1] + " Min."; 
		return duration;
	} catch(e){}
	return duration;
};

/**
* add time formating to FPTime
*/
FPTime.prototype.getFormatedTime = function() {
	return this.getHourString() + ":" + this.getMinuteString() + " Uhr";
}; 

