/*=======================================================================
 *
 * price_finder.js
 *
 * Assecutor Data Service GmbH
 *
 =======================================================================*/

//  <scrpt src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></scrpt>
//  <scrpt type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDnbitL06iLp3elmj-WtPudCykX9xvXcVE&libraries=places"></scrpt>
////https://www.webdew.com/blog/google-places-autocomplete-implementation
//    google.maps.event.addDomListener(window, 'load', initialize);
//      function initialize() {
//        var input = document.getElementById('autocomplete_search');
//        var autocomplete = new google.maps.places.Autocomplete(input);
//        autocomplete.addListener('place_changed', function () {
//        var place = autocomplete.getPlace();
//        // place variable will have all the information you are looking for.
//        $('#lat').val(place.geometry['location'].lat());
//        $('#long').val(place.geometry['location'].lng());
//      });
//    }

const contact_data = [
  ["bremen@stadtbote.de",    "0421 38 38 38",  "zone"],
  ["hamburg@stadtbote.de",   "040 54 54 54",   "plz" ],
  ["berlin@stadtbote.de",    "030 30 30 30",   "zone"],
  ["hannover@stadtbote.de",  "0511 93 93 93",  "plz" ],
  ["frankfurt@stadtbote.de", "069 44 44 44",   "plz" ],
  ["dresden@stadtbote.de",   "0351 31 31 31",  "plz" ],
  ["essen@stadtbote.de",     "0201 38 38 30",  "plz" ],
  ["leipzig@stadtbote.de",   "0341 86 86 86",  "plz" ],
  ["","",""],
  ["","",""],
  ["stuttgart@stadtbote.de", "0711 34 16 900", "plz" ]
];
const euroSign = String.fromCharCode(8364);
//const euroSign = String.fromCodePoint(0x404);

const timezoneOffsetInMsecs = -1 * (new Date()).getTimezoneOffset() * 60 * 1000;

let autocomplete_handlers = [];
let autocomplete_full_address = [];
let autocomplete_full_address_all;
let autocomplete_ajaxParms = [];
let autocomplete_ajaxParms_all;
let autocomplete_accuracy = [];
let autocomplete_hq_id = [];
const max_autocomplete = 5;
let cnt_add_stations = 0;
const cnt_add_stations_max = 3;

function initAutocomplete1(i) {
  if (typeof google == 'undefined') {
    if (i < 10)
      self.setTimeout('initAutocomplete1(' + (i+1) + ')', 100);
    return;
  }
  autocomplete_handlers[1] = new google.maps.places.Autocomplete(
    document.getElementById('autocomplete1'),
    {
      types: ['address'],
//      componentRestrictions: {'country': ['DE']},
      fields: ["geometry", "address_components", "types"]
    });

//    autocomplete_handlers[1].setFields('address_components');
  autocomplete_handlers[1].addListener('place_changed', function(){fillInAddress(1);});
  autocomplete_full_address[1] = "";
  autocomplete_ajaxParms[1] = "";
  autocomplete_accuracy[1] = -1;
  autocomplete_hq_id[1] = 0;
  initAutocomplete(max_autocomplete);
}

function initAutocomplete(i) {
  autocomplete_handlers[i] = new google.maps.places.Autocomplete(
    document.getElementById('autocomplete' + i),
    {
      types: ['address'],
//      componentRestrictions: {'country': ['DE']},
      fields: ["geometry", "address_components", "types"]
    });

//    autocomplete.setFields('address_components');
  autocomplete_handlers[i].addListener('place_changed', function(){fillInAddress(i);});
  autocomplete_full_address[i] = "";
  autocomplete_ajaxParms[i] = "";
  autocomplete_accuracy[i] = -1;
  autocomplete_hq_id[i] = 0;
}

// JQuery.Request (GET)
function ajaxRequestGet(url, data) {
  $.ajax({
     type: "GET",
     url: url,
     data: data,
     async: false,
     cache: false,
     success: function(msg){eval(msg);}
  });
}
 
function fillInAddress(i) {
//console.log("fillInAddress(" + i + ")");
  // Get the place details from the autocomplete object.
  let place = autocomplete_handlers[i].getPlace();
//console.log(place);
  if (!place.geometry) {
//console.log("no geometry, end here");
    return;
  }
 
//console.log(place.types);
  let accuracy = 0;
  const sufficient_types = ["intersection", "street_address", "premise", "subpremise"];
  const sufficient_types_accuracy = [7, 8, 9, 9];

  let type_index = -1;
  for (const type of place.types) {
    type_index = sufficient_types.indexOf(type);
    if (type_index > -1) {
      if (accuracy < sufficient_types_accuracy[type_index])
        accuracy = sufficient_types_accuracy[type_index];
    }
  }
  let route = "";
  let street_number = "";
  let country = "";
  let postal_code = ""
  let locality = "";
  let lat = 0;
  let lng = 0;

  if (type_index > -1) {
    lat = place.geometry.location.lat();
    lng = place.geometry.location.lng();
  }

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  // place.address_components are google.maps.GeocoderAddressComponent objects
  // which are documented at http://goo.gle/3l5i5Mr
  for (const component of place.address_components) {
    // @ts-ignore remove once typings fixed
    for (const componentType of component.types) {
//      const componentType = component.types[0];
      switch (componentType) {
        case "route": {
          route = component.short_name;
          break;
        }
        case "street_number": {
          street_number = component.short_name;
          break;
        }
        case "country": {
          country = component.short_name;
          break;
        }
        case "postal_code": {
          postal_code = component.short_name;
          break;
        }
        case "locality": {
          locality = component.long_name;
          break;
        }
      }
    }
  }

//console.log(route + " " + street_number + ", " + country + ", " + postal_code + " " + locality);
 
  // After filling the form with address components from the Autocomplete
  // prediction, set cursor focus on the second address line to encourage
  // entry of subpremise information such as apartment, unit, or floor number.
  let full_address = route + " " + street_number + ", " + (country != "DE" ? country + "-" : "") + postal_code + " " + locality;
  let ajaxParms = myEncodeURI(route) + ";" + myEncodeURI(street_number) + ";" + myEncodeURI(postal_code) + ";" + myEncodeURI(locality) + ";" + myEncodeURI(country);
  document.getElementById('autocomplete' + i).value = full_address;
  autocomplete_full_address[i] = full_address;
  autocomplete_ajaxParms[i] = ajaxParms;
  autocomplete_accuracy[i] = accuracy;
  autocomplete_hq_id[i] = 0;
//console.log("fillInAddress: " + full_address + ", " + accuracy);
  if (accuracy > 6) {
    document.getElementById('autocomplete' + i).className = "form-control";
    ajaxRequestGet('../include/ajaxReqKmPrice.php', "mode=coords&a=" + route + ";" + street_number + ";" + postal_code + ";" + locality + ";" + country + ";" + lat + ";" + lng + ";" + accuracy);
//console.log("fillInAddress: " + retValue);
    autocomplete_hq_id[i] = retValue;
  } else {
//    document.getElementById('autocomplete' + i).className = "form-control alert alert-danger";
    document.getElementById('autocomplete' + i).style.background_color = "#f8d7da";
//console.log(document.getElementById('autocomplete' + i).style.background_color);
  }
//console.log("fillInAddress: " + "before check_sendtour");
  check_sendtour();
}
self.setTimeout('initAutocomplete1(0)', 100);

function check_input(i, doit) {
//    if (typeof doit == "undefined") {
//      self.setTimeout('check_input(' + i + ', true)', 100);
//      return;
//    }
  let inputClassName = "form-control";
//console.log("check_input(" +i+")");
//console.log(document.getElementById('autocomplete' + i).value);
//console.log(autocomplete_full_address[i]);
//console.log(autocomplete_ajaxParms[i]);
//console.log(autocomplete_accuracy[i]);
//console.log(autocomplete_hq_id[i]);
  if (trim(document.getElementById("autocomplete" + i).value) == "") {
    autocomplete_full_address[i] = "";
    autocomplete_ajaxParms[i] = "";
    autocomplete_accuracy[i] = 0;
    autocomplete_hq_id[i] = 0;
  } else {
//console.log("check_input: "+ document.getElementById("autocomplete" + i).value + ", " + autocomplete_full_address[i]);
    if (trim(document.getElementById("autocomplete" + i).value) != autocomplete_full_address[i]) {
      ajaxRequestGet('../include/ajaxReqKmPrice.php', "mode=full_address&a=" + myEncodeURI(trim(document.getElementById("autocomplete" + i).value)));
//console.log('../include/ajaxReqKmPrice.php'+"?"+"mode=full_address&a=" + myEncodeURI(trim(document.getElementById("autocomplete" + i).value)));
//console.log("retValue[0] = " + retValue[0]);
//console.log(autocomplete_hq_id[i]);
      if (retValue[0] > 6) {
        document.getElementById("autocomplete" + i).value = retValue[4] + " " + retValue[5] + ", " + retValue[2] + " " + retValue[3];
        autocomplete_full_address[i] = retValue[4] + " " + retValue[5] + ", " + (retValue[1] != "DE" ? retValue[1] + "-" : "") + retValue[2] + " " + retValue[3];
        autocomplete_ajaxParms[i] = myEncodeURI(retValue[4]) + ";" + myEncodeURI(retValue[5]) + ";" + myEncodeURI(retValue[2]) + ";" + myEncodeURI(retValue[3]) + ";" + myEncodeURI(retValue[1]);
        autocomplete_hq_id[i] = retValue[6];
//console.log(document.getElementById('autocomplete' + i).value);
//console.log(autocomplete_full_address[i]);
//console.log(autocomplete_ajaxParms[i]);
//console.log(autocomplete_accuracy[i]);
//console.log(autocomplete_hq_id[i]);
	  } else {
        inputClassName = "form-control-danger";
      }
      autocomplete_full_address[i] = document.getElementById("autocomplete" + i).value;
      autocomplete_accuracy[i] = retValue[0];
    }
  }
  document.getElementById('autocomplete' + i).className = inputClassName;
  check_sendtour();
}

function check_sendtour() {
//console.log("check_sendtour: " + "start");
  errors_found = true;
  let autocomplete_ajaxParms_intermediate = "";
  let autocomplete_full_address_intermediate = "";
//console.log("check_sendtour: " + autocomplete_hq_id[1] + ", " + autocomplete_ajaxParms[1] + ", " + autocomplete_full_address[1] + ", " + autocomplete_accuracy[1]);
  if (autocomplete_hq_id[1] > 0 && autocomplete_accuracy[1] > 6 && autocomplete_accuracy[max_autocomplete] > 6) {
//console.log("check_sendtour: "  + autocomplete_ajaxParms[1] + ", " + autocomplete_full_address[1] + ", " + autocomplete_accuracy[1]);
    errors_found = false;
    for(i = 2; i < max_autocomplete; i++) {
//console.log("check_sendtour: " + i + ", " + autocomplete_ajaxParms[i] + ", " + autocomplete_full_address[i] + ", " + autocomplete_accuracy[i]);
      if (autocomplete_accuracy[i] >= 0 && autocomplete_accuracy[i] <= 6) {
        errors_found = true;
        break;
      } else {
        if (autocomplete_accuracy[i] > -1 && typeof autocomplete_ajaxParms[i] != "undefined") {
          autocomplete_ajaxParms_intermediate += autocomplete_ajaxParms[i] + "|";
          autocomplete_full_address_intermediate += autocomplete_full_address[i] + "\n";
        }
      }
    }
  }
//console.log("check_sendtour:  errors_found = " + errors_found);
  if (!errors_found) {
    autocomplete_ajaxParms_all = autocomplete_ajaxParms[1] + "|" + autocomplete_ajaxParms_intermediate + autocomplete_ajaxParms[max_autocomplete];
    autocomplete_full_address_all = autocomplete_full_address[1] + "\n" + autocomplete_full_address_intermediate + autocomplete_full_address[max_autocomplete] +
      "\nBenötigtes Fahrzeug: " + document.getElementById("vht_id").options[document.getElementById("vht_id").selectedIndex].text;
    document.getElementById("priceButton").style.display = "inline";
  } else {
    autocomplete_ajaxParms_all = "";	
    autocomplete_full_address_all = "";
    document.getElementById("priceButton").style.display = "none";
  }
}

function add_station(i) {
  document.getElementById("input-group" + (1 + ++cnt_add_stations)).style.display = "";
  if (typeof autocomplete_handlers[(1 + cnt_add_stations)] == "undefined")
    initAutocomplete(1 + cnt_add_stations);
  if (cnt_add_stations == cnt_add_stations_max) {
    document.getElementById("add_stationsButton").style.display = "none";
    document.getElementById("filler_end2").style.display = "inline";
  }
}

function del_station(i) {
//console.log("del_station, " + i);
//console.log("del_station, " + cnt_add_stations);
//console.log("del_station, " + 1 + cnt_add_stations);
  for(j = i; j < 1 + cnt_add_stations; j++) {
//console.log(j);
    document.getElementById("autocomplete" + j).value = document.getElementById("autocomplete" + (j + 1)).value;
    autocomplete_full_address[j] = autocomplete_full_address[j + 1];
    autocomplete_ajaxParms[j] = autocomplete_ajaxParms[j + 1];
    autocomplete_accuracy[j] = autocomplete_accuracy[j + 1];
    autocomplete_hq_id[j] = autocomplete_hq_id[j + 1];
    document.getElementById('autocomplete' + j).className = document.getElementById("autocomplete" + (j + 1)).className;
  }
//console.log(i + ", " + cnt_add_stations)
  document.getElementById("autocomplete" + j).value = "";
  autocomplete_full_address[j] = autocomplete_full_address[j] = "";
  autocomplete_ajaxParms[j] = autocomplete_ajaxParms[j] = "";
  autocomplete_accuracy[j] = autocomplete_accuracy[j] = -1;
  autocomplete_hq_id[j] = autocomplete_hq_id[j] = -1;
  document.getElementById('autocomplete' + j).className = "form-control";
  document.getElementById("input-group" + j).style.display = "none";
  document.getElementById("add_stationsButton").style.display = "inline";
  document.getElementById("filler_end2").style.display = "none";
  cnt_add_stations--;
}

function move_station(i, offset) {
  let tmp_value =        document.getElementById("autocomplete" + i).value;
  let tmp_full_address = autocomplete_full_address[i];
  let tmp_ajaxParms =    autocomplete_ajaxParms[i];
  let tmp_accuracy =     autocomplete_accuracy[i];
  let tmp_hq_id =        autocomplete_hq_id[i];
//console.log(tmp_accuracy);
  let tmp_className =    document.getElementById('autocomplete' + i).className;
  
  let j = 0;
//console.log("move_station, " + i + ", " + offset + ", " + "input-group" + (i + 1 * offset));
  while(document.getElementById("input-group" + (i + ++j * offset)).style.display == "none") {
//console.log(j + ", " + "input-group" + (i + j * offset) + ", " + document.getElementById("input-group" + (i + j * offset)).style.display);
  }
//console.log(i + ", "  + i + j * offset);
  document.getElementById("autocomplete" + i).value = document.getElementById("autocomplete" + (i + j * offset)).value;
  autocomplete_full_address[i] = autocomplete_full_address[i + j * offset];
  autocomplete_ajaxParms[i] = autocomplete_ajaxParms[i + j * offset];
  autocomplete_accuracy[i] = autocomplete_accuracy[i + j * offset];
  autocomplete_hq_id[i] = autocomplete_hq_id[i + j * offset];
//console.log(i + j * offset + ", " + autocomplete_accuracy[i + j * offset]);
  document.getElementById('autocomplete' + i).className = document.getElementById("autocomplete" + (i + j * offset)).className;

  document.getElementById("autocomplete" + (i + j * offset)).value = tmp_value;
  autocomplete_full_address[i + j * offset] = tmp_full_address;
  autocomplete_ajaxParms[i + j * offset] = tmp_ajaxParms;
  autocomplete_accuracy[i + j * offset] = tmp_accuracy;
  autocomplete_hq_id[i + j * offset] = tmp_hq_id;
  document.getElementById('autocomplete' + (i + j * offset)).className = tmp_className;
  check_sendtour();
}

function jb_ordertime_date_changed() {
  console.log(document.getElementById("jb_ordertime_date").value);
  console.log(document.getElementById("jb_ordertime_date").valueAsNumber);
  if (!isNaN(document.getElementById("jb_ordertime_time").valueAsNumber) && document.getElementById("jb_ordertime_date").valueAsNumber + document.getElementById("jb_ordertime_time").valueAsNumber - timezoneOffsetInMsecs < Date.now())
    document.getElementById("jb_ordertime_date").value = "";
  if (document.getElementById("jb_ordertime_date").valueAsNumber - timezoneOffsetInMsecs < Date.now() - 24 * 3600 * 1000)
    document.getElementById("jb_ordertime_date").value = "";
}

function jb_ordertime_time_changed() {
  console.log(document.getElementById("jb_ordertime_time").value);
  console.log(document.getElementById("jb_ordertime_time").valueAsNumber);
  if (!isNaN(document.getElementById("jb_ordertime_date").valueAsNumber) && document.getElementById("jb_ordertime_date").valueAsNumber + document.getElementById("jb_ordertime_time").valueAsNumber - timezoneOffsetInMsecs < Date.now())
    document.getElementById("jb_ordertime_time").value = "";
}

function openDistancepriceDoit() {
//    let i = 0;
//    while (checkTourComplete(i))
//    {
//      if (ajaxParms != "")
//        ajaxParms += "|";
//      ajaxParms += getJobList(i, jl_ad_street) + ";" + getJobList(i, jl_tr_hsno) + ";" + getJobList(i, jl_ad_zipcode) + ";" + getJobList(i, jl_ad_city) + ";" + getJobList(i, jl_ad_country);    
//      if (i++ >= maxTour)
//        break;
//    }
//    let cntTour = i;

  document.getElementById("result").style.display = "none";
  document.getElementById("contact").style.display = "none";
  let jb_ordertime = "";
  let jb_ordertime_local = "";
//console.log(document.getElementById("jb_ordertime_date").valueAsNumber);
//console.log(document.getElementById("jb_ordertime_time").valueAsNumber);
  if (!isNaN(document.getElementById("jb_ordertime_date").valueAsNumber) && !isNaN(document.getElementById("jb_ordertime_time").valueAsNumber)) {
    jb_ordertime = document.getElementById("jb_ordertime_date").value + " " + document.getElementById("jb_ordertime_time").value + ":00";
    jb_ordertime_local = " für den " + document.getElementById("jb_ordertime_date").value.substr(8, 2) + "." + document.getElementById("jb_ordertime_date").value.substr(5, 2) + "."
      + document.getElementById("jb_ordertime_date").value.substr(0, 4) + ", " + document.getElementById("jb_ordertime_time").value + " Uhr";
  }
  ajaxParms = "hq_id=" + autocomplete_hq_id[1] + '&cs_id=0'  + "&vht_id=" + document.getElementById("vht_id").value +
    "&jb_markup=&jb_ordertime=" + jb_ordertime + "&mode=" + contact_data[autocomplete_hq_id[1] - 1][2] + "&a=" + autocomplete_ajaxParms_all;
  ajaxRequestGet('../include/ajaxReqKmPrice.php', ajaxParms);
//console.log(ajaxParms);
//for (let i = 0; i < retValue[3].length; i++) {
//console.log(retValue[3].charAt(i));
//console.log(retValue[3].charCodeAt(i));
//}
//console.log(retValue);
  if (retValue[0] != "ERROR") {
    let price_details = "";
    let net_price = 0;
//    let duration = "";
    if (contact_data[autocomplete_hq_id[1] - 1][2] == "zone") {
      const fixprice_min = retValue[10].replace("[M] ", "");
      net_price = parseFloat(retValue[0].replace(/,/,".").substr(0, retValue[0].length - 1).replace("[M] ", ""));
//      let tsz = parseFloat(retValue[4].substr(retValue[4].indexOf("+"), retValue[4].length - retValue[4].indexOf("+") - retValue[4].indexOf("%")).replace(/,/,"."));
//      let tsz_price = Math.round(tsz * parseFloat(retValue[5].replace(/,/,".")) * 100) / 100;
	  
      //if (fixprice_min != "") {
      //  price_details = fixprice_min + " " + retValue[5] + " " + euroSign + "<br>";
      //} else {
      //  let rows = trim(retValue[3].replace("(","").replace(")","")).split("+");
      //  for (row of rows) {
      //    let row_price = 0;
      //    if (row.indexOf("*") > -1) {
      //      multiplicands = trim(row).split("*");
      //      let km = parseFloat(trim(multiplicands[0].substr(0, multiplicands[0].indexOf("km")).replace(/,/,".")));
      //      let eur = parseFloat(trim(multiplicands[1].substr(0, multiplicands[1].indexOf(euroSign)).replace(/,/,".")));
      //      row_price = Math.round(km * eur * 100) / 100;
      //    } else {
      //      if (row.indexOf("pro") > -1) {
      //        multiplicands = trim(row).split("pro");
      //        let eur = parseFloat(trim(multiplicands[0].substr(0, multiplicands[0].indexOf(euroSign)).replace(/,/,".")));
      //        let cnt = parseFloat(trim(multiplicands[1].substr(0, multiplicands[1].indexOf("weitere")).replace(/,/,".")));
      //        row_price = Math.round(eur * cnt * 100) / 100;
      //      }
      //    }
      //    price_details += row.replace("Großer Bus", "Großer Transporter").replace("Bus", "Transporter").replaceAll("km","&nbsp;Km")
      //      .replaceAll(" " + euroSign, euroSign).replaceAll(euroSign, "&nbsp;"  + euroSign)
      //      + (row_price > 0 ? " = " + toEuro(row_price) : "") + "<br>";
      //  }
      //}
      price_details +=
//        retValue[4].replace("Tz.", "Treibstoffzuschlag").replace("%", "&nbsp;%").replace(/=/, "Gesamt: ") + " + 19% MwSt.<br>" +
//        trim(retValue[4].substr(retValue[4].indexOf("+") + 1)).replace("Tz.", "Treibstoffzuschlag").replace("%", "&nbsp;%") + " auf " + retValue[5] + " " + euroSign + " = " + retValue[0].replace(" [M]", "") + " netto";
        " Enthält " + trim(retValue[4].substr(retValue[4].indexOf("+") + 1)).replace("Tz.", "Treibstoffzuschlag").replace("%", "&nbsp;%") + ".";
// TOBEDONE:
// Hinweis auf LKW-Aufträge
// Verschieben anders machen
// Auslands-Fahrten abfangen auch PZM
// Preise auf dem Testserver kontrollieren

      let time_parts = trim(retValue[9]).split(":");
      let hourStr = "Stunde";
      let minStr = "Minute";
      if (time_parts[0] > 1)
        hourStr += "n";
      if (time_parts[1] > 1)
        minStr += "n";
//      duration = "Die Streckenlänge beträgt " + retValue[2] + ", die Fahrt wird (ohne Berücksichtigung der aktuellen Verkehrslage) ca. " + (time_parts[0] != 0 ? time_parts[0] + "&nbsp;" + hourStr + " " : "") + time_parts[1] + "&nbsp;" + minStr + " dauern";
    } else {
      if (contact_data[autocomplete_hq_id[1] - 1][2] == "plz") {
        let tsz_base = 0;
        for (let i = 1; i < retValue.length; i++) {
//          if (retValue[i][2] > 0)
//            price_details += retValue[i][0] + ": " + toEuro(retValue[i][2]) + "<br>";
          net_price += retValue[i][1];
          tsz_base += retValue[i][2];
        }
        if (net_price != tsz_base)
//          price_details += retValue[0].toFixed(2).replace(".",",") + " % Treibstoffzuschlag auf " + toEuro(tsz_base) + " = " + toEuro(net_price) + " netto";
          price_details += " Enthält " + retValue[0].toFixed(2).replace(".",",") + " % Treibstoffzuschlag. ";
      }
    }
    let gross_price = Math.round(net_price * 119) / 100;
    price_details += "<br>Der Gesamtpreis inkl. 19 % MwSt. beträgt " + toEuro(gross_price) + ".<br>";

    if (net_price > 0) {
      document.getElementById("result").innerHTML =
        "<span style=\"font-size:16pt;\">Preis: <b>" + toEuro(net_price) + "</b></span><br>" +
        "<span style=\"font-size:12pt;font-weight:normal;color:black\">Grundpreis ohne Ladezeiten." +
//        "So setzt sich der Preis zusammen:<br>" +
//        retValue[3].replace("(","").replace(")","").replace("Großer Bus", "Transporter XL").replace("Bus", "Transporter").replaceAll("km","&nbsp;Km").replaceAll(" " + euroSign, euroSign).replaceAll(euroSign, "&nbsp;"  + euroSign).replace(/\+/g, "<br>+") +
        price_details + "</span>"
//        + (duration != ""
//        ? "<p><span style=\"font-size:11pt\">" + duration + ".</p></span>"
//        : "")
        ;
      document.getElementById("mail_link").innerHTML = 
        "<a href=\"mailto:" + contact_data[autocomplete_hq_id[1] - 1][0] +
        "?subject=Verbindliche%20Bestellung%20eines%20Transportauftrags" + jb_ordertime_local +
        "&amp;body=" + encodeURIComponent("Liebes Stadtbote-Team,\n\nhiermit nehme ich Ihr Angebot für folgende Tour an:\n\n" + autocomplete_full_address_all +  "\nPreis: " + toEuro(gross_price) + " (inkl. 19% MwSt.)\n\nMit freundlichen Grüßen") +
        "\" class=\"btn btn-primary\" role=\"button\">" + contact_data[autocomplete_hq_id[1] - 1][0] + "</a></b>";
      document.getElementById("contact_header").style.display = "inline";
    } else {
      document.getElementById("result").innerHTML =
        "<span style=\"font-size:14pt\">" + "Leider können wir für diese Tour online keinen Preis ermitteln.<br>Bitte kontaktieren Sie uns für eine Preisauskunft!" + "</span><br><br>";
      document.getElementById("mail_link").innerHTML = 
        "<a href=\"mailto:" + contact_data[autocomplete_hq_id[1] - 1][0] +
        "?subject=Preisanfrage" + jb_ordertime_local +
        "&amp;body=" + encodeURIComponent("Liebes Stadtbote-Team,\n\nbitte nennen Sie uns den Preis für folgende Tour:\n\n" + autocomplete_full_address_all + "\n\nMit freundlichen Grüßen") +
        "\" class=\"btn btn-primary\" role=\"button\">" + contact_data[autocomplete_hq_id[1] - 1][0] + "</a></b>";
      document.getElementById("contact_header").style.display = "none";
    }
  } else {
    document.getElementById("result").innerHTML = retValue[1];
    document.getElementById("mail_link").innerHTML = 
      "<a href=\"mailto:" + contact_data[autocomplete_hq_id[1] - 1][0] +
      "?subject=Fehler in Preisanfrage" +
      "&amp;body=" + encodeURIComponent("Liebes Stadtbote-Team,\nbei folgender Anfrage ist leider ein Fehler aufgetreten:" + autocomplete_full_address_all + "\n\nMit freundlichen Grüßen") +
      "\" class=\"btn btn-primary\" role=\"button\">" + contact_data[autocomplete_hq_id[1] - 1][0] + "</a></b>";
  }
  document.getElementById("tel_link").innerHTML = 
    "<a href=\"tel:" + contact_data[autocomplete_hq_id[1] - 1][1].replace(/\s/,"") + "\" class=\"btn btn-primary\" role=\"button\">" + contact_data[autocomplete_hq_id[1] - 1][1] + "</a></b>";
//  for(i = 1; i <= max_autocomplete; i++) {
//    if (autocomplete_accuracy[i] > -1)
//      document.getElementById("autocomplete" + i).disabled = true;
//    else
//      document.getElementById("input-group" + i).style.display = "none";
//    if (i < max_autocomplete - 1) {
//      document.getElementById("down_station" + i).style.display = "none";
//    }
//    if (i > 1 && i < max_autocomplete) {
//      document.getElementById("del_stationsButton" + i).style.display = "none";
//      document.getElementById("up_station" + i).style.display = "none";
//    }
//  }
//  document.getElementById("filler_start1").style.display = "none";
//  document.getElementById("filler_start2").style.display = "none";
//  document.getElementById("filler_end1").style.display = "none";
//  document.getElementById("filler_end2").style.display = "none";
//  document.getElementById("add_stationsButton").style.display = "none";
//  document.getElementById("down_station" + (max_autocomplete - 1)).style.display = "none";
//  document.getElementById("up_station" + max_autocomplete).style.display = "none";
//  document.getElementById("vht_id").disabled = true;
//  document.getElementById("priceButton").style.display = "none";
  document.getElementById("result").style.display = "inline";
  document.getElementById("contact").style.display = "inline";
  document.getElementById("refreshButton").style.display = "inline";
}

function trim(zeichenkette) {
  if (typeof zeichenkette == "undefined")
    return "";
  return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

function myEncodeURI(aString) {
  let aStringNew = "";
  for (i = 0; i < aString.length; i++) {
    aStringNew = aStringNew + '%' + aString.charCodeAt(i).toString(16);
  }
  return aStringNew;
};

function toEuro(amount) {
  return amount.toFixed(2).replace(".",",") + " " + euroSign;
}
