	var map;
	var gdir;
	var from = "";
	var to = "";
	var geocoder = null;
	var addressMarker;
	var dist = "0";
	var totalmiles = 1000;

	var verbrauch;
	var strecke;
	var kpreis;
	var kraftstoff;
	var mitfahrer;
    var anzahlTage;
    var preisProFahrt;
    var preisProJahr;
    var ersparnisProFahrt;
    var ersparnisProJahr;
    var rueckfahrt;
    var ausProFahrt;
    var ausProJahr;
    var zusatzkosten;
    var oldfuel;
    var showInfobox = false;
    var queryId ="";


    function gmload() {
      if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(50, 10), 3);

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
      }
    }

    function setDirections(fromAddress, toAddress) {
        $("#strecke").addClass("ac_loading");
        gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": + "de" });
    }

	function onGDirectionsLoad(){
	   //The working version
	   $("#strecke").removeClass("ac_loading");
	   document.getElementById("strecke").value = parseInt(gdir.getDistance().meters/1000);
            showInfobox = true;
            calc();
            fahrpreisStatistik();
	}

    function handleErrors(){
     $("#strecke").removeClass("ac_loading");
            showInfobox = false;
            document.getElementById("netterText").innerHTML = setText();

	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
	     alert("keine Adresse\nError code: " + gdir.getStatus().code);
       }
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR){
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
       }
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY){
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
       }
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY){
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
       }
	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST){
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
       }
	   else {
           alert("An unknown error occurred.");
       }
	}

    function initializeVars()
    {
	  	if (document.formCalculator.from.value!="" && document.formCalculator.to.value!="")
    	{
	  		if (document.formCalculator.from.value!=from || document.formCalculator.to.value!=to)
    		{
    			from=document.formCalculator.from.value;
    			to=document.formCalculator.to.value;
                mitfahrer = eval(document.formCalculator.mitfahrer.options[document.formCalculator.mitfahrer.selectedIndex].value);
    			setDirections(from, to);
    		}

            if (eval(document.formCalculator.mitfahrer.options[document.formCalculator.mitfahrer.selectedIndex].value) != mitfahrer){
                mitfahrer = eval(document.formCalculator.mitfahrer.options[document.formCalculator.mitfahrer.selectedIndex].value);
    			setDirections(from, to);
            }
    	}

		if(isNaN(document.formCalculator.strecke.value)) document.formCalculator.strecke.value = 0;
		strecke = eval(Komma(document.formCalculator.strecke.value));
		if(isNaN(document.formCalculator.verbrauch.value)) document.formCalculator.verbrauch.value = 0;
		verbrauch = eval(Komma(document.formCalculator.verbrauch.value));
		if(isNaN(document.formCalculator.kpreis.value)) document.formCalculator.kpreis.value = 0;
		kpreis = eval(Komma(document.formCalculator.kpreis.value));
		if(isNaN(document.formCalculator.zusatzkosten.value) || document.formCalculator.zusatzkosten.value == "") document.formCalculator.zusatzkosten.value = 0;
		zusatzkosten = eval(Komma(document.formCalculator.zusatzkosten.value));
        kraftstoff = parseInt(document.formCalculator.kraftstoff.selectedIndex+1);
		mitfahrer = eval(document.formCalculator.mitfahrer.options[document.formCalculator.mitfahrer.selectedIndex].value);
        anzahlTage = eval(document.formCalculator.anzahlTage.value);

        //anzahlFg = eval(document.formCalculator.anzahlFahrgemeinschaften.value);


        if (document.formCalculator.rueckfahrt.checked){rueckfahrt = 2; }else {rueckfahrt = 1;}
        //if (anzahlFg < 0) anzahlFg = 1;
		if (mitfahrer < 0) mitfahrer=0;
        if (anzahlTage < 0) anzahlTage = 1;
    }

    function calcCO2()
    {
		if (kraftstoff == 4) co2faktor=27;
		else co2faktor=24;


        ausProFahrt = Math.round(verbrauch*co2faktor*strecke*(mitfahrer)/1000*100)/100;
        ausProJahr  = (Math.round(verbrauch*co2faktor*strecke*(mitfahrer)/1000*100)/100)*anzahlTage;
        document.formCalculator.co2.value = ausProFahrt* rueckfahrt;
        document.formCalculator.co2insgesamt.value = ausProJahr* rueckfahrt;
    }

    function calcPrice()
    {

		if (kraftstoff == 1)
		{
			if (document.formCalculator.kpreis.value=="" || oldfuel != kraftstoff) document.formCalculator.kpreis.value=fuelprice[2];

		}
		if (kraftstoff == 2)
		{
			if (document.formCalculator.kpreis.value=="" || oldfuel != kraftstoff) document.formCalculator.kpreis.value=fuelprice[3];

		}
		if (kraftstoff == 3)
		{
			if (document.formCalculator.kpreis.value=="" || oldfuel != kraftstoff) document.formCalculator.kpreis.value=fuelprice[4];

		}
		if (kraftstoff == 4)
		{
			if (document.formCalculator.kpreis.value==""  || oldfuel != kraftstoff) document.formCalculator.kpreis.value=fuelprice[1];

		}
        oldfuel = kraftstoff;
        kpreis = eval(Komma(document.formCalculator.kpreis.value));
        
        preisProFahrt = ((Math.round((((strecke/100)*verbrauch*kpreis)/(mitfahrer+1)+(zusatzkosten /(mitfahrer+1)))*100)/100)*rueckfahrt);
        preisProJahr  = preisProFahrt*anzahlTage;

        ersparnisProFahrt = preisProFahrt * mitfahrer;
        ersparnisProJahr  = ersparnisProFahrt*anzahlTage;

	document.formCalculator.erg.value = preisProFahrt;
        document.formCalculator.erginsgesamt.value = (Math.round(preisProJahr*100)/100);

        document.formCalculator.ers.value = (Math.round((ersparnisProFahrt)*100)/100);
        document.formCalculator.ersinsgesamt.value = (Math.round((ersparnisProJahr)*100)/100);
    }

    function setText(){
        if(!showInfobox){
            document.getElementById("nettBox").setAttribute("style", "display:none");
           return "nbsp;";
        }else{
           //document.getElementById("nettBox").setAttribute("style", "display:block");
           $('#nettBox').toggle();
           var text;

           text = '<div class="second_headline">Ihre pers&ouml;nliche Spar-Bilanz:</div>';
           var pers;
           if(mitfahrer != 1){pers='Personen';}else{pers='Person';}
           text += '<div align="justify" >F&uuml;r Ihre Strecke '
           if(document.formCalculator.from.value!="" && document.formCalculator.to.value!="" && gdir.getStatus().code == G_GEO_SUCCESS){
                   text += 'von <b>' + document.formCalculator.from.value +'</b> nach <b>'+ document.formCalculator.to.value +'</b> ';
               }
           text += 'sparen Sie <b>'+ document.formCalculator.ers.value +'</b> &euro;, wenn Sie <b>'+ eval(document.formCalculator.mitfahrer.options[document.formCalculator.mitfahrer.selectedIndex].value) +'</b> '+ pers +' mitnehmen.</div><br />';
           text += '<div class="second_headline">Dabei tun Sie auch was f&uuml;r die Umwelt:</div>';
           text += '<div algign="justify">Bei Ihrer Fahrt ersparen Sie der Umwelt <b>'+ document.formCalculator.co2.value +'</b> kg sch&auml;dliche CO2-Emissionen. </div><br />';

           var mit;
           if(mitfahrer == 0){
               mit = 1;
           }else{
               mit = mitfahrer;
           }
           // Wenn die Bedingung nicht erf�llt ist werden die Daten(From To Mitfahrer) nicht an die Inserat Seite �bergeben!
           if(gdir.getStatus().code == G_GEO_SUCCESS){
                text += '<div align="center"><input class="mfz_button_orange_130" type="button"  value="Jetzt inserieren!" onclick="self.location.href=\'./entry.php?abort='+from+'&anort='+to+'&anzahl='+mit+'\'" /></div>';
           }else if(strecke > 0){
                text += '<div><input class="mfz_button_orange_130" type="button"  value="Jetzt inserieren!" onclick="self.location.href=\'./entry.php\'" /></div>';
           }
           return text;
       }
    }

    function calcPriceAllgemein(){
        liter = Math.round((((strecke / 100)*verbrauch) * mitfahrer * anzahlFg * anzahlTage * rueckfahrt)*100) / 100;
        // Liter pro Jahr Allgemein
        document.formCalculator.lpja.value = liter;
        // Kosten pro Jahr Allgemein
        document.formCalculator.kpja.value = ersparnisProJahr * (mitfahrer+1) * rueckfahrt * anzahlFg;
        // Pkw pro Jahr Allgemein
        document.formCalculator.ppja.value = mitfahrer * anzahlFg;
        // Co2 pro Jahr Allgemein
        document.formCalculator.co2pja.value = (ausProJahr * (mitfahrer+1) * rueckfahrt * anzahlFg)/1000;
    }

    function Komma(text){
        text=text.replace(/,/g,".");
        return text;
    }

    function calc(){
        initializeVars();
        calcPrice();
    	calcCO2();
       /*calcPriceAllgemein();*/
                   document.getElementById("netterText").innerHTML = setText();
    }

    function updateDirections() {
      if(document.formCalculator.from.value!='' && document.formCalculator.to.value!='') {
        setDirections(document.formCalculator.from.value, document.formCalculator.to.value);
      }
    }

    function fahrpreisStatistik(){
        http_request = false;
            if (window.XMLHttpRequest) { // Mozilla, Safari,...
                http_request = new XMLHttpRequest();
                if (http_request.overrideMimeType) {
                    http_request.overrideMimeType('text/xml');
                    // zu dieser Zeile siehe weiter unten
                }
            } 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('Ende :( Kann keine XMLHTTP-Instanz erzeugen');
                return false;
            }
                var url = "/fahrpreisStatistik.php";
                // Request �ffnen
                http_request.open('post', url, true);
                // Requestheader senden
                http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                // Request senden
                var value = "";
                    value += "id="+queryId;
                    value += "&abort="+document.formCalculator.from.value;
                    value += "&anort="+document.formCalculator.to.value;
                    value += "&distance="+(document.formCalculator.strecke.value);
                    value += "&price="+document.formCalculator.erg.value;
                    value += "&passenger="+eval(document.formCalculator.mitfahrer.options[document.formCalculator.mitfahrer.selectedIndex].value);
                    value += "&fuelkind="+parseInt(document.formCalculator.kraftstoff.selectedIndex+1);
                    value += "&fuelprice="+eval(Komma(document.formCalculator.kpreis.value));
                    value += "&consumption="+eval(Komma(document.formCalculator.verbrauch.value));
                    value += "&dues="+eval(Komma(document.formCalculator.zusatzkosten.value));

                http_request.send(value);
                // Request auswerten
                http_request.onreadystatechange = function(){
                    switch(http_request.readyState) {
                        case 4: if(http_request.status!=200) {
                                    alert("Fehler:   " +http_request.status);
                                }else{
                                   queryId = http_request.responseText;
                                   //document.getElementById("ajaxtest").innerHTML = http_request.responseText;
                                }
                                break;
                        default: return false; break;
                    }
                };
    }

