/*=======================================================================
 *
 * 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" ]
];

let autocomplete_handlers = [];
let autocomplete_full_address = [];
let autocomplete_ajaxParms = [];
let autocomplete_ajaxParms_all;
let autocomplete_accuracy = [];
let autocomplete_hq_id = 0;
let max_autocomplete = 10;
let cnt_add_stations = 0;

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;
  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;
}

// 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();
  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
    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.short_name;
        break;
      }
    }
  }

//console.log(route + " " + street_number + ", " + 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;
//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);
    if (i == 1)
      autocomplete_hq_id = retValue;
  } else {
    document.getElementById('autocomplete' + i).className = "form-control alert alert-danger";
  }
//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;
//    }

//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]);
  if (trim(document.getElementById("autocomplete" + i).value) == "") {
    autocomplete_full_address[i] = "";
    autocomplete_ajaxParms[i] = "";
    autocomplete_accuracy[i] = 0;
    if (i == 1)
      autocomplete_hq_id = 0;
  } else {
    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)));
      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[2] + " " + retValue[3];
        autocomplete_ajaxParms[i] = myEncodeURI(retValue[4]) + ";" + myEncodeURI(retValue[5]) + ";" + myEncodeURI(retValue[2]) + ";" + myEncodeURI(retValue[3]) + ";" + myEncodeURI(retValue[1]);
        if (i == 1)
          autocomplete_hq_id = 0;
//console.log(document.getElementById('autocomplete' + i).value);
//console.log(autocomplete_full_address[i]);
//console.log(autocomplete_ajaxParms[i]);
//console.log(autocomplete_accuracy[i]);
          document.getElementById('autocomplete' + i).className = "form-control";
	    } else {
          document.getElementById('autocomplete' + i).className = "form-control alert alert-danger";
      }
      autocomplete_accuracy[i] = retValue[0];
    }
  }
  check_sendtour();
}

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

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

function del_station(i) {
//console.log(i);
//console.log(cnt_add_stations);
//console.log(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];
    document.getElementById('autocomplete' + j).className = document.getElementById("autocomplete" + (j + 1)).className;
  }
  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;
  document.getElementById('autocomplete' + j).className = "form-control";
  document.getElementById("input-group" + j).style.display = "none";
  document.getElementById("add_stationsButton" + (j - 1)).style.display = "inline";
  cnt_add_stations--;
}

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;
  ajaxParms = "hq_id=" + autocomplete_hq_id + '&cs_id=0'  + "&vht_id=" + document.getElementById("vht_id").value +
    "&jb_markup=&jb_ordertime=&mode=" + contact_data[autocomplete_hq_id - 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][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] + " " + String.fromCharCode(8364) + "<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(String.fromCharCode(8364))).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(String.fromCharCode(8364))).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(" " + String.fromCharCode(8364), String.fromCharCode(8364)).replaceAll(String.fromCharCode(8364), "&nbsp;"  + String.fromCharCode(8364))
            + (row_price > 0 ? " = " + row_price.toFixed(2).replace(".",",") + " " + String.fromCharCode(8364) : "") + "<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] + " " + String.fromCharCode(8364) + " = " + retValue[0].replace(" [M]", "");
// Auslands-Fahrten abfangen auch PZM
// Preise auf dem Testserver kontrollieren
// Verschieben
      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][2] == "plz") {
        let tsz_base = 0;
        for (let i = 1; i < retValue.length; i++) {
          if (retValue[i][2] > 0)
            price_details += retValue[i][0] + ": " + retValue[i][2].toFixed(2).replace(".",",") + " " + String.fromCharCode(8364) + "<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 " + tsz_base.toFixed(2).replace(".",",") + " " + String.fromCharCode(8364) + " = " + net_price.toFixed(2).replace(".",",") + " " + String.fromCharCode(8364);
      }
    }
    let gross_price = Math.round(net_price * 119) / 100;

    if (net_price > 0) {
      document.getElementById("result_text").innerHTML =
        "<p><span style=\"font-size:11pt\">" +
//        "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(" " + String.fromCharCode(8364), String.fromCharCode(8364)).replaceAll(String.fromCharCode(8364), "&nbsp;"  + String.fromCharCode(8364)).replace(/\+/g, "<br>+") +
        price_details + "</p>" +
        "<p style=\"font-size:16pt;\">Preis inkl. 19 % MwSt.: <b>" + gross_price.toFixed(2).replace(".",",") + " " + String.fromCodePoint(0x404) + "</b></p>" +
        (duration != ""
        ? "<p><span style=\"font-size:11pt\">" + duration + ".</p></span>"
        : "");
    } else {
      document.getElementById("result_text").innerHTML =
        "<p><span style=\"font-size:14pt\">" + "Leider können wir Ihnen für diese Tour online keinen Preis ermitteln.<br>Bitte kontaktieren Sie uns für eine Preisauskunft!" + "</p>";
    }
  } else {
    document.getElementById("result_text").innerHTML = retValue[1];
  }
  document.getElementById("mail_link").innerHTML = 
    "<a href=\"mailto:" + contact_data[autocomplete_hq_id - 1][0] +
    "?subject=Verbindliche%20Bestellung%20eines%20Transportauftrags" +
    "&amp;body=Liebes%20Stadtbote-Team,%20hiermit%20nehme%20ich%20Ihr%20Angebot%20an." +
    "\">" + contact_data[autocomplete_hq_id - 1][0] + "</a></b>";
  document.getElementById("tel_link").innerHTML = 
    "<a href=\"tel:" + contact_data[autocomplete_hq_id - 1][1].replace(/\s/,"") + "\">" + contact_data[autocomplete_hq_id - 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("add_stationsButton" + i).style.display = "none";
    if (i > 1 && i < max_autocomplete)
      document.getElementById("del_stationsButton" + i).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;
};

//      $km_price_paramsArrArr = array();
//      if (!(strpos($km_price_params, "|") === FALSE)) {
//        $km_price_paramsArr = explode("|", $km_price_params);
//        if ($km_price_paramsArr[3] != "zone") {
//          $total_km = explode(" ", $km_price_paramsArr[0])[0];
//          $price_per_km = explode(" ", $km_price_paramsArr[1])[0];
//          $basic_price = explode(" ", trim(str_replace("+", "", $km_price_paramsArr[2])))[0];
//          $km_price_params = str_replace(",", ".", $total_km . "|" . $price_per_km . "|" . $basic_price);
//        } else {
//          $km_price_paramsArr[1] = str_replace("[n]", "(n)", str_replace("(", "", str_replace(")", "", str_replace("(n)", "[n]", $km_price_paramsArr[1]))));
//          $km_price_paramsArrArr = explode("+", $km_price_paramsArr[1]);
//          $di_ids = explode(",", $km_price_paramsArr[4]);
//          $fixprice_min = $km_price_paramsArr[5];
//		}
//      }


//      if ($cs_invmode == 0) {
//        if (!(strpos($costArr[$i][0], "*") === false)) {
//          $tmp_cost = explode("*", $costArr[$i][0]);
//          $pos = strpos($tmp_cost[0], "km");
//          $km = (float) trim(str_replace(",", ".", substr($tmp_cost[0], 0, $pos)));
//          $tmp_cost[1] = str_replace("&nbsp;", "", $tmp_cost[1]);
//          $pos = strpos($tmp_cost[1], chr(128));
//          $eur = (float) trim(str_replace(",", ".", substr($tmp_cost[1], 0, $pos)));
//          $costArr[$i][1] = round($km * $eur, 2);
//        } else {
//          if (!(strpos($costArr[$i][0], "pro") === false)) {
//            $tmp_cost = explode("pro", $costArr[$i][0]);
//            $pos = strpos($tmp_cost[0], chr(128));
//            $eur = (float) trim(str_replace(",", ".", substr($tmp_cost[0], 0, $pos)));
//            $tmp_cost[1] = str_replace("&nbsp;", "", $tmp_cost[1]);
//            $pos = strpos($tmp_cost[1], "weitere");
//            $cnt = (int) trim(str_replace(",", ".", substr($tmp_cost[1], 0, $pos)));
//            $costArr[$i][1] = $cnt * $eur;
//          } else {
//            if ($costArr[$i][0] != "Fixpreis&nbsp;" && substr($costArr[$i][0], 0, strlen("Fixpreis&nbsp;[M]")) != "Fixpreis&nbsp;[M]" && $costArr[$i][0] != "Servicepreis&nbsp;") {
//              $pos = strpos($costArr[$i][0], chr(128));
//              $eur = (float) trim(str_replace(",", ".", substr($costArr[$i][0], 0, $pos)));
//              $costArr[$i][1] = $eur;
//            } else {
//              if (substr($costArr[$i][0], 0, strlen("Fixpreis&nbsp;[M]")) == "Fixpreis&nbsp;[M]") {
//                $costArr[$i][0] = substr($costArr[$i][0], strlen("Fixpreis&nbsp;[M]" . "&nbsp;"));
//                $costArr[$i][1] = $db->getOne("SELECT jb_fixprice FROM job WHERE jb_id = " . $jb_id);
//                $is_minimum = true;
//              }
//            }
//          }
//        }
//        $costArr[$i][0] = str_replace("Bus", "Transporter", str_replace("km", " km", str_replace(chr(128), " EUR", str_replace("&nbsp;" . chr(128), " EUR", str_replace("&nbsp;z", "", $costArr[$i][0])))));
//      }
//      if (!($cs_invmode == 0 && ($costArr[$i][0] == "Fixpreis&nbsp;" || $costArr[$i][0] == "Servicepreis&nbsp;"))) {
//        if (!$is_minimum || substr($costArr[$i][0], 0, strlen("Mindestpreis")) == "Mindestpreis") {
//          $tmp_special_jb_invtext .= trim(str_replace("&nbsp;", " ", $costArr[$i][0])) . ": " .
//          padLeft(str_replace(".", ",", sprintf("%01.2f", trim($costArr[$i][1]))) . " EUR", getParameterValue("0", "INV_MAXCOLS", $hq_id) - strlen(trim(str_replace("&nbsp;", " ", $costArr[$i][0])). ": ")) .
//          "\n";
//        }
//      }
//
