var map, mapPreselection, places, placesPreselection, placeName, placePreselectionName;
var geocoder;
var searchPlace;
var searchTextField;

var markers = [];
var clientLocationMarkers = [];
var preselectionMarkers = [];
var additionalMarkers = [];

var jsonData = [];
var jsonClientLocationData = [];
var jsonPreselectionData = [];
var jsonAddtionalData = [];

var markerRedCircle = '/catalogPortlet.web/images/red-circle.png';
var markerRedDiamond = '/catalogPortlet.web/images/red-diamond.png';
var markerWhiteCircle = '/catalogPortlet.web/images/marker.png';

var contractStatusArray = [['_rollback','/catalogPortlet.web/img/uturn.gif'],
['_changeToConfirmed','/catalogPortlet.web/img/rubberstamp.png'],
['_negotiation','/catalogPortlet.web/images/scales.gif'],
['_negotiationDual','/catalogPortlet.web/images/scales.gif'],
['_chanceNotInterested','/catalogPortlet.web/images/page_red.gif'],
['_confirmed','/images/catalogPortlet.web/check.gif'],
['_acceptReject','/catalogPortlet.web/img/accept.gif'],
['_firstRejection','/catalogPortlet.web/images/reject.gif'],
['_firstAccepted','/catalogPortlet.web/img/check.gif'],
['_secondRejected','/catalogPortlet.web/images/cross.gif'],
['_undoFirstDecision','/catalogPortlet.web/img/arrow_left.gif'],
['_rejectedWithPopup','/catalogPortlet.web/images/cross.gif'],
['_secondDecisionRejected','/catalogPortlet.web/img/check.gif']];

var contractStatusMap = new Map(this.contractStatusArray);

var contractStatusImg = [['markerGreenS','/catalogPortlet.web/images/markerGreenS.png'],
['markerGreenM','/catalogPortlet.web/images/markerGreenM.png'],
['markerGreenL','/catalogPortlet.web/images/markerGreenL.png'],
['markerRedS','/catalogPortlet.web/images/markerRedS.png'],
['markerRedM','/catalogPortlet.web/images/markerRedM.png'],
['markerRedL','/catalogPortlet.web/images/markerRedL.png'],
['markerWhiteS','/catalogPortlet.web/images/markerWhiteS.png'],
['markerWhiteM','/catalogPortlet.web/images/markerWhiteM.png'],
['markerWhiteL','/catalogPortlet.web/images/markerWhiteL.png'],
['markerYellowS','/catalogPortlet.web/images/markerYellowS.png'],
['markerYellowM','/catalogPortlet.web/images/markerYellowM.png'],
['markerYellowL','/catalogPortlet.web/images/markerYellowL.png']];

var contractStatusImgMap = new Map(this.contractStatusImg);

var preselectionStatusArray = [['_clearPreselectionStatus','/catalogPortlet.web/img/arrow_undo.gif'],
['_preselected','/catalogPortlet.web/img/check.gif'],
['_rejected','/catalogPortlet.web/img/cross.gif'],
['_copiedToSupplierCircle','/catalogPortlet.web/img/page_copy.gif'],
['_deletePreselection','/catalogPortlet.web/images/delete.gif'],
['_checkEmail','/catalogPortlet.web/img/page_copy.gif'],
['_close','/catalogPortlet.web/images/flag_red.gif'],
['_open','/catalogPortlet.web/images/flag_green.gif']];

var preselectionStatusMap = new Map(this.preselectionStatusArray);

var preselectionStatusImg = [['markerGreenS','/catalogPortlet.web/images/markerGreenS.png'],
['markerGreenM','/catalogPortlet.web/images/markerGreenM.png'],
['markerGreenL','/catalogPortlet.web/images/markerGreenL.png'],
['markerRedS','/catalogPortlet.web/images/markerRedS.png'],
['markerRedM','/catalogPortlet.web/images/markerRedM.png'],
['markerRedL','/catalogPortlet.web/images/markerRedL.png'],
['markerWhiteS','/catalogPortlet.web/images/markerWhiteS.png'],
['markerWhiteM','/catalogPortlet.web/images/markerWhiteM.png'],
['markerWhiteL','/catalogPortlet.web/images/markerWhiteL.png'],
['markerBlackS','/catalogPortlet.web/images/markerBlackS.png'],
['markerBlackM','/catalogPortlet.web/images/markerBlackM.png'],
['markerBlackL','/catalogPortlet.web/images/markerBlackL.png'],
['markerYellowS','/catalogPortlet.web/images/markerYellowS.png'],
['markerYellowM','/catalogPortlet.web/images/markerYellowM.png'],
['markerYellowL','/catalogPortlet.web/images/markerYellowL.png']];

var preselectionStatusImgMap = new Map(this.preselectionStatusImg);

//var infowindow;
var infowindows = [];

var contentString  = [];
var autocomplete;
var autocompletePreselection;
var countryRestrict = {
	'country': 'de'
};

var hiddenLatitude = 51.2;
var hiddenLongitude = 10.4;

var hiddenPreselectionLat = 51.2;
var hiddenPreselectionLng = 10.4;

var zoomLevel = 15;
var theZoomLevel = 15;

var MARKER_PATH = 'https://developers.google.com/maps/documentation/javascript/images/marker_green';
var hostnameRegexp = new RegExp('^https?://.+?/');

var styles = {
     default: [
      {
        featureType: 'poi.business',
        elementType : 'labels',
        stylers: [{visibility: 'on'}]
      },
      {
        featureType: 'transit',
        elementType: 'labels.icon',
        stylers: [{visibility: 'on'}]
      }
    ],
    hide: [
          {
            featureType: 'poi.business',
            elementType : 'labels',
            stylers: [{visibility: 'off'}]
          },
          {
            featureType: 'transit',
            elementType: 'labels.icon',
            stylers: [{visibility: 'off'}]
          }
        ]
    };

function displayMap(mapId){
    document.getElementById(mapId).style.display = 'block';
    document.getElementById('style-selector-control').style.display = 'block';
}

function initMap() {
    map = new google.maps.Map(document.getElementById('searchMap'), {
			zoom: theZoomLevel,
			center: new google.maps.LatLng(hiddenLatitude, hiddenLongitude),
			mapTypeControl: true,
			panControl: true,
			zoomControl: true,
			streetViewControl: true,
			mapTypeControlOptions: {
                              		style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                              		mapTypeIds: ['roadmap', 'terrain']}
	});

	addStyleControls(map);

	map.setOptions({styles: styles['default']});

	var infowindow =  new google.maps.InfoWindow();
	infowindows[0] = infowindow;

    if (typeof searchTextField === "undefined" || searchTextField == null) {
        searchTextField = document.getElementById('searchTextField');
    } else {
        document.getElementById('searchTextField').value = searchTextField.value;
        searchTextField = document.getElementById('searchTextField');
    }

	// Create the autocomplete object and associate it with the UI input control.
	// Restrict the search to the default country, and to place type "cities".
	autocomplete = new google.maps.places.Autocomplete(searchTextField);
    autocomplete.setTypes(['geocode','establishment']);
	autocomplete.addListener('place_changed', onPlaceChanged);

	places = new google.maps.places.PlacesService(map);

    // add geoCoder to search for Google coordinates or address string
    geocoder = new google.maps.Geocoder();
    document.getElementById("selectedClientLocation").addEventListener("change", () => {
        onSelectClientLocation(infowindow, map, 'searchMap','FS');
    });

    showClientLocationMarker(map, 'clientLocationData');
}

function extractLatLng(geoCoordinates) {
    let latLng;
    if (typeof geoCoordinates !== "undefined" && geoCoordinates != null) {
        let pipe = geoCoordinates.indexOf('|');
        if (pipe > 0) {
            let latitude = geoCoordinates.substring(0, pipe - 1);
            let longitude = geoCoordinates.substring(pipe + 1, geoCoordinates.length);
            latLng = getGeoCoordinatesLatLng(latitude, longitude);
        }
    }
    return latLng;
}

function extractClientLocationName(selectedClientLocation) {
    let clientLocationName;
    let selectString = selectedClientLocation.options[selectedClientLocation.selectedIndex].innerText;
    let pipe = selectString.indexOf('|');
    if (pipe > 0) {
        clientLocationName = selectString.substring(0, pipe - 1);
    }
    return clientLocationName;
}

function extractSearchString(selectedClientLocation) {
    let searchString;
    let selectString = selectedClientLocation.options[selectedClientLocation.selectedIndex].innerText;
    let pipe = selectString.indexOf('|');
    if (pipe > 0) {
        searchString = selectString.substring(pipe + 1, selectString.length);
    }
    return searchString;
}

function onSelectClientLocation(infowindow, map, mapId, processStep) {
    let selectedClientLocation = document.getElementById('selectedClientLocation');
    let geoCoordinates = selectedClientLocation.options[selectedClientLocation.selectedIndex].value;
    let request;

    // reverse geoCoding: geoCoordinates
    let latLng = extractLatLng(geoCoordinates);
    if (typeof latLng !== "undefined") {
        request = {'location': latLng}
    }

    let clientLocationName = extractClientLocationName(selectedClientLocation);

    // geoCoding: address search
    let searchString = extractSearchString(selectedClientLocation);

    if (typeof latLng == "undefined") {
        request = {'address': searchString};
    }
    jQuery("input[class*=hiddenClientLocation]").val(searchString);

    clearClientLocationMarkers()

    geocoder.geocode(request, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK || status == google.maps.GeocoderStatus.ZERO_RESULTS) {
            if (results && results[0]) {
                let locationPosition = results[0].geometry.location;
                if (locationPosition) {
                    map.setCenter(locationPosition);

                    if (processStep == 'FS') {
                        hiddenLatitude = locationPosition.lat();
                        jQuery("input[class*=hiddenLatitude]").val(hiddenLatitude);

                        hiddenLongitude = locationPosition.lng();
                        jQuery("input[class*=hiddenLongitude]").val(hiddenLongitude);
                    }
                    if (processStep == 'PS') {
                        hiddenPreselectionLat = locationPosition.lat();
                        jQuery("input[class*=hiddenPreselectionLatitude]").val(hiddenPreselectionLat);

                        hiddenPreselectionLng = locationPosition.lng();
                        jQuery("input[class*=hiddenPreselectionLongitude]").val(hiddenPreselectionLng);
                    }
                }
                const redCircle = {
                    url: markerRedCircle,
                    scaledSize: new google.maps.Size(42, 42),
                    labelOrigin: new google.maps.Point(80, 15)
                };
                let marker = new google.maps.Marker({
                    icon: redCircle,
                    map: map,
                    position: locationPosition,
                    label: clientLocationName,
                });
                clientLocationMarkers[0] = marker;
                map.setZoom(zoomLevel);

                infowindow.setContent(generateClientInfo(results[0].formatted_address, clientLocationName));

                marker.addListener('mouseover', () => {
                    infowindow.open(map, marker)
                });

                marker.addListener('mouseout', () => {
                    infowindow.close()
                });

                displayMap(mapId);
            }
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

function showClientLocationMarker(map, clientLocationData) {
    try {
        jsonClientLocationData = JSON.parse(document.getElementById(clientLocationData).textContent);
    } catch (e) {
        return;
    }
    clearClientLocationMarkers()

    for (let i = 0; i <= jsonClientLocationData.length - 1; i++) {
        let location = jsonClientLocationData[i].result.geometry.location;
        let latLng = new google.maps.LatLng(location.lat, location.lng);

        let name = jsonClientLocationData[i].result.name;
        let address = jsonClientLocationData[i].result.address;
        const redDiamond = {
            url: markerWhiteCircle,
            scaledSize: new google.maps.Size(40, 40),
            labelOrigin: new google.maps.Point(75, 15)
        };
        let marker = new google.maps.Marker({
            icon: redDiamond,
            position: latLng,
            map: map,
            label: name
        });
        clientLocationMarkers[i] = marker;
        dropMarker(clientLocationMarkers, map, i);

        let infowindow = new google.maps.InfoWindow();
        infowindow.setContent(generateClientInfo(address, name));

        marker.addListener('mouseover', () => {
            infowindow.open(map, marker)
        });

        marker.addListener('mouseout', () => {
            infowindow.close()
        });
    }
}

function clearClientLocationMarkers() {
    for (let i = 0; i < clientLocationMarkers.length; i++) {
        if (clientLocationMarkers[i]) {
            clientLocationMarkers[i].setMap(null);
        }
    }
    clientLocationMarkers = [];
}

function getGeoCoordinatesLatLng(latitude, longitude) {
    var latitude = latitude;
    var longitude = longitude;
    var latLng = new google.maps.LatLng();
    if (isFloat(latitude)) {
        if (isFloat(longitude)) {
            latLng = new google.maps.LatLng(latitude, longitude);
        }
    }
    return latLng;
}

var isFloat = function (value) {
    if (isNaN(value)) {
        return false;
    } else {
        if (parseFloat(value)) {
            return true;
        } else {
            return false;
        }
    }
}

function generateClientInfo(address, name) {
    let content =
            '<div>' +
            '<h4>' + name + '</h4>' +
            '</br>' +
            address +
            '</div>'
    return content;
}

// When the user selects a city, get the place details for the city and
// zoom the map in on the city.
function onPlaceChanged() {
	var place = autocomplete.getPlace();

	if (place.geometry) {
	    hiddenLatitude = place.geometry.location.lat();
	    jQuery("input[class*=hiddenLatitude]").val(hiddenLatitude);

	    hiddenLongitude = place.geometry.location.lng();
        jQuery("input[class*=hiddenLongitude]").val(hiddenLongitude);
        placeName = place.vicinity;

		map.panTo(place.geometry.location);
		map.setZoom(zoomLevel);
		displayMap('searchMap');
		clearMarkers();
		setMarker(place.geometry.location, name);
	} else {
		document.getElementById('searchTextField').placeholder = 'Enter a city';
	}
	document.getElementById('style-selector-control').display = 'block';

    showClientLocationMarker(map, 'clientLocationData');
}

function setMarker(location, name) {
   mapShow = "show";
   var myLatLng = {lat: location.lat(), lng: location.lng()};

   markers[0] = new google.maps.Marker({
             position: myLatLng,
             map: map,
             title: name
           });
}

function showMapPoints(){
  try {
       jsonData = JSON.parse(document.getElementById('data').textContent);
      } catch(e) {
            return;
     }
    clearMarkers();

   for (var i = 0; i <= jsonData.length - 1; i++) {
           displayMap('searchMap');
           var latLng = new google.maps.LatLng(jsonData[i].result.geometry.location.lat, jsonData[i].result.geometry.location.lng);
           var hotelName = jsonData[i].result.name;

           var labels = "";
           var labelList = jsonData[i].result.labels;
           for (h = 0; h < labelList.length; h++) {
             labels += jsonData[i].result.labels[h];
           }

           var iconPath = findMarkerImg(jsonData[i].result.mappingId, labels);

           var marker = new google.maps.Marker({
          			position: latLng,
          			map: map,
          			title: hotelName,
          			label: labels,
          			icon: iconPath,
          			animation: google.maps.Animation.DROP});
          	markers[i] = marker;
          	dropMarker(markers,map,i);
   }
   addMarkerListener();
}

function addMarkerListener(){
    for (var j = 0; j <= markers.length - 1; j++) {
		var marker = markers[j];
        infowindows[j] = new google.maps.InfoWindow();
	    google.maps.event.addListener(marker, 'click', (function(marker, j) {
        return function() {
            var infowindow = infowindows[j];
            infowindow.setContent(generateContent(jsonData[j]));
            infowindow.open(map, marker);
        }
    })(marker, j));
   	}
}

function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
      if (markers[i]) {
            markers[i].setMap(null);
      }
    }
    markers = [];
}

function dropMarker(markers, map, i) {
    return function() {
          markers[i].setMap(map);
    };
}

function changeZoom(){
    var distance = document.getElementById("selectedTheDistance");
    var distanceSelection = distance.options[distance.selectedIndex].value;

     var hiddenDistance = jQuery("input[class*=distance]");
     hiddenDistance[0].value = distanceSelection;

    var distanceInt = parseInt(distanceSelection);
    var myZoomLevel = 1
      if (distanceInt == 1 || distanceInt == 2) {
               myZoomLevel = 14;
      } else if (distanceInt == 5) {
               myZoomLevel = 13;
      } else if (distanceInt == 10) {
               myZoomLevel = 12;
      } else {
          myZoomLevel = 10;
    }
    map.setZoom(myZoomLevel);
    theZoomLevel = myZoomLevel;

    clearMarkers();
}

function findContractByMappingId(mappingId){
    var buttons = jQuery('input[class*='+mappingId+']');
    var buttonsHtml = "";

    for (var b = 0; b < buttons.length; b ++){
        var button = buttons[b];
        var buttonSrc = button.src;
        var buttonClassName = button.className;
        var buttonClass = buttonClassName.slice(buttonClassName.lastIndexOf("_") ,buttonClassName.length);
        var imageUrl = contractStatusMap.get(buttonClass);
        var buttonPic = buttonSrc.slice(buttonSrc.lastIndexOf("/"), buttonSrc.length);
        buttonsHtml = buttonsHtml + '<input type="image" src='+imageUrl+' onclick="clickAction('+'\''+button.className+'\''+');" />';
    }
    return buttonsHtml;

}

function findContractStatus(mappingId){
    var contractSpans = jQuery('span[class*='+mappingId+'_contractStatus]');

    for (var c = 0; c < contractSpans.length; c ++){
        var contractStatus = contractSpans[c];
        return contractStatus.innerHTML;
    }
    return "";
}

function findRealStatus(mappingId){
    var contractSpans = jQuery('span[class*='+mappingId+'_realStatus]');

    for (var c = 0; c < contractSpans.length; c ++){
        var contractStatus = contractSpans[c];
        return contractStatus.innerHTML;
    }
    return "";
}

function clickAction(buttonClass){
   var buttons = jQuery('input[class="'+buttonClass+'"]');
   for(i = 0; i < buttons.length; i++){
     buttons[i].click(function(){
        jQuery( this ).click();
     });
   }
}

function generateContent(data){
       var contentOben = '<table><tr>'+
                         '<td colspan="2"><b>'+ data.result.name +'</b></td>'+
                         '<td>'+ data.result.star +'</td>'+
                         '<td valign="right"><b>'+ data.result.serviceProviderId+'</b></td>'+
                      '</tr>'+
                      '<tr style="width: 100%; border-bottom: 1px solid black; width: 2px;">'+
                         '<td colspan="4"/>'+
                      '</tr>';

       var buttonsHtml =  findContractByMappingId(data.result.mappingId);

       var contractStatus = findContractStatus(data.result.mappingId);

        var infoLabelTabelle =  "";

       var infoLabels = data.result.infoLabels;
       for (var key in infoLabels) {
            	var infoLabel = '<tr>'+
            	'<td>'+key+'</td>'+
            	'<td>'+infoLabels[key]+'</td>'+
             	'</tr>';
             infoLabelTabelle = infoLabelTabelle + infoLabel;
        }

        var mappingId = data.result.mappingId;

        var contentUnten = '<tr style="width: 100%; border-top: 1px solid black">'+
                          '<td colspan="3"><b>'+ contractStatus +'</b></td>'+
                           '<td valign="right">'+ buttonsHtml + '</td>'+
                         '</tr>'+
                      '</table>';

       var content =  contentOben + infoLabelTabelle + contentUnten

        return content;
}

function refreshMapPoints(){

    try {
        jsonData = JSON.parse(document.getElementById('data').textContent);
    } catch(e){
        return;
    }

   for (var i = 0; i <= jsonData.length - 1; i++) {

           var labelList = jsonData[i].result.labels;
           var labels = "";
              for (h = 0; h < labelList.length; h++) {
                labels += jsonData[i].result.labels[h];
              }

           var iconUrl = findMarkerImg(jsonData[i].result.mappingId, labels);
           var marker = markers[i];

           marker.setIcon(iconUrl);
           var infowindow = infowindows[i];
           infowindow.setContent(generateContent(jsonData[i]));
   }
}

function findMarkerImg(mappingId, labels){

var     not_interested = 'NOT_INTERESTED';  //0
var	    open = 'OPEN';					// 1
var   	in_process = 'IN_PROCESS';			// 2
var   	released = 'RELEASED';				// 3
var   	accepted = 'ACCEPTED'; 				// 4
var   	rejected = 'REJECTED';				// 5
var   	negotiation = 'NEGOTIATION';			// 6
var  	in_negotiation = 'IN_NEGOTIATION'; 		// 7
var  	released_negotiation = 'RELEASED_NEGOTIATION';	// 8
var  	rejected_negotiation = 'REJECTED_NEGOTIATION';	// 9
var 	imported_with_errors = 'IMPORTED_WITH_ERRORS';	// 10
var 	first_accepted = 'FIRST_ACCEPTED';			// 11
var   	second_accepted = 'SECOND_ACCEPTED';		// 12
var   	first_rejected = 'FIRST_REJECTED';			// 13
var   	second_rejected = 'SECOND_REJECTED';		// 14
var   	no_agreement = 'NO_AGREEMENT';			// 15
var   	counter_offer = 'COUNTER_OFFER';			// 16

var contractStatus = findRealStatus(mappingId);
var small_button = 5;
var mid_button = 14;

var labelsize = labels.length;

    if (contractStatus == open
                    || contractStatus == in_process
                    || contractStatus == imported_with_errors
                    || contractStatus == not_interested) {
                if (labelsize < small_button) {
                    return contractStatusImgMap.get('markerWhiteS');
                } else if (labelsize < mid_button) {
                    return contractStatusImgMap.get('markerWhiteM');
                } else {
                    return contractStatusImgMap.get('markerWhiteL');
                }
    } else if (contractStatus == accepted || contractStatus == rejected) {

                if (labelsize < small_button) {
                    return contractStatusImgMap.get('markerGreenS');
                } else if (labelsize < mid_button) {
                    return contractStatusImgMap.get('markerGreenM');
                } else {
                    return contractStatusImgMap.get('markerGreenL');
                }
    } else if (contractStatus == released_negotiation
                    || contractStatus == released
                    || contractStatus == rejected_negotiation
                    || contractStatus == counter_offer) {
                if (labelsize < small_button) {
                    return contractStatusImgMap.get('markerRedS');
                } else if (labelsize < mid_button) {
                    return contractStatusImgMap.get('markerRedM');
                } else {
                    return contractStatusImgMap.get('markerRedL');
                }

    } else if (contractStatus == in_negotiation || contractStatus == negotiation) {
                if (labelsize < small_button) {
                    return contractStatusImgMap.get('markerYellowS');
                } else if (labelsize < mid_button) {
                    return contractStatusImgMap.get('markerYellowM');
                } else {
                    return contractStatusImgMap.get('markerYellowL');
                }
    }
    return contractStatusImgMap.get('markerGreenL');
}

function refreshPreselectionMapPoints(){

    try {
        jsonPreselectionData = JSON.parse(document.getElementById('jsonPreselectionData').textContent);
    } catch(e){
        return;
    }

   clearPreselectionMarkers();

   preselectionMarkers = generateMarker(jsonPreselectionData);

   addPreselectionMarkerListener();
}

function refreshAdditionalMapPoints(){
 try {
     try {
         var myJsonAddtionalData = JSON.parse(document.getElementById('jsonAdditionData').textContent);
     } catch (e) {
         return;
     }

        for (var i = 0; i <= myJsonAddtionalData.length - 1; i++) {
               var label = "";
               label = myJsonAddtionalData[i].result.name;

               var iconUrl = findAdditonMarkerImg(label);
               var marker = additionalMarkers[i];
               if (typeof(iconUrl) !== "undefined" && iconUrl && typeof(marker) !== "undefined" && marker){
                    marker.setIcon(iconUrl);
               }

               var additionalwindow = new google.maps.InfoWindow();

               additionalwindow.setContent(generateAdditionalContent(myJsonAddtionalData[i]));
               additionalwindow.close();
           }

          jsonAddtionalData =  myJsonAddtionalData;

    } catch(e){
        console.log("refreshAdditionalMapPoints fails: " + e);
    }
}

function removeAdditionalMarker(serviceProviderId){
    for (var i = 0; i <= additionalMarkers.length - 1; i++) {
        var marker = additionalMarkers[i];

        var titel = marker.getTitle();
        if (titel == serviceProviderId){
          marker.setMap(null);
          return;
        }
    }
}

function findPreselectionMarkerImg(mappingId, labels){

var     presented = 'PRESENTED';  //0
var	    selected = 'SELECTED';	 // 1
var   	rejected = 'REJECTED';	// 2
var   	copied_to_supplier_circle = 'COPIED_TO_SUPPLIER_CIRCLE'; // 3

var contractStatus = findPreselectionStatus(mappingId);
var small_button = 5;
var mid_button = 14;

var labelsize = labels.length;

    if (contractStatus == copied_to_supplier_circle) {
                if (labelsize < small_button) {
                    return preselectionStatusImgMap.get('markerBlackS');
                } else if (labelsize < mid_button) {
                    return preselectionStatusImgMap.get('markerBlackM');
                } else {
                    return preselectionStatusImgMap.get('markerBlackL');
                }
    } else if (contractStatus == selected) {

                if (labelsize < small_button) {
                    return preselectionStatusImgMap.get('markerGreenS');
                } else if (labelsize < mid_button) {
                    return preselectionStatusImgMap.get('markerGreenM');
                } else {
                    return preselectionStatusImgMap.get('markerGreenL');
                }
    } else if (contractStatus == rejected) {
                if (labelsize < small_button) {
                    return preselectionStatusImgMap.get('markerRedS');
                } else if (labelsize < mid_button) {
                    return preselectionStatusImgMap.get('markerRedM');
                } else {
                    return preselectionStatusImgMap.get('markerRedL');
                }

    } else if (contractStatus == presented) {
                if (labelsize < small_button) {
                    return preselectionStatusImgMap.get('markerYellowS');
                } else if (labelsize < mid_button) {
                    return preselectionStatusImgMap.get('markerYellowM');
                } else {
                    return preselectionStatusImgMap.get('markerYellowL');
                }
    }
    return preselectionStatusImgMap.get('markerGreenL');
}

function findAdditonMarkerImg(label){
    var small_button = 5;
    var mid_button = 14;
    try {
        var labelsize = label.length;

        if (labelsize < small_button) {
                return preselectionStatusImgMap.get('markerWhiteS');
        } else if (labelsize < mid_button) {
               return preselectionStatusImgMap.get('markerWhiteM');
        }
    } catch(e) {
        return preselectionStatusImgMap.get('markerWhiteL');
    }

    return preselectionStatusImgMap.get('markerWhiteL');
}

function findPreselectionStatus(mappingId){
    var preselectionSpans = jQuery('span[class*='+mappingId+'_preselectionStatus]');

    for (var c = 0; c < preselectionSpans.length; c ++){
        var preselectionStatus = preselectionSpans[c];
        var preselectionStatusText = preselectionStatus.innerHTML;
        return preselectionStatusText.toUpperCase();
    }
    return "";
}

function displayPreselecionMap(){
    document.getElementById('searchPreselectionMap').style.display = 'block';
    document.getElementById('style-selector-control').style.display = 'block';
}

function initPreselectionMap() {
    hideButtons();
	mapPreselection = new google.maps.Map(document.getElementById('searchPreselectionMap'), {
			zoom: zoomLevel,
			center: new google.maps.LatLng(hiddenPreselectionLat, hiddenPreselectionLng),
			mapTypeControl: true,
			panControl: true,
			zoomControl: true,
			streetViewControl: true,
			mapTypeControlOptions: {
                  		style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                  		mapTypeIds: ['roadmap', 'terrain']}
	});

    addStyleControls(mapPreselection);

	var infowindow =  new google.maps.InfoWindow();
	infowindows[0] = infowindow;

	// Create the autocomplete object and associate it with the UI input control.
	// Restrict the search to the default country, and to place type "cities".
    if (typeof searchPlace === "undefined" || searchPlace == null ){
	    searchPlace  = document.getElementById('searchPlace');
	} else {
	    document.getElementById('searchPlace').value = searchPlace.value;
	    searchPlace  = document.getElementById('searchPlace');
	}
	mapPreselection.setOptions({styles: styles['default']});

    autocompletePreselection = new google.maps.places.Autocomplete(searchPlace);
    autocompletePreselection.setTypes(['geocode','establishment']);

    autocompletePreselection.addListener('place_changed', onPlacePreselectionChanged);

    placesPreselection = new google.maps.places.PlacesService(mapPreselection);

    // add geoCoder to search for Google coordinates or address string
    geocoder = new google.maps.Geocoder();
    document.getElementById("selectedClientLocation").addEventListener("change", () => {
        onSelectClientLocation(infowindow, mapPreselection, 'searchPreselectionMap','PS');
    });

    showClientLocationMarker(mapPreselection,'clientLocationPreselectionData');
}

// When the user selects a city, get the place details for the city and
// zoom the map in on the city.
function onPlacePreselectionChanged() {
	placesPreselection = autocompletePreselection.getPlace();
	// searchPlace = placesPreselection.formatted_address;

	if (placesPreselection.geometry) {
	    zoomLevel = 15;
	    hiddenPreselectionLat = placesPreselection.geometry.location.lat();
	    jQuery("input[class*=hiddenPreselectionLatitude]").val(hiddenPreselectionLat);

	    hiddenPreselectionLng = placesPreselection.geometry.location.lng();
        jQuery("input[class*=hiddenPreselectionLongitude]").val(hiddenPreselectionLng);
        placePreselectionName = placesPreselection.vicinity;

		mapPreselection.panTo(placesPreselection.geometry.location);

		displayPreselecionMap();
		clearPreselectionMarkers();
		clearAdditionalMarkers();
		setPreselectionMarker(placesPreselection.geometry.location, placePreselectionName);

	} else {
		document.getElementById('searchPlace').placeholder = 'Enter a city';
	}
	hideButtons();
	document.getElementById('style-selector-control').display = 'block';

    showClientLocationMarker(mapPreselection,'clientLocationPreselectionData');
}

function clearPreselectionMarkers() {
    for (var i = 0; i < preselectionMarkers.length; i++) {
      if (preselectionMarkers[i]) {
            preselectionMarkers[i].setMap(null);
      }
    }
    preselectionMarkers = [];
}

function setPreselectionMarker(location, name) {
   var myLatLng = {lat: location.lat(), lng: location.lng()};

   preselectionMarkers[0] = new google.maps.Marker({
             position: myLatLng,
             map: mapPreselection,
             title: name
           });
}

function dropPreselectionMarker(marker) {
    return function() {
          marker.setMap(mapPreselection);
    };
}

function dropAdditionalMarker(i) {
    return function() {
          additionalMarkers[i].setMap(preselectionStatusMap);
    };
}

function addPreselectionMarkerListener(){
    for (var j = 0; j <= preselectionMarkers.length - 1; j++) {
		var marker = preselectionMarkers[j];
        infowindows[j] = new google.maps.InfoWindow();
	    google.maps.event.addListener(marker, 'click', (function(marker, j) {
        return function() {
            var infowindow = infowindows[j];
            infowindow.setContent(generatePreselectionContent(jsonPreselectionData[j]));
            infowindow.open(mapPreselection, marker);
        }
        })(marker, j));
   	}
}

function addAdditonalMarkerListener(){

    for (var j = 0; j <= additionalMarkers.length - 1; j++) {
		var marker = additionalMarkers[j];
	    google.maps.event.addListener(marker, 'click', (function(marker, j) {
        return function() {
            var additionalwindow = new google.maps.InfoWindow();

            additionalwindow.setContent(generateAdditionalContent(jsonAddtionalData[j]));
            additionalwindow.open(mapPreselection, marker);
        }
        })(marker, j));
   	}
}

function clickActionLink(buttonClass){
   var buttons = jQuery('input[class="'+buttonClass+'"]');
   for(i = 0; i < buttons.length; i++){
     buttons[i].click(function(){
        jQuery( this ).click();
     });
   }
}

function findPreselectionByMappingId(mappingId){
    var buttons = jQuery('input[class*='+mappingId+']');
    var buttonsHtml = "";

    for (var b = 0; b < buttons.length; b ++){
        var button = buttons[b];
        var buttonSrc = button.src;
        var buttonClassName = button.className;
        var buttonClass = buttonClassName.slice(buttonClassName.lastIndexOf("_") ,buttonClassName.length);
        var imageUrl = preselectionStatusMap.get(buttonClass);
        var buttonPic = buttonSrc.slice(buttonSrc.lastIndexOf("/"), buttonSrc.length);
        buttonsHtml = buttonsHtml + '<input type="image" onclick="clickActionLink('+'\''+button.className+'\''+');" src='+imageUrl+'></input>';
    }
    return buttonsHtml;
}

function generateAdditionalContent(data){
 var content = '<table><tr>'+
                         '<td colspan="2"><b>'+ data.result.name +'</b></td>'+
                         '<td>'+ data.result.star +'</td>'+
                         '<td valign="right"><b>'+ data.result.serviceProviderId+'</b></td>'+
                      '</tr>'+
                      '<tr style="width: 100%; border-bottom: 1px solid black; width: 2px;">'+
                         '<td colspan="4"/>'+
                      '</tr>'+
                      '<tr>'+
                          '<td>Street</td>'+
                          '<td colspan="2">'+ data.result.street +'</td>'+
                      '</tr>'+
                      '<tr>'+
                           '<td>City</td>'+
                            '<td colspan="2">'+ data.result.city +'</td>'+
                      '</tr>'+
                      '<tr>'+
                            '<td>Country</td>'+
                            '<td colspan="2">'+ data.result.country +'</td>'+
                      '</tr>'+
                      '<tr style="width: 100%; border-bottom: 1px solid black; width: 2px;">'+
                         '<td colspan="4"/>'+
                       '</tr>'+
                      '<tr>'+
                            '<td colspan="2"><input type="submit" class="testIdInviteAsPreselectedBtn" onclick="pushInvitePreselectedButton('+data.result.serviceProviderId+')" value="'+data.result.buttonPreselected+'"></td>'+
                            '<td colspan="2"><input type="submit" class="testIdInviteAsPresentedBtn" onclick="pushPreventedButton('+data.result.serviceProviderId+')" value="'+data.result.buttonPresented+'"></td>'+
                      '</tr></table>';

 return content;
}

function generatePreselectionContent(data){
       var contentOben = '<table><tr>'+
                         '<td colspan="2"><b>'+ data.result.name +'</b></td>'+
                         '<td>'+ data.result.star +'</td>'+
                         '<td valign="right"><b>'+ data.result.serviceProviderId+'</b></td>'+
                      '</tr>'+
                      '<tr style="width: 100%; border-bottom: 1px solid black; width: 2px;">'+
                         '<td colspan="4"/>'+
                      '</tr>';

       var buttonsHtml =  findPreselectionByMappingId(data.result.mappingId);

       var preselectionStatus = findPreselectionStatus(data.result.mappingId);

        var infoLabelTabelle =  "";

       var infoLabels = data.result.infoLabels;
       for (var key in infoLabels) {
            	var infoLabel = '<tr>'+
            	'<td>'+key+'</td>'+
            	'<td>'+infoLabels[key]+'</td>'+
             	'</tr>';
             infoLabelTabelle = infoLabelTabelle + infoLabel;
        }

        var mappingId = data.result.mappingId;

        var contentUnten = '<tr style="width: 100%; border-top: 1px solid black">'+
                          '<td colspan="3"><b>'+ preselectionStatus +'</b></td>'+
                           '<td valign="right">'+ buttonsHtml + '</td>'+
                         '</tr>'+
                      '</table>';

       var content =  contentOben + infoLabelTabelle + contentUnten

        return content;
}

function showPreselectionMapPoints(){
    try {
        jsonPreselectionData = JSON.parse(document.getElementById('jsonPreselectionData').textContent);
    } catch (e) {
        return;
    }

      switchAddtionalMarkers();
      clearPreselectionMarkers();
      clearAdditionalMarkers();

      preselectionMarkers = generateMarker(jsonPreselectionData);

      addPreselectionMarkerListener();
}

function generateMarker(theJsonData){
    var markersArray = [];
    for (var i = 0; i <= theJsonData.length - 1; i++) {
                 displayPreselecionMap();

                 var latitudeLng = new google.maps.LatLng(theJsonData[i].result.geometry.location.lat, theJsonData[i].result.geometry.location.lng);
                 var hotelName = theJsonData[i].result.name;

                 var labels = "";
                 var labelList = theJsonData[i].result.labels;
                 for (h = 0; h < labelList.length; h++) {
                   labels = labels + theJsonData[i].result.labels[h] +  " ";
                 }
                 labels.trim();


                 var iconPath = findPreselectionMarkerImg(theJsonData[i].result.mappingId, labels);

                 var marker = new google.maps.Marker({
                			position: latitudeLng,
                			map: mapPreselection,
                			title: hotelName,
                			label: labels,
                			icon: iconPath,
                			animation: google.maps.Animation.DROP});
                	markersArray[i] = marker;
                	dropPreselectionMarker(marker);
      }

      return markersArray;
}

function nameGenerator(name){
   var generateName = "";
   if (name != null){
         if (name.length > 18){
            generateName = name.substring(0, 18) + "..";
         } else {
            generateName = name;
         }
   }
   return generateName;
}

function changeZoomLevel(){
    var distance = document.getElementById("selectedDistance");
    var distanceSelection = distance.options[distance.selectedIndex].value;

     var hiddenDistance = jQuery("input[class*=hiddenDistance]");
     hiddenDistance[0].value = distanceSelection;

    var distanceInt = parseInt(distanceSelection);
    var myZoomLevel = 1
      if (distanceInt == 1 || distanceInt == 2) {
               myZoomLevel = 14;
      } else if (distanceInt == 5) {
               myZoomLevel = 13;
      } else if (distanceInt == 10) {
               myZoomLevel = 12;
      } else {
          myZoomLevel = 10;
    }
    mapPreselection.setZoom(myZoomLevel);
    zoomLevel = myZoomLevel;

    clearAdditionalMarkers();
    clearPreselectionMarkers();
    hideButtons();
}

function hideAdditionalHotels(){
   clearAdditionalMarkers();
}

function showAdditionalHotels(){
jsonAddtionalData = JSON.parse(document.getElementById('jsonAdditionData').textContent);

     if (typeof(jsonAddtionalData) !== "undefined" && jsonAddtionalData){

         for (var i = 0; i <= jsonAddtionalData.length - 1; i++) {
                         displayPreselecionMap();

                         var latitudeLng = new google.maps.LatLng(jsonAddtionalData[i].result.geometry.location.lat, jsonAddtionalData[i].result.geometry.location.lng);
                         var hotelName = jsonAddtionalData[i].result.name;

                         var generatedName = nameGenerator(hotelName)

                         var serviceProviderId = jsonAddtionalData[i].result.serviceProviderId;

                         var iconPath = findAdditonMarkerImg(hotelName);

                         var marker = new google.maps.Marker({
                                    position: latitudeLng,
                                    map: mapPreselection,
                                    title: serviceProviderId,
                                    label: generatedName,
                                    icon: iconPath,
                                    animation: google.maps.Animation.DROP});
                            additionalMarkers[i] = marker;
                            dropAdditionalMarker(i);
         }
         addAdditonalMarkerListener();
         switchPreslectionMarkers();
     }
}

function copyServiceProviderId(serviceProviderId){
  var inputField = jQuery("input[class*=inviteServiceProviderId]");
  inputField.val(serviceProviderId);
}

function pushInvitePreselectedButton(serviceProviderId){

     copyServiceProviderId(serviceProviderId);

     var buttons = jQuery("input[class*=testIdGeoInviteAsPreselectedBtn]");

     removeAdditionalMarker(serviceProviderId);

      for(i = 0; i < buttons.length; i++){
          buttons[i].click(function(){
             jQuery( this ).click();
          });
    }
}

function pushPreventedButton(serviceProviderId){

     copyServiceProviderId(serviceProviderId);

     var buttons = jQuery("input[class*=testIdGeoInviteAsPresentedBtn]");

     removeAdditionalMarker(serviceProviderId);

      for(i = 0; i < buttons.length; i++){
          buttons[i].click(function(){
             jQuery( this ).click();
          });
    }
}

function clearAdditionalMarkers() {
    for (var i = 0; i < additionalMarkers.length; i++) {
      if (additionalMarkers[i]) {
            additionalMarkers[i].setMap(null);
      }
    }
    additionalMarkers = [];
    switchAddtionalMarkers();
}

function switchAddtionalMarkers(){
    var showButton = jQuery("input[class*=showAdditionalHotels]");
    showButton[0].style.display = "block";

    var hideButton = jQuery("input[class*=hideAdditionalHotels]");
    hideButton[0].style.display = "none";
}

function switchPreslectionMarkers(){
    var showButton = jQuery("input[class*=showAdditionalHotels]");
    showButton[0].style.display = "none";

    var hideButton = jQuery("input[class*=hideAdditionalHotels]");
    hideButton[0].style.display = "block";
}

function hideButtons(){
    var showButton = jQuery("input[class*=showAdditionalHotels]");
    showButton[0].style.display = "none";

    var hideButton = jQuery("input[class*=hideAdditionalHotels]");
    hideButton[0].style.display = "none";
}

function initMasterDataMap(mapDiv, myLatLng, isDraggable, titleString) {
    var map = new google.maps.Map(mapDiv, {
      zoom: 17,
      draggable: true,
      center: myLatLng,
    });
    addStyleControls(map);
    var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    draggable: isDraggable,
    title: titleString
    });

    marker.addListener('mouseup', function(event){
        copyMarker(marker.getPosition().lat(),marker.getPosition().lng());
    });
}

function addStyleControls(map) {
    // Add controls to the map, allowing users to hide/show features.
    var styleControl = document.getElementById('style-selector-control');
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(styleControl);
     // Apply new JSON when the user chooses to hide/show features.
    document.getElementById('hide-poi').addEventListener('click', function() {
          map.setOptions({styles: styles['hide']});
    });
    document.getElementById('show-poi').addEventListener('click', function() {
          map.setOptions({styles: styles['default']});
    });
    map.setOptions({styles: styles['default']});
}

function onStatusChangeRefreshMap(data) {
   var status = data.status;
       if (status === "success") {
            refreshPreselectionMapPoints();
            refreshAdditionalMapPoints();
       }
}
