const userMenuButton = document.getElementById("userMenuButton");
const greyOut = document.getElementById("greyOut");
const usersTable = document.getElementById("usersTable");
const newUserForm = document.getElementById("newUserForm");
const editUserDiv = document.getElementById("editUserDiv");
const editUserForm = document.getElementById("editUserForm");
const changeUserPasswordForm = document.getElementById("changeUserPasswordForm");
const changeUserPasswordOutput = document.getElementById("changeUserPasswordOutput");
const userHeaderContent = document.getElementById("userHeaderContent");
const userReturnButton = document.getElementById("userReturnButton");
const addUserButton = document.getElementById("addUserButton");

const select = document.getElementById("navStatusSelect");
const selected = select.querySelector(".selected");
const options = select.querySelector(".options");
const hiddenInput = document.getElementById("navStatusValue");

// toggle dropdown
selected.addEventListener("click", () => {
  options.style.display = options.style.display === "block" ? "none" : "block";
});

// select option
options.querySelectorAll("div").forEach(option => {
  option.addEventListener("click", () => {
    selected.textContent = option.textContent;
    hiddenInput.value = option.dataset.value;
    options.style.display = "none";
  });
});

// close if clicked outside
document.addEventListener("click", (e) => {
  if (!select.contains(e.target)) {
    options.style.display = "none";
  }
});


const questionnaireScoringThresholds = {
    low: 150,
    medium: 127,
}

console.log(host_URL);
console.log(document_root);
console.log(app_root);
console.log(parent_folder);

function unescape(text) {
    if (typeof text !== "string") {
        return text;
    } else {
        return text.replaceAll(/\\'/g, "'").replaceAll(/\\"/g, "\"").replaceAll(/\\n/g, "\n");
    }
}

  mapboxgl.accessToken = 'pk.eyJ1IjoiYW1lb3MiLCJhIjoiY2x1a3VncHZhMDdwYzJtb2ZsbWIwaGt5MSJ9.23kQZmiKT4U8HnVvP6JtrQ';

  const lightStyle = 'mapbox://styles/ameos/clwf2fafj00fc01ny4tbdabta';
  const darkStyle = 'mapbox://styles/mapbox/dark-v11';

  let currentMode = 'light';
  let map;

  // Initial map load
function initMap(style) {
  map = new mapboxgl.Map({
    container: 'map',
    center: [20, 35],
    zoom: 1.00,
    minZoom: 0.00,
    maxZoom: 20.00,
    style: style
  });

  map.on('style.load', () => {
    map.setProjection('mercator'); // Flat projection
  });
}

  initMap(lightStyle); // Start with light mode

 // Function to hide the questionnaire section
  function hideUser() {
    document.getElementById("tab_8").style.display = "none";
  }

function closeAllPanels() {
  document.getElementById('geocoder').style.display = 'none';
  document.querySelector('.map-options').classList.remove('visible');
  document.querySelector('.direction_panels').classList.remove('visible');
  document.getElementById("alert_console_container").style.display = "none";
  document.getElementById("userDropdown").style.display = "none";
  close_incident_panel();
  close_danger_panel();
  hideUser();
  closePopup();
  console_shown = false; // reset console state
}


  
  // Toggle dark/light mode
function reset_mode() {
  const icon = document.querySelector('.icons_topbar_dark');

  const center = map.getCenter();
  const zoom = map.getZoom();

  currentMode = (currentMode === 'light') ? 'dark' : 'light';
  const newStyle = (currentMode === 'dark') ? darkStyle : lightStyle;

  icon.src = currentMode === 'dark'
    ? './assets/images/light.svg'
    : './assets/images/dark.svg';
  icon.classList.toggle('icon-toggled');

  map.setStyle(newStyle);

map.on('style.load', () => {
  map.setCenter(center);
  map.setZoom(zoom);
  map.setProjection('mercator');

  if (currentMode === 'dark') {
    const layers = map.getStyle().layers;

    // Change background (land base)
    const landLayer = layers.find(layer => layer.type === 'background');
    if (landLayer) {
      map.setPaintProperty(landLayer.id, 'background-color', '#333F48');
    }

    // Change water layers
    layers.forEach(layer => {
      if (layer.id.includes('water') && layer.type === 'fill') {
        map.setPaintProperty(layer.id, 'fill-color', '#1E2931');
      }
    });
    // Improve text visibility
    map.getStyle().layers.forEach(layer => {
    if (layer.type === 'symbol' && layer.layout && layer.layout['text-field']) {
        // Brighten text color
        map.setPaintProperty(layer.id, 'text-color', '#FFFFFF'); // Pure white text
        // Add glow around text
        map.setPaintProperty(layer.id, 'text-halo-color', '#000000'); // Black halo
        map.setPaintProperty(layer.id, 'text-halo-width', 1.5);
        map.setPaintProperty(layer.id, 'text-halo-blur', 0.5);
    }
    });
  }
});

}


    
const geocoder = new MapboxGeocoder({
        accessToken: mapboxgl.accessToken,
        mapboxgl: mapboxgl
})
document.getElementById('geocoder').appendChild(geocoder.onAdd(map));

const distance_item = new mapboxgl.ScaleControl();
document.getElementById('distance').appendChild(distance_item.onAdd(map))

map.on('load', () => {

    map.addSource('route_line', {
    'type': 'geojson',
    'data': {
    'type': 'Feature',
    'properties': {},
    'geometry': {
    'type': 'LineString',
    'coordinates': []
    }
    }
    });

    map.addLayer({
    'id': 'route_line',
    'type': 'line',
    'source': 'route_line',
    'layout': {
    'line-join': 'round',
    'line-cap': 'round'
    },
    'paint': {
    'line-color': '#3bff58',
    'line-width': 2.5
    }
    });


    map.addSource('polygon_line', {
        'type': 'geojson',
        'data': {
            'type': 'Feature',
            'geometry': {
                'type': 'Polygon',
                'coordinates': []
            }
        }
    });
     
    // Add a new layer to visualize the polygon.
    map.addLayer({
        'id': 'polygon_middle',
        'type': 'fill',
        'source': 'polygon_line', // reference the data source
        'layout': {},
        'paint': {
            'fill-color': '#0080ff', // blue color fill
            'fill-opacity': 0.5
        }
    });

    // Add a black outline around the polygon.
    map.addLayer({
        'id': 'polygon_outline',
        'type': 'line',
        'source': 'polygon_line',
        'layout': {},
        'paint': {
            'line-color': '#000',
            'line-width': 1
        }
    });


});


function logoutClicked() {
    
    location.replace("http://" + host_URL + "/client_login.php");
}

// function logoClicked() {
    
//     window.open("http://eosrisk.critical.media/", "_blank");
// }


/////////////////////////////////// Handles the API Call


function load_vessel_data() { 

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/load_vessel_data.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            remove_vessel_markers()

            api_response_data = (this.responseText);

            var api_array = api_response_data.split(',;')
            // console.log(api_array)
            
            var array_api_length = (api_array.length / 14) - 1;
            for (let x = 0; x <= array_api_length; x++) {

                var imo = api_array[14*x + 0]
                var latitude = Number(api_array[14*x + 1]);
                var longitude = Number(api_array[14*x + 2]);
                var heading = api_array[14*x + 3]

                // console.log(imo)
                // console.log(latitude)
                // console.log(longitude)
                // console.log("---")

                var name = api_array[14*x + 4]
                var callsign = api_array[14*x + 5]
                var shipType = api_array[14*x + 6]
                var is_vessel_inside_eos_dmz = api_array[14*x + 7]
                var is_vessel_inside_route = api_array[14*x + 8]
                var navigationalStatus = api_array[14*x + 9]
                var mmsi = api_array[14*x + 10]
                var speed = api_array[14*x + 11]
                var destination = api_array[14*x + 12]
                var date_received = api_array[14*x + 13];

                var current_date_seconds = new Date().getTime()
                var date_received_seconds = new Date(date_received).getTime()
                var time_difference_milliseconds = current_date_seconds - date_received_seconds
                var time_difference_seconds = time_difference_milliseconds / 1000
                var time_difference_minutes = time_difference_seconds / 60
                var time_difference_hours = time_difference_minutes / 60

                create_vessel_marker(imo, latitude, longitude, heading, name, callsign, shipType, is_vessel_inside_eos_dmz, is_vessel_inside_route, navigationalStatus, mmsi, speed, destination, date_received, time_difference_hours)
            }

            if (global_filtered_vessels_loaded_array.length > 0) { // only load unfiltered vessel list if there are vessels on it
                load_unfiltered_vessels(); // loads any vessels the user has viewed, but arent currently filtered on 
            }
            else {
                // do nothing, no more vessels need loading
            }

        }
    }
    ajax_request.send(data_to_send);
}
load_vessel_data()


var global_vessel_markers_array = []; // holds all vessel marker data for removal
function create_vessel_marker(imo, latitude, longitude, heading, name, callsign, shipType, is_vessel_inside_eos_dmz, is_vessel_inside_route, navigationalStatus, mmsi, speed, destination, date_received, time_difference_hours) {

    const customMarker = document.createElement('div');
    if (heading == 511) {
        
        if (time_difference_hours > 24) {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/yellow_circle.png)';
            customMarker.style.width = '20px';
            customMarker.style.height = '20px';
        }

        else if (is_vessel_inside_eos_dmz == 1) {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/red_circle.png)';
            customMarker.style.width = '20px';
            customMarker.style.height = '20px';
        }

        else if (is_vessel_inside_route == 1) {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/green_circle.png)';
            customMarker.style.width = '20px';
            customMarker.style.height = '20px';
        }

        else {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/cyan_circle.png)';
            customMarker.style.width = '20px';
            customMarker.style.height = '20px';
        }

    }   


    else {

        if (time_difference_hours > 24) {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/yellow_cursor.png)';
            customMarker.style.width = '18px';
            customMarker.style.height = '18px';
        }

        else if (is_vessel_inside_eos_dmz == 1) {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/red_cursor.png)';
            customMarker.style.width = '18px';
            customMarker.style.height = '18px';
        }

        else if (is_vessel_inside_route == 1) {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/green_cursor.png)';
            customMarker.style.width = '18px';
            customMarker.style.height = '18px';
        }

        else {
            customMarker.style.backgroundImage = 'url(' + document_root + '/assets/cyan_cursor.png)';
            customMarker.style.width = '18px';
            customMarker.style.height = '18px';
        }

    }

    customMarker.style.backgroundSize = 'cover';
    customMarker.style.backgroundPosition = 'center';
    customMarker.setAttribute('class','map_markers');
    customMarker.setAttribute('id', "marker_" + imo);

    const detailed_popup = new mapboxgl.Popup({className: "detailed_popup"}).setHTML("<b>IMO: </b>"+imo+"<br>"+"<b>Name: </b>"+"<a href='javascript:void(0);' onclick=vessel_manager_open_edit("+imo+")>"+name+"</a>"+"<br>"+"<b>Callsign: </b>"+callsign+"<br>"+"<b>shipType: </b>"+shipType+"<br>"+"<b>Status: </b>"+navigationalStatus+"<br>"+"<b>MMSI: </b>"+mmsi+"<br>"+"<b>Speed: </b>"+speed+"<br>"+"<b>Destination: </b>"+destination+"<br>"+"<b>Latitude: </b>"+latitude+"<br>"+"<b>Longitude: </b>"+longitude+"<br>"+"<b>Date: </b>"+date_received+"<br>"+"<button class='log_action_button' onclick='log_action("+imo+")' >Log Action</button>"+"<br>"+"<button class='view_route_button' onclick='route_open_button("+imo+")' >View Route</button>"+"<br>")
    const name_popup = new mapboxgl.Popup({closeButton: false, className: "name_popup"}).setHTML("<b>Name: </b>"+name)

    const marker = new mapboxgl.Marker({
        anchor: 'center',
        element: customMarker,
        rotation: heading
      })
    .setLngLat([longitude, latitude])
    .setPopup(name_popup)
    .addTo(map)

    global_vessel_markers_array.push(marker); // add marker to array for removal later

    // console.log(customMarker)
    // console.log(marker)

    const mouse_enter = () => { // toggles popup when mouse enters marker
        marker.togglePopup()
    };

    const mouse_leave = () => { // toggles popup when mouse enters marker
        marker.togglePopup()
    };

    const mouse_click = () => { // enables detailed popup, and disables hover on specific popup when mouse clicks marker

        marker.setPopup(detailed_popup)
        markerDiv.removeEventListener("mouseenter", mouse_enter)
        markerDiv.removeEventListener("mouseleave", mouse_leave)

    };

    const markerDiv = marker.getElement() // creates element around marker and adds hover and click EventListeners
    markerDiv.addEventListener("mouseenter", mouse_enter)
    markerDiv.addEventListener("mouseleave", mouse_leave)
    markerDiv.addEventListener("click", mouse_click)

    var prevent_close = false;
    detailed_popup.on('close', function(e) {

        if (prevent_close == false) { // stops close function looping when popup is unset

            prevent_close = true

            marker.setPopup(name_popup)
            markerDiv.addEventListener("mouseenter", mouse_enter)
            markerDiv.addEventListener("mouseleave", mouse_leave)

        }

        else {

            prevent_close = false
        }

    })

}


function remove_vessel_markers() { // call this function to remove all vessel_markers on map

    global_vessel_markers_array.forEach((marker) => marker.remove())
    global_vessel_markers_array = [];

}


/////////////////////////////////////////////////////////////////// EEZ Layer

map.on('load', () => {

    map.addSource('mapbox-terrain', {
        type: 'vector',
        url: 'mapbox://ameos.3pdg97l7'
    });

    map.addLayer({
        'id': 'eez_lines',
        'type': 'line',
        'source': 'mapbox-terrain',
        'source-layer': 'eez_v11-do2afn',
        'layout': {
            'visibility': 'none',
            'line-join': 'round',
            'line-cap': 'round'
        },
        'paint': {
            'line-color': '#808080',
            'line-width': 0.5
        },
    });

});

/////////////////////////////////////////////////////////////////// EEZ Layer

map.on('load', () => {

    map.addSource('temp-data', {
        "type": "raster",
        "tiles": ['https://tile.openweathermap.org/map/temp_new/{z}/{x}/{y}.png?appid=847ddbcd20b288782fb05a1f49892eec'],
        "tileSize": 256
    });

    map.addLayer({
        "id": "temp-layer",
        "type": "raster",
        "source": "temp-data",
        "minzoom": 0,
        "maxzoom": 20,
        'layout': {
            'visibility': 'none'
        },
    });


    map.addSource('precipitation-data', {
        "type": "raster",
        "tiles": ['https://tile.openweathermap.org/map/precipitation_new/{z}/{x}/{y}.png?appid=847ddbcd20b288782fb05a1f49892eec'],
        "tileSize": 256
    });

    map.addLayer({
        "id": "precipitation-layer",
        "type": "raster",
        "source": "precipitation-data",
        "minzoom": 0,
        "maxzoom": 20,
        'layout': {
            'visibility': 'none'
        },
    });


    map.addSource('pressure-data', {
        "type": "raster",
        "tiles": ['https://tile.openweathermap.org/map/pressure_new/{z}/{x}/{y}.png?appid=847ddbcd20b288782fb05a1f49892eec'],
        "tileSize": 256
    });

    map.addLayer({
        "id": "pressure-layer",
        "type": "raster",
        "source": "pressure-data",
        "minzoom": 0,
        "maxzoom": 20,
        'layout': {
            'visibility': 'none'
        },
    });


    map.addSource('wind-data', {
        "type": "raster",
        "tiles": ['https://tile.openweathermap.org/map/wind_new/{z}/{x}/{y}.png?appid=847ddbcd20b288782fb05a1f49892eec'],
        "tileSize": 256
    });

    map.addLayer({
        "id": "wind-layer",
        "type": "raster",
        "source": "wind-data",
        "minzoom": 0,
        "maxzoom": 20,
        'layout': {
            'visibility': 'none'
        },
    });


    map.addSource('clouds-data', {
        "type": "raster",
        "tiles": ['https://tile.openweathermap.org/map/clouds_new/{z}/{x}/{y}.png?appid=847ddbcd20b288782fb05a1f49892eec'],
        "tileSize": 256
    });

    map.addLayer({
        "id": "clouds-layer",
        "type": "raster",
        "source": "clouds-data",
        "minzoom": 0,
        "maxzoom": 20,
        'layout': {
            'visibility': 'none'
        },
    });

});

temp_toggle = 1;
function toggleTemp() {

    if (temp_toggle < 0) {
        //console.log("T")
        map.setLayoutProperty('temp-layer', 'visibility', 'none');
        temp_toggle = temp_toggle + 2
    }

    else if (temp_toggle > 0) {
        //console.log("F")
        map.setLayoutProperty('temp-layer', 'visibility', 'visible');
        temp_toggle = temp_toggle - 2
    }
}

precipitation_toggle = 1;
function togglePrecipitation() {

    if (precipitation_toggle < 0) {
        //console.log("T")
        map.setLayoutProperty('precipitation-layer', 'visibility', 'none');
        precipitation_toggle = precipitation_toggle + 2
    }

    else if (precipitation_toggle > 0) {
        //console.log("F")
        map.setLayoutProperty('precipitation-layer', 'visibility', 'visible');
        precipitation_toggle = precipitation_toggle - 2
    }
}

pressure_toggle = 1;
function togglePressure() {

    if (pressure_toggle < 0) {
        //console.log("T")
        map.setLayoutProperty('pressure-layer', 'visibility', 'none');
        pressure_toggle = pressure_toggle + 2
    }

    else if (pressure_toggle > 0) {
        //console.log("F")
        map.setLayoutProperty('pressure-layer', 'visibility', 'visible');
        pressure_toggle = pressure_toggle - 2
    }
}

wind_toggle = 1;
function toggleWind() {

    if (wind_toggle < 0) {
        //console.log("T")
        map.setLayoutProperty('wind-layer', 'visibility', 'none');
        wind_toggle = wind_toggle + 2
    }

    else if (wind_toggle > 0) {
        //console.log("F")
        map.setLayoutProperty('wind-layer', 'visibility', 'visible');
        wind_toggle = wind_toggle - 2
    }
}

clouds_toggle = 1;
function toggleClouds() {

    if (clouds_toggle < 0) {
        //console.log("T")
        map.setLayoutProperty('clouds-layer', 'visibility', 'none');
        clouds_toggle = clouds_toggle + 2
    }

    else if (clouds_toggle > 0) {
        //console.log("F")
        map.setLayoutProperty('clouds-layer', 'visibility', 'visible');
        clouds_toggle = clouds_toggle - 2
    }
}


// Manually unchecks each checkbox on page load
// document.getElementById("testMenuCheckbox2").checked = false;
// document.getElementById("testMenuCheckbox3").checked = false;
// document.getElementById("testMenuCheckbox6").checked = false;
// document.getElementById("testMenuCheckbox7").checked = false;
// document.getElementById("testMenuCheckbox8").checked = false;
// document.getElementById("testMenuCheckbox9").checked = false;
// document.getElementById("testMenuCheckbox10").checked = false;
// document.getElementById("testMenuCheckbox11").checked = false;

x_eez = 1;
function addEEZ() {

    if (x_eez < 0) {
        //console.log("T")
        map.setLayoutProperty('eez_lines', 'visibility', 'none');
        x_eez = x_eez + 2
    }

    else if (x_eez > 0) {
        //console.log("F")
        map.setLayoutProperty('eez_lines', 'visibility', 'visible');
        x_eez = x_eez - 2
    }
}


//////////////////////////////////////////////////////////////////////////////////////////

var long_degrees;
var long_minutes;
var long_seconds;
var east_west;

var lat_degrees;
var lat_minutes;
var lat_seconds;
var north_south;


var long_dms;
var long_raw;
var lat_dms;
var lat_raw;

map.on('mousemove', (mousemove_object) => {

    var longLat = mousemove_object.lngLat.wrap(); // Takes lnglat parameter from the mousemove_object
    var longLatValues = Object.values(longLat)
    //console.log(longLatValues)
    var long_var = longLatValues[0].toString()
    var lat_var = longLatValues[1].toString()
    
    long_raw = Number(long_var).toFixed(2);
    lat_raw = Number(lat_var).toFixed(2);

    long_dms = long_to_dms(long_var)
    lat_dms = lat_to_dms(lat_var)

    document.getElementById('info').innerHTML =

    "Lat: " + lat_dms + "  " + "Long: " + long_dms

});



function long_to_dms(long_var) {

    if (long_var >= 0) {
        east_west = "E";
    }

    else if (long_var < 0) {
        east_west = "W";
    }

    var long_var_abs = Math.abs(long_var);
    long_degrees = Math.trunc(long_var_abs);
    var long_degrees_decimal = (long_var_abs % 1);

    var long_minutes_raw = (long_degrees_decimal * 60)
    long_minutes = Math.trunc(long_minutes_raw);
    var long_minutes_decimal = (long_minutes_raw % 1)

    var long_seconds_raw = (long_minutes_decimal * 60)
    long_seconds = Math.trunc(long_seconds_raw);


    long_dms = (long_degrees + "Â°" + long_minutes + "\'" + long_seconds + "\"" + east_west);
    return long_dms;

}

function lat_to_dms(lat_var) {

    if (lat_var >= 0) {
        north_south = "N";
    }

    else if (lat_var < 0) {
        north_south = "S";
    }

    var lat_var_abs = Math.abs(lat_var);
    lat_degrees = Math.trunc(lat_var_abs);
    var lat_degrees_decimal = (lat_var_abs % 1);

    var lat_minutes_raw = (lat_degrees_decimal * 60)
    lat_minutes = Math.trunc(lat_minutes_raw);
    var lat_minutes_decimal = (lat_minutes_raw % 1)

    var lat_seconds_raw = (lat_minutes_decimal * 60)
    lat_seconds = Math.trunc(lat_seconds_raw);


    lat_dms = (lat_degrees + "Â°" + lat_minutes + "\'" + lat_seconds + "\"" + north_south);
    return lat_dms;
    
}

function long_to_dm(long_var) {

    if (long_var >= 0) {
        east_west = "E";
    }

    else if (long_var < 0) {
        east_west = "W";
    }

    var long_var_abs = Math.abs(long_var);
    long_degrees = Math.trunc(long_var_abs);
    var long_degrees_decimal = (long_var_abs % 1);

    var long_minutes_raw = (long_degrees_decimal * 60)
    long_minutes = long_minutes_raw.toFixed(3);


    long_dms = (long_degrees + "Â°" + long_minutes + "\'" + east_west);
    return long_dms;

}

function lat_to_dm(lat_var) {

    if (lat_var >= 0) {
        north_south = "N";
    }

    else if (lat_var < 0) {
        north_south = "S";
    }

    var lat_var_abs = Math.abs(lat_var);
    lat_degrees = Math.trunc(lat_var_abs);
    var lat_degrees_decimal = (lat_var_abs % 1);

    var lat_minutes_raw = (lat_degrees_decimal * 60)
    lat_minutes = lat_minutes_raw.toFixed(3);


    lat_dms = (lat_degrees + "Â°" + lat_minutes + "\'" + north_south);
    return lat_dms;
    
}


function dms_to_raw(dms_test) {

    let dms_commas = dms_test.replace("Â°", ",").replace("\'", ",").replace("\"", ",");
    const dms_array = dms_commas.split(",");
    var pos_neg;

    if (dms_array[3] == "N") {
        pos_neg = "1"
    }

    if (dms_array[3] == "E") {
        pos_neg = "1"
    }   

    if (dms_array[3] == "S") {
        pos_neg = "-1"
    }   

    if (dms_array[3] == "W") {
        pos_neg = "-1"
    }      

    var multiplier = Number (pos_neg)
    var number_0 = Number(dms_array[0])
    var number_1 = Number(dms_array[1]/60)
    var number_2 = Number(dms_array[2]/3600)

    var raw_lnglat = (multiplier*(number_0 + number_1 + number_2));;
    return raw_lnglat.toFixed(8);

}


map.on('click', (e) => {
    if (e.originalEvent.target.closest('.mapboxgl-marker')) {
        return // Click target was a marker so do nothingâ€¦
    }

    else {
        clickMap()
    }
})


function clickMap() {

    var latitude_clicked = lat_raw;
    var longitude_clicked = long_raw;


    if (polygon_plotting_enabled == true) {

        polygon_plot_point(latitude_clicked, longitude_clicked);
        polygon_update_visual_from_box()

    }
    else {
        // do nothing
    }


    if (incident_plotting_enabled == true) {

        incident_plot_point(latitude_clicked, longitude_clicked);

    }
    else {
        // do nothing
    }


    if (port_add_plotting_enabled == true) {

        port_add_insert_coordinate(lat_raw, long_raw)

    }
    else {
        // do nothing
    }


}


function enable_grabber() {

    map.getCanvas().style.cursor = 'grab';

    map.on('mousedown', () => {
        map.getCanvas().style.cursor = 'grabbing';
    });

    map.on('mouseup', () => {
        map.getCanvas().style.cursor = 'grab';
    });

}

function enable_crosshair() {

    map.getCanvas().style.cursor = 'crosshair';

    map.on('mousedown', () => {

        map.getCanvas().style.cursor = 'crosshair';
    });

    map.on('mouseup', () => {
        map.getCanvas().style.cursor = 'crosshair';
    });

}



function optionsOpen() {

    //console.log("optionsOpen()");

    if (is_nothing_open == true) {

        is_nothing_open = false;


        if (window.permissions[1] !== "0") {
            reload_route_imo_selector()
        }

        document.getElementById("route_imo_dropdown").selectedIndex = 0;

        route_manager_retrieve_lines();
        polygon_manager_load_all_lines();
        vessel_manager_retrieve_lines();
        port_manager_retrieve_data();


        fullMenuBox.style.left = "10px";
        closeMenuBox.style.display = "block";

        let filter_company_box = document.getElementById("fullCompaniesFilterBox");
        let filter_dmz_box = document.getElementById("fullDmzFilterBox");

        filter_dmz_box.style.left = "-400px";
        filter_company_box.style.left = "-400px";
    }

    else {
        // do nothing
    }

}

// Companies and DMZs filter toggler function
function filterCompaniesToggler() {
    let filter_company_box = document.getElementById("fullCompaniesFilterBox");
    let filter_dmz_box = document.getElementById("fullDmzFilterBox");

    let company_left_style = parseInt(window.getComputedStyle(filter_company_box).left);
    let dmz_left_style = parseInt(window.getComputedStyle(filter_dmz_box).left);

    // Hide DMZ box when opening the Companies box
    if (dmz_left_style === 10) {
        filter_dmz_box.style.left = "-400px";
    }

    filter_company_box.style.left = company_left_style === -400 ? "10px" : "-400px";

    optionsClose();
}

let dmz_first_load = false;
function filterDmzToggler() {
    let filter_dmz_box = document.getElementById("fullDmzFilterBox");
    let filter_company_box = document.getElementById("fullCompaniesFilterBox");

    let dmz_left_style = parseInt(window.getComputedStyle(filter_dmz_box).left);
    let company_left_style = parseInt(window.getComputedStyle(filter_company_box).left);

    // Hide Companies box when opening the DMZ box
    if (company_left_style === 10) {
        filter_company_box.style.left = "-400px";
    }

    const tabs = document.querySelectorAll(".tab-button");
    tabs[0].click(); // Click the first tab to load the DMZ data

    filter_dmz_box.style.left = dmz_left_style === -400 ? "10px" : "-400px";

    optionsClose();
}

// JavaScript for Tab Switching 
document.addEventListener("DOMContentLoaded", function() {
    const tabs = document.querySelectorAll(".tab-button");
    const tabPanes = document.querySelectorAll(".tab-pane");

    // Show the first tab by default
    if (tabs.length > 0) {
        tabs[0].classList.add("active");
        tabPanes[0].style.display = "block";
    }

    // Add event listeners for tab buttons
    let dmz_first_loads = [];
    tabs.forEach(tab => {
        tab.addEventListener("click", function() {
            const targetTab = this.getAttribute("data-tab");
            let targetType = this.getAttribute("data-type");
            let toggle_dmz_button = document.getElementById("toggleAllPolygons");
            let toggle_all_polygons_text = document.getElementById("toggle-all-polygons-text");

            toggle_dmz_button.checked ? toggle_all_polygons_text.textContent = "Collapse DMZs" : toggle_all_polygons_text.textContent = "Display DMZs";

            if (toggle_dmz_button.checked && dmz_first_loads[targetType] !== true) {
                
                dmz_first_loads[targetType] = true;
                refreshMarkers();

                load_all_polygons(targetType);
            }
            
            // Hide all tab panes
            tabPanes.forEach(pane => {
                pane.style.display = "none";
            });

            // Remove active class from all tabs
            tabs.forEach(t => t.classList.remove("active"));

            // Show the selected tab pane
            document.getElementById(targetTab).style.display = "block";
            this.classList.add("active");
        });
    });
});

let requestCount = 0;
document.addEventListener("DOMContentLoaded", function() {
    const toggleAll = document.getElementById("toggleAllPolygons");
    const selectAllCheckboxes = document.querySelectorAll(".select-all");
    const individualCheckboxes = document.querySelectorAll(".polygon-checkbox");

    // Event listener for each "Select All" per type
    selectAllCheckboxes.forEach(selectAll => {
        selectAll.addEventListener("change", function() {
            const type = this.getAttribute("data-type");
            const checkboxes = document.querySelectorAll(`.polygon-checkbox[data-type='${type}']`);

            this.nextElementSibling.textContent = this.checked ? `Unselect All ${type}` : `Select All ${type}`;

            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });

            checkboxes.forEach(checkbox => {
                document.getElementById('overlay').style.display = 'flex';
                requestCount++;
                updatePolygonSelection(checkbox.dataset.number, this.checked, checkbox.dataset.type, true);
            });
        });
    });

    // Individual checkbox change listener to keep "Select All" and global toggle in sync
    individualCheckboxes.forEach(checkbox => {
        checkbox.addEventListener("change", function() {
            const type = this.getAttribute("data-type");
            const typeCheckboxes = document.querySelectorAll(`.polygon-checkbox[data-type='${type}']`);
            const allChecked = [...typeCheckboxes].every(box => box.checked);

            // Update the respective "Select All" checkbox
            const selectAll = document.querySelector(`.select-all[data-type='${type}']`);
            if (selectAll) {
                selectAll.checked = allChecked;
            }

            // Send AJAX request to update the database for this specific polygon
            updatePolygonSelection(this.dataset.number, this.checked, this.dataset.type, false);
        });
    });

    // Global toggle event
    toggleAll.addEventListener("change", function() {
        toggleAllCheckboxes(this.checked);
        saveDmzPreference(this.dataset.number, this.checked, this.dataset.type);

        let toggle_dmz_button = document.getElementById("toggleAllPolygons");
        let toggle_all_polygons_text = document.getElementById("toggle-all-polygons-text");

        toggle_dmz_button.checked ? toggle_all_polygons_text.textContent = "Collapse DMZs" : toggle_all_polygons_text.textContent = "Display DMZs";

    });

    // Function to check/uncheck all checkboxes and update DB
    function toggleAllCheckboxes(isChecked) {
        individualCheckboxes.forEach(checkbox => {
            let polygonNumber = checkbox.dataset.number;
            let polygonType = checkbox.dataset.type;
            let isSelected = checkbox.checked;

            if (isChecked) {
                if (isSelected) {
                    load_all_polygon_details(polygonNumber, polygonType);
                }
            } else {
                remove_polygon_zones(polygonNumber, polygonType);
            }
        });
    }

    // Check if all checkboxes are checked for each type and mark "Select All"
    selectAllCheckboxes.forEach(selectAll => {
        const type = selectAll.getAttribute("data-type");
        const checkboxes = document.querySelectorAll(`.polygon-checkbox[data-type='${type}']`);
        
        // Check if all checkboxes are checked for the current type
        const allChecked = [...checkboxes].every(checkbox => checkbox.checked);

        // If all are checked, set the "Select All" checkbox to checked
        if (allChecked) {
            selectAll.checked = true;
            selectAll.nextElementSibling.textContent = `Unselect All ${type}`;
        }
    });

    // Function to send AJAX request to update the database for a specific polygon
    function updatePolygonSelection(polygonNumber, isSelected, polygonType, isInBatch) {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', app_root + '/admin_scripts/update_selection.php', true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(`polygon_number=${polygonNumber}&is_displayed=${isSelected ? 1 : 0}`);
        xhr.onload = function() {
            if (xhr.status === 200) {
                if (isSelected && toggleAll.checked) {
                    load_all_polygon_details(polygonNumber, polygonType);
                } else {
                    remove_polygon_zones(polygonNumber, polygonType);
                }
                if (isInBatch) {
                    requestCount--;
                }
                if (requestCount === 0) {
                    hideSpinnerWithDelay();
                }
            }
        };
        xhr.onerror = function() {
            hideSpinnerWithDelay();
        }
        
    }
});

function saveDmzPreference(polygonNumber, isDisplayed, polygonType) {
    fetch(app_root + "/admin_scripts/update_selection.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: new URLSearchParams({
            display_dmz: "true",
            is_displayed: isDisplayed ? "1" : "0"
        })
    })
    .then(response => response.json()) 
    
    .catch(error => console.error("Error saving DMZ display preference:", error));
}


function refreshMarkers() {
    // Remove current markers and polygons from the map
    remove_all_incidents();
    remove_all_polygons();
    incident_remove_single_marker();
    
}

function hideSpinnerWithDelay() {

    setTimeout(() => {
        document.getElementById('overlay').style.display = 'none';
    }, 1500);
}

// Function to check the "Select All Companies" checkbox on page load
function checkSelectAllOnLoad() {
    const companyCheckboxes = document.querySelectorAll('.company-checkbox-container input[type="checkbox"]');
    const allChecked = Array.from(companyCheckboxes).every(checkbox => checkbox.checked);
    document.getElementById('select_all_companies').checked = allChecked;
}

function toggleSelectAllCompanies(_this) {
    const isChecked = _this.checked;
    const companyCheckboxes = document.querySelectorAll('.company-checkbox-container input[type="checkbox"]');
    _this.nextElementSibling.textContent = isChecked ? "Unselect All Companies" : "Select All Companies";

    let all_company_ids = [];
    companyCheckboxes.forEach(checkbox => {
        checkbox.checked = isChecked;

        let companyId = checkbox.getAttribute('data-companyId');
        all_company_ids.push(companyId);
    });

    var xhr = new XMLHttpRequest();
    xhr.open('POST', app_root + '/admin_scripts/update_selection.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    document.getElementById('overlay').style.display = 'flex';
    activeRequests.push(xhr);
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            load_vessel_data();
        }
        removeRequest(xhr);
    };

    xhr.onerror = function() {
        hideSpinnerWithDelay();
    };

    xhr.send(`company_batch_update=${JSON.stringify(all_company_ids)}&is_displayed=${isChecked ? 1 : 0}`);
}

// Function to update company selection in the database via user preference
function updateCompanySelection(companyId, isChecked) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', app_root + '/admin_scripts/update_selection.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            load_vessel_data();
        }
    };

    // Send company ID and new checked status (1 or 0)
    xhr.send("company_id=" + companyId + "&is_displayed=" + (isChecked ? 1 : 0));
}

// Call the function on page load
document.addEventListener('DOMContentLoaded', checkSelectAllOnLoad);


var is_nothing_open = true; // determines if any extra tabs are open, preventing optionsOpen() from working
function optionsClose(keepCloseButton) {

    hide_route_imo_search_box()
    hide_vessel_imo_search_box()
    hide_port_search_box()

    closeRightBox()
    clear_colours()
    
    polygon_add_incident_type_close();

    // route_edit_clearRoute()
    if (route_add_box_position == 2) {
        document.getElementById("route_add_box").style.left = "-1000px"; 
        route_add_box_position = 1;

        map.setLayoutProperty('route_line', 'visibility', 'none');
    }

    // route_edit_clearRoute()
    if (route_edit_box_position == 2) {
        document.getElementById("route_edit_box").style.left = "-1000px"; 
        route_edit_box_position = 1;

        map.setLayoutProperty('route_line', 'visibility', 'none');
    }


    if (company_create_box_position == 2) {
        document.getElementById("company_create_box").style.left = "-1000px";
        company_create_box_position = 1;
    }

    if (company_edit_box_position == 2) {
        document.getElementById("company_edit_box").style.left = "-1000px";
        company_edit_box_position = 1;
    }

    if (vessel_create_box_position == 2) {
        document.getElementById("vessel_create_box").style.left = "-1000px";
        vessel_create_box_position = 1;
    }

    if (vessel_edit_box_position == 2) {
        document.getElementById("vessel_edit_box").style.left = "-1000px"; 
        vessel_edit_box_position = 1;
    }

    if (log_action_box_position == 2) {
        document.getElementById("log_action_box").style.left = "-1000px"; 
        log_action_box_position = 1;

    }


    fullMenuBox.style.left = "-300px";
    if (!keepCloseButton) {
        closeMenuBox.style.display = "none";
    }
    
    close_add_port();
    close_edit_port();
    close_port_risk_analysis_box();

    close_polygon_menu();

    is_nothing_open = true;

    // move filter button back to the left for visibility
}


function reset_zoom() {
    map.flyTo({center: [20,35], zoom:1});
}


//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////


function openRightBox() {
    page_box.style.right = "0px"; 
}

function closeRightBox() {
    page_box.style.right = "-200vw"; 
}



function clear_pages() {

    hide_route_imo_search_box()
    hide_vessel_imo_search_box()
    hide_port_search_box()

    document.getElementById("company_menu_tab").style.display = "none";
    document.getElementById("tab_1").style.display = "none";
    document.getElementById("tab_2").style.display = "none";
    document.getElementById("tab_3").style.display = "none";
    document.getElementById("tab_4").style.display = "none";
    document.getElementById("tab_5").style.display = "none";
    document.getElementById("tab_6").style.display = "none";

}

function clear_colours() {

    if (document.getElementById("company_menu_button")) {
        document.getElementById("company_menu_button").style.backgroundColor = "#2A3C46";
    }

    if (window.permissions[0] !== "0") {
        document.getElementById("tab_1_button").style.backgroundColor = "#2A3C46";
        document.getElementById("tab_1_button").classList.add('gray_colour_onhover');
    }

    if (window.permissions[1] !== "0") {
        document.getElementById("tab_2_button").style.backgroundColor = "#2A3C46";
        document.getElementById("tab_2_button").classList.add('gray_colour_onhover');
    }

    if (window.permissions[2] !== "0") {
        document.getElementById("tab_3_button").style.backgroundColor = "#2A3C46";
        document.getElementById("tab_3_button").classList.add('gray_colour_onhover');
    }

    document.getElementById("tab_4_button").style.backgroundColor = "#2A3C46";
    document.getElementById("tab_5_button").style.backgroundColor = "#2A3C46";
    

    if (document.getElementById("company_menu_button")) {
        document.getElementById("company_menu_button").classList.add('gray_colour_onhover');
    }
    if (document.getElementById("tab_6_button")) {
        document.getElementById("tab_6_button").classList.add('gray_colour_onhover');
    }
    if (document.getElementById("tab_7_button")) {
        document.getElementById("tab_7_button").classList.add('gray_colour_onhover');
    }
    document.getElementById("tab_4_button").classList.add('gray_colour_onhover');
    document.getElementById("tab_5_button").classList.add('gray_colour_onhover');
}
clear_colours()

function openCompanies() {
    openRightBox();
    clear_pages();
    clear_colours();

    show_vessel_imo_search_box();

    document.getElementById("company_menu_tab").style.display = "block";
    if (document.getElementById("company_menu_button")) {
        document.getElementById("company_menu_button").style.backgroundColor = "#223139";
        document.getElementById("company_menu_button").classList.remove('gray_colour_onhover');
    }
}

function openVessels() {

    openRightBox()
    clear_pages()
    clear_colours()

    show_vessel_imo_search_box()

    document.getElementById("individual_vessel_wrapper").style.display = "none";
    document.getElementById("tab_1").style.display = "block";
    document.getElementById("tab_1_button").style.backgroundColor = "#223139";
    document.getElementById("tab_1_button").classList.remove('gray_colour_onhover');
}

function openRoutes() {

    reload_route_imo_selector()

    openRightBox()
    clear_pages()
    clear_colours()

    show_route_imo_search_box()

    document.getElementById("tab_2").style.display = "block";
    document.getElementById("tab_2_button").style.backgroundColor = "#223139";
    document.getElementById("tab_2_button").classList.remove('gray_colour_onhover');
}


function show_port_search_box() {
    document.getElementById("geocoder").style.display = "none";
    document.getElementById("port_search_box").style.display = "block";
}

function hide_port_search_box() {
    document.getElementById("port_search_box").style.display = "none";
    document.getElementById("geocoder").style.display = "block";
}


function show_vessel_imo_search_box() {
    document.getElementById("geocoder").style.display = "none";
    document.getElementById("vessel_imo_search_box").style.display = "block";
}

function hide_vessel_imo_search_box() {
    document.getElementById("vessel_imo_search_box").style.display = "none";
    document.getElementById("geocoder").style.display = "block";
}


function show_route_imo_search_box() {
    document.getElementById("geocoder").style.display = "none";
    document.getElementById("route_imo_search_box").style.display = "block";
}

function hide_route_imo_search_box() {
    document.getElementById("route_imo_search_box").style.display = "none";
    document.getElementById("geocoder").style.display = "block";
}



function reload_route_imo_selector() {

    var route_selected_index = document.getElementById("route_imo_dropdown").selectedIndex
    // console.log(route_selected_index)

    document.getElementById("route_imo_dropdown").length = "";

    var route_option = document.createElement('option'); // sets first option to "All Vessels"
    route_option.value = "All Vessels";
    route_option.innerHTML = "All Vessels";

    document.getElementById("route_imo_dropdown").appendChild(route_option)

    var imo_array_length = imo_array.length - 1;
    for (let x = 0; x <= imo_array_length; x++) {

        var route_option = document.createElement('option');
        route_option.value = imo_array[x];
        route_option.innerHTML = imo_array[x];

        document.getElementById("route_imo_dropdown").appendChild(route_option)

    }

    document.getElementById("route_imo_dropdown").selectedIndex = route_selected_index
}

function openDangerZones() {

    openRightBox()
    clear_pages()
    clear_colours()
    document.getElementById("tab_3").style.display = "block";
    document.getElementById("tab_3_button").style.backgroundColor = "#223139";
    document.getElementById("tab_3_button").classList.remove('gray_colour_onhover');
}

function openPorts() {

    openRightBox()
    clear_pages()
    clear_colours()

    show_port_search_box()

    document.getElementById("tab_4").style.display = "block";
    document.getElementById("tab_4_button").style.backgroundColor = "#223139";
    document.getElementById("tab_4_button").classList.remove('gray_colour_onhover');
}

function openUser() {

    openRightBox()
    clear_pages()
    clear_colours()

    show_port_search_box()

    document.getElementById("tab_8").style.display = "block";
    document.getElementById("tab_5_button").style.backgroundColor = "#223139";
    document.getElementById("tab_5_button").classList.remove('gray_colour_onhover');
}

function openMapOptions() {

    openRightBox()
    clear_pages()
    clear_colours()
    document.getElementById("tab_5").style.display = "block";
    document.getElementById("tab_5_button").style.backgroundColor = "#223139";
    document.getElementById("tab_5_button").classList.remove('gray_colour_onhover');
}

function openLogs() {

    openRightBox()
    clear_pages()
    clear_colours()
    document.getElementById("tab_6").style.display = "block";
}

function vesselShortcut() {

    hide_route_imo_search_box()
    hide_port_search_box()

    is_nothing_open = true;
    //console.log("is_nothing_open = true")
    optionsClose()
    optionsOpen()
    openVessels()
}

/* **** Company creation and editing by Chris **** */
function submitNewCompany(event) {
    event.preventDefault();
    var formData = {};
    var form = event.target;

    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];

        if (element.tagName === "INPUT" || element.tagName === "SELECT" || element.tagName === "TEXTAREA") {
            if (element.name === "emails[]" || element.name === "email_alerts[]" || element.name === "invoice_emails[]" || element.name === "invoice_email_alerts[]" || element.name === "phones[]") {
                continue;
            }
            else if (element.type === "checkbox") {
                if (element.name.slice(-2) === "[]") {
                    var arrayName = element.name.replace(/\[\]$/, "");
                    if (!formData[arrayName]) {
                        formData[arrayName] = [];
                    }
                    formData[arrayName].push(element.checked);
                }
                else {
                    formData[element.name] = element.checked;
                }
            }
            else {
                formData[element.name] = element.value;
            }
        }
    }

    // Store email address objects from form
    var emails = [];
    if ("emails[]" in event.target.elements) {
        if (typeof event.target.elements["emails[]"].length === "number") {
            for (let i = 0; i < event.target.elements["emails[]"].length; i++) {
                if (event.target.elements["emails[]"][i].value.length > 0) {
                    let item = {};
                    item.address = event.target.elements["emails[]"][i].value;
                    item.alerts = event.target.elements["email_alerts[]"][i].checked;
                    emails.push(item);
                }
            }
        } else if (event.target.elements["emails[]"] instanceof Element && event.target.elements["emails[]"].tagName === "INPUT" && event.target.elements["emails[]"].value.length > 0) {
            let item = {};
            item.address = event.target.elements["emails[]"].value;
            item.alerts = event.target.elements["email_alerts[]"].checked;
            emails.push(item);
        }
    }
    formData["emails"] = emails;

    // Store invoice email address objects from form
    var invoice_emails = [];
    if ("invoice_emails[]" in event.target.elements) {
        if (typeof event.target.elements["invoice_emails[]"].length === "number") {
            for (let i = 0; i < event.target.elements["invoice_emails[]"].length; i++) {
                if (event.target.elements["invoice_emails[]"][i].value.length > 0) {
                    let item = {};
                    item.address = event.target.elements["invoice_emails[]"][i].value;
                    item.alerts = event.target.elements["invoice_email_alerts[]"][i].checked;
                    invoice_emails.push(item);
                }
            }
        } else if (event.target.elements["invoice_emails[]"] instanceof Element && event.target.elements["invoice_emails[]"].tagName === "INPUT" && event.target.elements["invoice_emails[]"].value.length > 0) {
            let item = {};
            item.address = event.target.elements["invoice_emails[]"].value;
            item.alerts = event.target.elements["invoice_email_alerts[]"].checked;
            invoice_emails.push(item);
        }
    }
    formData["invoice_emails"] = invoice_emails;

    // Store phone numbers from form
    var phones = [];
    if ("phones[]" in event.target.elements) {
        if (typeof event.target.elements["phones[]"].length === "number") {
            for (let i = 0; i < event.target.elements["phones[]"].length; i++) {
                if (event.target.elements["phones[]"][i].value.length > 0) {
                    let item = {number: event.target.elements["phones[]"][i].value};
                    phones.push(item);
                }
            }
        } else if (event.target.elements["phones[]"] instanceof Element && event.target.elements["phones[]"].tagName === "INPUT" && event.target.elements["phones[]"].value.length > 0) {
            let item = {number: event.target.elements["phones[]"].value};
            phones.push(item);
        }
    }
    formData["phones"] = phones;

    // AJAX request
    var create_request = new XMLHttpRequest();
    create_request.open('POST', '' + app_root + '/admin_scripts/create_company.php', true);
    create_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    var outputElement = document.getElementById("newCompanyOutput");
    outputElement.innerText = "";
    create_request.onreadystatechange = function() {
        if (create_request.readyState === 4) {
            if (create_request.status === 200) {
                // Handle response
                var responseData = this.responseText;
                // alert(create_request.responseText);
                console.log(responseData);
                refresh_companies_table();
                refresh_users_table();
                // toggleAddCompany();
                optionsClose();
                optionsOpen();
                openCompanies();
                // location.reload();

            }
            else {
                console.error('Error:', create_request.status);
            }
        }
    };

    create_request.send(JSON.stringify(formData));
}

function submitEditCompany(event) {
    event.preventDefault();
    var formData = {};
    var form = event.target;

    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];

        if (element.name === "emails[]" || element.name === "email_alerts[]" || element.name === "invoice_emails[]" || element.name === "invoice_email_alerts[]" || element.name === "phones[]") {
            continue;
        }
        else if (element.tagName === "INPUT" || element.tagName === "SELECT" || element.tagName === "TEXTAREA") {
            if (element.type === "checkbox") {
                if (element.name.slice(-2) === "[]") {
                    var arrayName = element.name.replace(/\[\]$/, "");
                    if (!formData[arrayName]) {
                        formData[arrayName] = [];
                    }
                    formData[arrayName].push(element.checked);
                }
                else {
                    formData[element.name] = element.checked;
                }
            }
            else {
                formData[element.name] = element.value;
            }
        }
    }
    
    // Store email address objects from form
    var emails = [];
    if ("emails[]" in event.target.elements) {
        if (typeof event.target.elements["emails[]"].length === "number") {
            for (let i = 0; i < event.target.elements["emails[]"].length; i++) {
                if (event.target.elements["emails[]"][i].value.length > 0) {
                    let item = {};
                    item.address = event.target.elements["emails[]"][i].value;
                    item.alerts = event.target.elements["email_alerts[]"][i].checked;
                    emails.push(item);
                }
            }
        } else if (event.target.elements["emails[]"] instanceof Element && event.target.elements["emails[]"].tagName === "INPUT" && event.target.elements["emails[]"].value.length > 0) {
            let item = {};
            item.address = event.target.elements["emails[]"].value;
            item.alerts = event.target.elements["email_alerts[]"].checked;
            emails.push(item);
        }
    }
    formData["emails"] = emails;

    // Store invoice email address objects from form
    var invoice_emails = [];
    if ("invoice_emails[]" in event.target.elements) {
        if (typeof event.target.elements["invoice_emails[]"].length === "number") {
            for (let i = 0; i < event.target.elements["invoice_emails[]"].length; i++) {
                if (event.target.elements["invoice_emails[]"][i].value.length > 0) {
                    let item = {};
                    item.address = event.target.elements["invoice_emails[]"][i].value;
                    item.alerts = event.target.elements["invoice_email_alerts[]"][i].checked;
                    invoice_emails.push(item);
                }
            }
        } else if (event.target.elements["invoice_emails[]"] instanceof Element && event.target.elements["invoice_emails[]"].tagName === "INPUT" && event.target.elements["invoice_emails[]"].value.length > 0) {
            let item = {};
            item.address = event.target.elements["invoice_emails[]"].value;
            item.alerts = event.target.elements["invoice_email_alerts[]"].checked;
            invoice_emails.push(item);
        }
    }
    formData["invoice_emails"] = invoice_emails;

    // Store phone numbers from form
    var phones = [];
    if ("phones[]" in event.target.elements) {
        if (typeof event.target.elements["phones[]"].length === "number") {
            for (let i = 0; i < event.target.elements["phones[]"].length; i++) {
                if (event.target.elements["phones[]"][i].value.length > 0) {
                    let item = {number: event.target.elements["phones[]"][i].value};
                    phones.push(item);
                }
            }
        } else if (event.target.elements["phones[]"] instanceof Element && event.target.elements["phones[]"].tagName === "INPUT" && event.target.elements["phones[]"].value.length > 0) {
            let item = {number: event.target.elements["phones[]"].value};
            phones.push(item);
        }
    }
    formData["phones"] = phones;

    // AJAX request
    var create_request = new XMLHttpRequest();
    create_request.open('POST', '' + app_root + '/admin_scripts/edit_company_push.php', true);
    create_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    var outputElement = document.getElementById("editCompanyOutput");
    outputElement.innerText = "";
    create_request.onreadystatechange = function() {
        if (create_request.readyState === 4) {
            if (create_request.status === 200) {
                // Handle response
                var responseData = create_request.responseText;
                outputElement.innerText = responseData;
                alert(create_request.responseText);
                // alert(responseData);
                refresh_companies_table();
                refresh_users_table();
                // toggleEditCompany();
                optionsClose();
                optionsOpen();
                openCompanies();
                // location.reload();
            }
            else {
                outputElement.innerText = 'Error:', create_request.status;
            }
        }
    };

    create_request.send(JSON.stringify(formData));
}

function openAddCompany() {
    // Clear form values for new user
    for (var i = 0; i < newCompanyForm.elements.length; i++) {
        var formElement = newCompanyForm.elements[i];
        if (formElement.tagName === "INPUT") {
            if (formElement.type === "checkbox") {
                formElement.checked = false;
            }
            else {
                formElement.value = "";
            }
        }
        else if (formElement.tagName === "SELECT") {
            formElement.selectedIndex = 1;
        }
    }

    // One email field
    clearContactList("new_company_email_list");
    addEmailItem("new_company_email_list", "", true, "");
    clearContactList("new_company_invoice_email_list");
    addEmailItem("new_company_invoice_email_list", "", true, "invoice_");
    clearContactList("new_company_phone_list");
    addPhoneItem("new_company_phone_list", "", true);
    
    // companiesTable.style.display = 'none';
    // newCompanyForm.style.display = 'block'
    // addCompanyButton.innerText = "Cancel";
    // addCompanyButton.classList.remove("add_line_button");
    // addCompanyButton.style.display = 'none';
    // companyHeaderContent.style.display = 'none';
    // companyReturnButton.style.display = 'inline-block';
    // companyReturnButton.setAttribute("onclick", "closeAddCompany()");
    
    // addingCompany = true;
    
    document.getElementById("newCompanyOutput").innerText = "";

    optionsClose(1);
    document.getElementById("company_create_box").style.left = "10px"; 
    company_create_box_position = 2;

}

function closeAddCompany() {
    // companiesTable.style.display = 'table';
    // newCompanyForm.style.display = 'none';
    // addCompanyButton.innerText = "Add Company";
    // addCompanyButton.classList.add("add_line_button");
    // companyReturnButton.style.display = 'none';
    // companyReturnButton.setAttribute("onclick", "");
    // companyHeaderContent.style.display = 'inline-block';
    // addCompanyButton.style.display = 'inline-block'
    // addingCompany = false;
    document.getElementById("company_create_box").style.left = "-1000px"; 
    company_create_box_position = 1;
}

var addingCompany = false, editingCompany = false;
var addingUser = false, editingUser = false;

function toggleAddCompany() {
    if (!addingCompany) {
        openAddCompany();
    }
    else {
        closeAddCompany();
    }
    // editCompanyForm.style.display = 'none';
}

function openEditCompany() {
        // companiesTable.style.display = 'none';
        // editCompanyForm.style.display = 'block';

        // addCompanyButton.style.display = 'none';
        // companyHeaderContent.style.display = 'none';
        // companyReturnButton.style.display = 'inline-block';
        // companyReturnButton.setAttribute("onclick", "closeEditCompany()");

        // editingCompany = true;
}

function closeEditCompany() {
        // companiesTable.style.display = 'table';
        // editCompanyForm.style.display = 'none'

        // companyReturnButton.style.display = 'none';
        // companyReturnButton.setAttribute("onclick", "");
        // companyHeaderContent.style.display = 'inline-block';
        // addCompanyButton.style.display = 'inline-block';

        // editingCompany = false;
}

function toggleEditCompany() {
    if (!editingCompany) {
        openEditCompany();
    }
    else {
        closeEditCompany();
    }
    newCompanyForm.style.display = 'none';
}

function refresh_companies_table() {
    var table = document.getElementById("companiesTable");
    table.children[1].innerHTML = "";
    table_retrieve_lines(table, ["id", "company_name", "vessel_count"], "companies_request.php")
}

// if (window.privilege == '0') {
if (document.getElementById("company_menu_button")) {
    refresh_companies_table();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////


route_edit_box_position = 1;
function route_edit_open(route_number) {

    route_manager_getDataFromNumber(route_number)

    document.getElementById("route_edit_imo_title").innerText = route_selected_imo // sets route title to the name

    document.getElementById("route_edit_start_date_input").value = route_selected_start_date;
    document.getElementById("route_edit_arrival_date_input").value = route_selected_arrival_date;
    document.getElementById("route_edit_name_input").value = route_selected_name;
    document.getElementById("route_edit_start_input").value = route_selected_start;
    document.getElementById("route_edit_destination_input").value = route_selected_destination;
    document.getElementById("route_edit_risk_area_sel").value = route_selected_tra;

    if (route_selected_transit_risk_rating == 1) {
        change_low_edit()
    }

    else if (route_selected_transit_risk_rating == 2) {
        change_moderate_edit()
    }

    else if (route_selected_transit_risk_rating == 3) {
        change_substantial_edit()
    }

    else if (route_selected_transit_risk_rating == 4) {
        change_high_edit()
    }

    else if (route_selected_transit_risk_rating == 5) {
        change_extreme_edit()
    }

    else {
        console.log("Radio Value Error")
    }
    document.getElementById("radio_" + route_selected_transit_risk_rating + "_edit").checked = true;

    const startSearchBox = document.getElementById("route_edit_start_input");
    if (route_selected_port_id_start !== "" && route_selected_port_id_start !== null) {
        document.getElementById("route_edit_port_id_start").value = route_selected_port_id_start;
        startSearchBox.readOnly = true;
        startSearchBox.disabled = true;
        document.getElementById("cross-btn-start-edit").style.display = "inline";
    } else {
        document.getElementById("route_edit_port_id_start").value = "";
        startSearchBox.readOnly = false;
        startSearchBox.disabled = false;
        document.getElementById("cross-btn-start-edit").style.display = "none";
    }
    startSearchBox.style.borderColor = "black";
    document.getElementById("suggestions-start-edit").style.display = "none";

    const destinationSearchBox = document.getElementById("route_edit_destination_input");
    if (route_selected_port_id_destination !== "" && route_selected_port_id_start !== null) {
        document.getElementById("route_edit_port_id_destination").value = route_selected_port_id_destination;
        destinationSearchBox.readOnly = true;
        destinationSearchBox.disabled = true;
        document.getElementById("cross-btn-destination-edit").style.display = "inline";
    } else {
        document.getElementById("route_edit_port_id_destination").value = "";
        destinationSearchBox.readOnly = false;
        destinationSearchBox.disabled = false;
        document.getElementById("cross-btn-destination-edit").style.display = "none";
    }
    destinationSearchBox.style.borderColor = "black";
    document.getElementById("suggestions-destination-edit").style.display = "none";


    document.getElementById("route_edit_box").style.left = "10px"; 
    route_edit_box_position = 2;

    route_edit_retrieveCoordsByNumber(route_number)

    map.setLayoutProperty('route_line', 'visibility', 'visible');


}


function route_edit_retrieveCoordsByNumber(route_number) {

    console.log("route_edit_retrieveCoordsByNumber")

    console.log(route_number)

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + '&route_number=' + route_number
    ajax_request.open('POST', '' + app_root + '/routes/route_edit_request.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);
            var retrieved_coords_edit = this.responseText;
            
            route_edit_loadRouteByCoords(retrieved_coords_edit);

        }
    }
    ajax_request.send(data_to_send);

}

function route_edit_loadRouteByCoords(retrieved_coords_edit) {

    var coord_bundle_array = retrieved_coords_edit.split(',;')

    var coord_bundle_array_length = coord_bundle_array.length / 2

    var route_edit_box_html = "";
    for (let x = 0; x < coord_bundle_array_length; x++) {

        var longitude = coord_bundle_array[(2*x + 0)]
        var latitude = coord_bundle_array[(2*x + 1)]

        route_edit_box_html = route_edit_box_html + longitude + "  " + latitude + "<br>"

    }

    document.getElementById("route_edit_textbox").innerHTML = route_edit_box_html;

    route_edit_update_visual()


}



function route_edit_update_route() {

    route_edit_getCoordData()

    route_manager_getDataFromNumber(global_route_number_clicked) // sets route_selected_imo from the number

    var imo_number_to_send = route_selected_imo

    console.log(imo_number_to_send)
    console.log(global_route_number_clicked)
    console.log(long_pass_route_edit)
    console.log(lat_pass_route_edit)

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'imo_number=' + imo_number_to_send
    + '&route_number=' + global_route_number_clicked
    + '&long_pass=' + long_pass_route_edit
    + '&lat_pass=' + lat_pass_route_edit
    ajax_request.open('POST', '' + app_root + '/routes/route_edit_send.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            // there is no response, only data sent and inputted

        }
    }
    ajax_request.send(data_to_send);
}


function route_edit_save_clicked() {

    console.log("route_edit_save_clicked()");

    // const sel = document.getElementById("route_edit_risk_area_sel");
    // if (sel.value === "") {
    //     sel.style.borderColor = "red";
    //     return;
    // } else {
    //     sel.style.borderColor = "black";
    // }

    // Check for missing ports
    if (document.getElementById("route_edit_port_id_start").value == "") {
        document.getElementById("route_edit_start_input").style.borderColor = "red";
        return 1;
    }
    if (document.getElementById("route_edit_port_id_destination").value == "") {
        document.getElementById("route_edit_destination_input").style.borderColor = "red";
        return 1;
    }


    route_edit_update_data();
    route_edit_update_route();



    // reloads route tab lines
    route_manager_clear_lines()
    route_manager_retrieve_lines()

    alert("Route Saved")

    openRoutes();

    // closes edit route tab
    map.setLayoutProperty('route_line', 'visibility', 'none');
    document.getElementById("route_edit_box").style.left = "-1000px"; 
    route_edit_box_position = 1;

    fullMenuBox.style.left = "10px";
    closeMenuBox.style.display = "block";


}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////// Route Start ///////////////////////////////////////////////////////////////////////////////////////////////


var global_route_manager_data = ""; // this will be used to gather and update the data, for use in other functions such as the search function
function route_manager_retrieve_lines() {

    //console.log("route_manager_retrieve_lines()");

    route_manager_clear_lines()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'imo_number=' + document.getElementById("route_imo_dropdown").value;
    ajax_request.open('POST', '' + app_root + '/routes/route_manager_request.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);

            global_route_manager_data = this.responseText;

            if (global_route_manager_data === "") {
                // do nothing if data returned is <empty string>
                // alert(document.getElementById("route_imo_dropdown").value)
            }

            else {
                route_manager_load_lines("");
            }
        
            // console.log("route ajax request returned")
        }
    
    }
    ajax_request.send(data_to_send);

    // console.log("route refresh function ended")
}


function route_manager_clear_lines() {

    //console.log("route_manager_clear_lines()");

    for (let x = 0; x <= route_total_lines; x++) {

        if (document.getElementById("route_line_" + x) !== null) {
                
            var line_to_delete = document.getElementById("route_line_" + x)
            line_to_delete.remove()

        }

    }

    route_total_lines = 0;

}


function route_manager_load_lines(imo_search_text) {

    // imo_search_text passed through, represents imo text to filter by
    var imo_text_chars = imo_search_text.length


    var route_manager_array = global_route_manager_data.split(',;')
    // console.log(route_manager_array)

    var route_lines_to_load = route_manager_array.length / 8;

    for (let x = 0; x < route_lines_to_load; x++) {

        var route_number = route_manager_array[8*x + 0]
        var route_imo = route_manager_array[8*x + 1]
        var route_start_date = route_manager_array[8*x + 2]
        var route_arrival_date = route_manager_array[8*x + 3]
        var route_name = route_manager_array[8*x + 4]
        var route_start = route_manager_array[8*x + 5]
        var route_destination = route_manager_array[8*x + 6]
        var route_vessel_name = route_manager_array[8*x + 7]

        // console.log(route_number)
        // console.log(route_imo)
        // console.log(route_start_date)
        // console.log(route_arrival_date)
        // console.log(route_name)
        // console.log(route_start)
        // console.log(route_destination)
        // console.log(route_vessel_name)
        // console.log(" ")

        if (route_imo.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase()) {

            route_manager_insert_line(route_number);

            var route_text_imo = document.getElementById("route_text_imo_" + route_total_lines)
            route_text_imo.innerText = route_imo;

            var route_text_vessel_name = document.getElementById("route_text_vessel_name_" + route_total_lines)
            route_text_vessel_name.innerText = route_vessel_name;

            var route_text_start_date = document.getElementById("route_text_start_date_" + route_total_lines)
            var route_start_date_split = route_start_date.split("-");
            var route_start_date_formatted = route_start_date_split[2] + "/" + route_start_date_split[1] + "/" + route_start_date_split[0]
            route_text_start_date.innerText = route_start_date_formatted;

            var route_text_arrival_date = document.getElementById("route_text_arrival_date_" + route_total_lines)
            var route_arrival_date_split = route_arrival_date.split("-");
            var route_arrival_date_formatted = route_arrival_date_split[2] + "/" + route_arrival_date_split[1] + "/" + route_arrival_date_split[0]
            route_text_arrival_date.innerText = route_arrival_date_formatted;

            var route_text_name = document.getElementById("route_text_name_" + route_total_lines)
            route_text_name.innerText = route_name;

            var route_text_start = document.getElementById("route_text_start_" + route_total_lines)
            route_text_start.innerText = route_start;

            var route_text_destination = document.getElementById("route_text_destination_" + route_total_lines)
            route_text_destination.innerText = route_destination;

        }

        else if (route_vessel_name.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase()) {

            route_manager_insert_line(route_number);

            var route_text_imo = document.getElementById("route_text_imo_" + route_total_lines)
            route_text_imo.innerText = route_imo;

            var route_text_vessel_name = document.getElementById("route_text_vessel_name_" + route_total_lines)
            route_text_vessel_name.innerText = route_vessel_name;

            var route_text_start_date = document.getElementById("route_text_start_date_" + route_total_lines)
            route_text_start_date.innerText = route_start_date;

            var route_text_arrival_date = document.getElementById("route_text_arrival_date_" + route_total_lines)
            route_text_arrival_date.innerText = route_arrival_date;

            var route_text_name = document.getElementById("route_text_name_" + route_total_lines)
            route_text_name.innerText = route_name;

            var route_text_start = document.getElementById("route_text_start_" + route_total_lines)
            route_text_start.innerText = route_start;

            var route_text_destination = document.getElementById("route_text_destination_" + route_total_lines)
            route_text_destination.innerText = route_destination;

        }

        else if (route_start_date.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase()) {

            route_manager_insert_line(route_number);

            var route_text_imo = document.getElementById("route_text_imo_" + route_total_lines)
            route_text_imo.innerText = route_imo;

            var route_text_vessel_name = document.getElementById("route_text_vessel_name_" + route_total_lines)
            route_text_vessel_name.innerText = route_vessel_name;

            var route_text_start_date = document.getElementById("route_text_start_date_" + route_total_lines)
            route_text_start_date.innerText = route_start_date;

            var route_text_arrival_date = document.getElementById("route_text_arrival_date_" + route_total_lines)
            route_text_arrival_date.innerText = route_arrival_date;

            var route_text_name = document.getElementById("route_text_name_" + route_total_lines)
            route_text_name.innerText = route_name;

            var route_text_start = document.getElementById("route_text_start_" + route_total_lines)
            route_text_start.innerText = route_start;

            var route_text_destination = document.getElementById("route_text_destination_" + route_total_lines)
            route_text_destination.innerText = route_destination;

        }

        else if (route_name.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase()) {

            route_manager_insert_line(route_number);

            var route_text_imo = document.getElementById("route_text_imo_" + route_total_lines)
            route_text_imo.innerText = route_imo;

            var route_text_vessel_name = document.getElementById("route_text_vessel_name_" + route_total_lines)
            route_text_vessel_name.innerText = route_vessel_name;

            var route_text_start_date = document.getElementById("route_text_start_date_" + route_total_lines)
            route_text_start_date.innerText = route_start_date;

            var route_text_arrival_date = document.getElementById("route_text_arrival_date_" + route_total_lines)
            route_text_arrival_date.innerText = route_arrival_date;

            var route_text_name = document.getElementById("route_text_name_" + route_total_lines)
            route_text_name.innerText = route_name;

            var route_text_start = document.getElementById("route_text_start_" + route_total_lines)
            route_text_start.innerText = route_start;

            var route_text_destination = document.getElementById("route_text_destination_" + route_total_lines)
            route_text_destination.innerText = route_destination;

        }

        else {
            // do nothing
        }
    }
}


var route_total_lines = 0;
function route_manager_insert_line(route_number) {

    //console.log("route_manager_insert_line()");

    route_total_lines++

    var route_line = document.createElement("div");
        route_line.setAttribute("class", "application_table_line");
        route_line.setAttribute("id", "route_line_" + route_total_lines);
        document.getElementById("route_table_body_id").appendChild(route_line);



    var route_cell_imo = document.createElement("div");
        route_cell_imo.setAttribute("class", "route_table_cell");
        route_cell_imo.setAttribute("id", "route_cell_imo_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_imo)

    var route_text_imo = document.createElement("p");
        route_text_imo.setAttribute("class", "application_cell_text");
        route_text_imo.setAttribute("id", "route_text_imo_" + route_total_lines);
        route_text_imo.innerText = "";
        document.getElementById("route_cell_imo_" + route_total_lines).appendChild(route_text_imo) 



    var route_cell_vessel_name = document.createElement("div");
        route_cell_vessel_name.setAttribute("class", "route_table_cell");
        route_cell_vessel_name.setAttribute("id", "route_cell_vessel_name_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_vessel_name)

    var route_text_vessel_name = document.createElement("p");
        route_text_vessel_name.setAttribute("class", "application_cell_text");
        route_text_vessel_name.setAttribute("id", "route_text_vessel_name_" + route_total_lines);
        route_text_vessel_name.innerText = "";
        document.getElementById("route_cell_vessel_name_" + route_total_lines).appendChild(route_text_vessel_name) 



    var route_cell_start_date = document.createElement("div");
        route_cell_start_date.setAttribute("class", "route_table_cell");
        route_cell_start_date.setAttribute("id", "route_cell_start_date_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_start_date)

    var route_text_start_date = document.createElement("p");
        route_text_start_date.setAttribute("class", "application_cell_text");
        route_text_start_date.setAttribute("id", "route_text_start_date_" + route_total_lines);
        route_text_start_date.innerText = "";
        document.getElementById("route_cell_start_date_" + route_total_lines).appendChild(route_text_start_date)   



    var route_cell_arrival_date = document.createElement("div");
        route_cell_arrival_date.setAttribute("class", "route_table_cell");
        route_cell_arrival_date.setAttribute("id", "route_cell_arrival_date_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_arrival_date)

    var route_text_arrival_date = document.createElement("p");
        route_text_arrival_date.setAttribute("class", "application_cell_text");
        route_text_arrival_date.setAttribute("id", "route_text_arrival_date_" + route_total_lines);
        route_text_arrival_date.innerText = "";
        document.getElementById("route_cell_arrival_date_" + route_total_lines).appendChild(route_text_arrival_date)   



    var route_cell_name = document.createElement("div");
        route_cell_name.setAttribute("class", "route_table_cell");
        route_cell_name.setAttribute("id", "route_cell_name_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_name)

    var route_text_name = document.createElement("p");
        route_text_name.setAttribute("class", "application_cell_text");
        route_text_name.setAttribute("id", "route_text_name_" + route_total_lines);
        route_text_name.innerText = "";
        document.getElementById("route_cell_name_" + route_total_lines).appendChild(route_text_name)  



    var route_cell_start = document.createElement("div");
        route_cell_start.setAttribute("class", "route_table_cell");
        route_cell_start.setAttribute("id", "route_cell_start_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_start)

    var route_text_start = document.createElement("p");
        route_text_start.setAttribute("class", "application_cell_text");
        route_text_start.setAttribute("id", "route_text_start_" + route_total_lines);
        route_text_start.innerText = "";
        document.getElementById("route_cell_start_" + route_total_lines).appendChild(route_text_start) 



    var route_cell_destination = document.createElement("div");
        route_cell_destination.setAttribute("class", "route_table_cell");
        route_cell_destination.setAttribute("id", "route_cell_destination_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_destination)

    var route_text_destination = document.createElement("p");
        route_text_destination.setAttribute("class", "application_cell_text");
        route_text_destination.setAttribute("id", "route_text_destination_" + route_total_lines);
        route_text_destination.innerText = "";
        document.getElementById("route_cell_destination_" + route_total_lines).appendChild(route_text_destination) 



    var route_cell_view = document.createElement("div");
        route_cell_view.setAttribute("class", "route_table_cell_button");
        route_cell_view.setAttribute("id", "route_cell_view_" + route_total_lines);
        document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_view)

    var route_picture_view = document.createElement("div");
        route_picture_view.setAttribute("class", "application_view_button");
        route_picture_view.setAttribute("id", "route_picture_view_" + route_total_lines);
        route_picture_view.setAttribute("data", route_number);
        route_picture_view.setAttribute("onclick", "route_manager_view_clicked(this.id)");
        document.getElementById("route_cell_view_" + route_total_lines).appendChild(route_picture_view) 

    if (resource_permissions.canEditRoutes) {
        var route_cell_edit = document.createElement("div");
            route_cell_edit.setAttribute("class", "route_table_cell_button");
            route_cell_edit.setAttribute("id", "route_cell_edit_" + route_total_lines);
            document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_edit)

        var route_picture_edit = document.createElement("div");
            route_picture_edit.setAttribute("class", "application_edit_button");
            route_picture_edit.setAttribute("id", "route_picture_edit_" + route_total_lines);
            route_picture_edit.setAttribute("data", route_number);
            route_picture_edit.setAttribute("onclick", "route_manager_edit_clicked(this.id)");
            document.getElementById("route_cell_edit_" + route_total_lines).appendChild(route_picture_edit)
    }

    if (resource_permissions.canDeleteRoutes) {
        var route_cell_delete = document.createElement("div");
            route_cell_delete.setAttribute("class", "route_table_cell_button");
            route_cell_delete.setAttribute("id", "route_cell_delete_" + route_total_lines);
            document.getElementById("route_line_" + route_total_lines).appendChild(route_cell_delete)

        var route_picture_delete = document.createElement("div");
            route_picture_delete.setAttribute("class", "application_delete_button");
            route_picture_delete.setAttribute("id", "route_picture_delete_" + route_total_lines);
            route_picture_delete.setAttribute("data", route_number);
            route_picture_delete.setAttribute("onclick", "route_manager_delete_line(this.id)");
            document.getElementById("route_cell_delete_" + route_total_lines).appendChild(route_picture_delete)
    }

}


function route_manager_colour_lines() {

    //console.log("route_manager_colour_lines()");
    

    var route_array = [];
    for (let x = 0; x <= route_total_lines; x++) {

        if (document.getElementById("route_line_" + x) !== null) {
            
            route_array.push(x)

        }

    }

    var route_array_length = route_array.length - 1;
    for (let x = 0; x <= route_array_length; x++) {

        var route_array_value = route_array[x];

        if (x % 2 == 0) {
            //console.log(x + " is even")
            document.getElementById("route_line_" + route_array_value).style.backgroundColor = "white";
        }

        else if (x % 2 == 1) {
            //console.log(x + " is odd")
            document.getElementById("route_line_" + route_array_value).style.backgroundColor = "#2A3C46";
        }

    }

}

// function sendNewQuestionnaire(listElement, email, route_number) {
function sendNewQuestionnaire(event) {
    event.preventDefault();

    const listElement = document.getElementById("route_questionnaires_list");
    const email = event.target.elements["email"].value;
    const route_number = global_route_number_clicked;

    const qSendRequest = new XMLHttpRequest();
    qSendRequest.open('POST', '' + app_root + '/routes/send_new_questionnaire.php', true);
    qSendRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    qSendRequest.onreadystatechange = function() {
        if (qSendRequest.readyState === 4) {
            if (qSendRequest.status === 200) {
                alert(this.responseText);
                if (qSendRequest.responseText != "1") {
    
                } else {
                    alert("Failed to send questionnaire");
                }
            }
        }
    }

    qSendRequest.send(`email=${email}&questionnaire_id=1&route_number=${route_number}`);

    updateQuestionnaires(listElement, route_number);
}

document.getElementById("new_questionnaire_form").addEventListener("submit", sendNewQuestionnaire);

function addQuestionnaireResult(listElement, token, timestamp, email, completed, score, scoring) {
    let response = document.createElement("tr");
    response.classList.add("questionnaire_result_item");

    let timestampField = document.createElement("td");
    timestampField.innerText = timestamp;
    response.appendChild(timestampField);

    let emailField = document.createElement("td");
    let emailLink = document.createElement("a");
    emailLink.innerText = email;
    emailLink.href = `mailto:${email}`
    emailField.appendChild(emailLink);
    response.appendChild(emailField);

    let scoreField = document.createElement("td");
    let scoreLink = document.createElement("a");
    scoreField.appendChild(scoreLink);
    scoreField.classList.add("questionnaire_score_field");

    if (!completed) {
        scoreLink.innerText = "Not completed";
        scoreField.classList.add("uncompleted");
    }
    else {
        scoreLink.innerText = score;
        if (score >= scoring["low"]) {
            scoreField.classList.add("low");
        } else if (score >= scoring["medium"]) {
            scoreField.classList.add("medium");
        } else {
            scoreField.classList.add("high");
        }
        scoreLink.href = `/questionnaire_response.php?token=${token}`;
        scoreLink.target = "_blank";
    }

    response.appendChild(scoreField);
    listElement.appendChild(response);
}

function updateQuestionnaires(listElement, route_number) {
    listElement.innerHTML = "";

    const getQResponsesRequest = new XMLHttpRequest();
    getQResponsesRequest.open('POST', '' + app_root + '/routes/questionnaire_responses_get.php', true);
    getQResponsesRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    getQResponsesRequest.onreadystatechange = function() {
        if (getQResponsesRequest.readyState === 4) {
            if (getQResponsesRequest.status === 200) {
                if (getQResponsesRequest.responseText != "1") {
                    let existingQuestionnaires = JSON.parse(this.responseText);
                    let token, email, completed, score;
                    for (let i = 0; i < existingQuestionnaires.length; i++) {
                        token = existingQuestionnaires[i]["token"];
                        timestamp = existingQuestionnaires[i]["created_at"];
                        email = existingQuestionnaires[i]["email"];
                        completed = existingQuestionnaires[i]["completed"];
                        score = completed ? existingQuestionnaires[i]["score"] : null;
                        addQuestionnaireResult(listElement, token, timestamp, email, completed, score, questionnaireScoringThresholds);
                    }
                } else {
                    console.log("Failed to fetch existing questionnaires - maybe none exist.");
                }
            }
        }
    }

    getQResponsesRequest.send(`route_number=${route_number}`);
    // getQResponsesRequest.send(`email=${email},questionnaire_id=1,route_number=${route_number}`);

}

var global_route_number_clicked = "";
function route_manager_edit_clicked(passed_id) {

    var route_number = document.getElementById(passed_id).getAttribute("data")
    console.log(route_number)

    global_route_number_clicked = route_number

    var route_selected_index = "";
    for (let x = 1; x <= route_total_lines; x++) {
        if (document.getElementById("route_picture_edit_" + x) !== null) {

            var data_to_check = document.getElementById("route_picture_edit_" + x).getAttribute("data");
            if (data_to_check == route_number) {
                route_selected_index = (x-1)
            }

        }
    }
    console.log(route_selected_index)

    optionsClose(1)
    is_nothing_open = false;

    route_edit_open(route_number, route_selected_index)

    const responseList = document.getElementById("route_questionnaires_list");
    updateQuestionnaires(responseList, route_number);

    // addQuestionnaireResult(responseList, "3247905", "a@b.c", true, 64, questionnaireScoring);
    // addQuestionnaireResult(responseList, "4789235", "c@a.b", true, 149, questionnaireScoring);
    // addQuestionnaireResult(responseList, "4523655", "b@c.a", false);

}


function route_edit_name_clicked() {

    route_edit_open(route_number)
}


var route_selected_imo = "";
var route_selected_number = "";
var route_selected_start_date = "";
var route_selected_arrival_date = "";
var route_selected_name = "";
var route_selected_start = "";
var route_selected_destination = "";
var route_selected_transit_risk_rating = "";
var route_selected_port_id_start = "";
var route_selected_port_id_destination = "";
var route_selected_tra = "";

function route_manager_getDataFromNumber(route_number) {

    console.log("getDataFromNumber")
    console.log(route_number)
    //console.log("route_manager_getDataFromNumber()");

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + '&route_number=' + route_number
    ajax_request.open('POST', '' + app_root + '/routes/route_manager_getDataFromNumber.php', false);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
            var route_selected_array = this.responseText.split(',;');

            //console.log(route_number_clicked)
            console.log(route_selected_array);

            route_selected_imo = route_selected_array[0];
            route_selected_number = route_selected_array[1];
            route_selected_start_date = route_selected_array[2];
            route_selected_arrival_date = route_selected_array[3];
            route_selected_name = route_selected_array[4];
            route_selected_start = route_selected_array[5];
            route_selected_destination = route_selected_array[6];
            route_selected_transit_risk_rating = route_selected_array[7];
            route_selected_port_id_start = route_selected_array[8];
            route_selected_port_id_destination = route_selected_array[9];
            route_selected_tra = route_selected_array[10];

        }
    
    }
    ajax_request.send(data_to_send);

}


function route_manager_view_clicked(passed_id) {

    route_manager_edit_clicked(passed_id)

    document.getElementById("route_edit_box").style.left = "-1000px"; 
    
}

var imo_array = [];
function route_manager_get_imos() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/routes/route_manager_get_vessels.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {

            //console.log(this.responseText);
            var imo_response = this.responseText;
            imo_array = imo_response.split(',');

        }

    }
    ajax_request.send(data_to_send);
}
route_manager_get_imos()


function route_manager_delete_line(passed_id) {

  let text = "Do you really want to delete this Route? Press OK to confirm.";

  if (confirm(text) == true) {

    var route_number = document.getElementById(passed_id).getAttribute("data")
    route_manager_delete(route_number);

    var line_to_delete = document.getElementById(passed_id).parentElement.parentElement // gets line from delete button id, then removes it
    line_to_delete.remove()

    alert("Route Deleted")

  } 

  else {
    // do nothing else if cancelled
  }

}

function route_manager_delete(route_number) {

    // console.log(route_number);

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'route_number=' + route_number
    ajax_request.open('POST', '' + app_root + '/routes/route_manager_delete.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

        }
    
    }
    ajax_request.send(data_to_send);


}


function route_edit_update_data() {

    get_radio_value_edit()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'imo_number=' + route_selected_imo
    + '&route_number=' + global_route_number_clicked
    + '&route_start_date=' + document.getElementById("route_edit_start_date_input").value
    + '&route_arrival_date=' + document.getElementById("route_edit_arrival_date_input").value
    + '&route_name=' + document.getElementById("route_edit_name_input").value
    + '&route_start_port_id=' + document.getElementById("route_edit_port_id_start").value
    + '&route_start=' + document.getElementById("route_edit_start_input").value
    + '&route_destination_port_id=' + document.getElementById("route_edit_port_id_destination").value
    + '&route_destination=' + document.getElementById("route_edit_destination_input").value
    + '&transit_risk_rating=' + radio_value_edit
    + '&transit_risk_area=' + document.getElementById("route_edit_risk_area_sel").value
    ajax_request.open('POST', '' + app_root + '/routes/route_manager_edit_row.php', false);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log("############################################################################################################################");
            console.log(this.responseText);

        }
    
    }
    ajax_request.send(data_to_send);

}


//////////////////////////////////////////////////////////////////////////////////////////////////////


ports_enabled = 1
function toggle_ports() {

    if (ports_enabled == 1) {
        map.setLayoutProperty('path', 'visibility', 'visible');
        ports_enabled = 2;
    }

    else if (ports_enabled == 2) {
        map.setLayoutProperty('path', 'visibility', 'none');
        ports_enabled = 1;
    }

}



//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////

vessel_create_box_position = 1;
function vessel_create_open() {
    if (vessel_create_box_position == 1) {
        document.getElementById("vessel_create_box").style.left = "10px";
        vessel_create_box_position = 2;
    }
    else if (vessel_edit_box_position == 2) {
        document.getElementById("vessel_create_box").style.left = "-1000px";
        vessel_create_box_position = 1;
    }
}

company_create_box_position = 1;
company_edit_box_position = 1;
vessel_edit_box_position = 1;
function vessel_edit_open() {

    // if (typeof mode === 'undefined' || mode == "add") {
    //     document.getElementById("vessel_title").innerText = "Add Vessel";
    // } else if (mode == "edit") {
    //     document.getElementById("vessel_title").innerText = "Edit Vessel";
    // }

    if (vessel_edit_box_position == 1) {

        document.getElementById("vessel_edit_box").style.left = "10px"; 
        vessel_edit_box_position = 2;

    }

    else if (vessel_edit_box_position == 2) {
        document.getElementById("vessel_edit_box").style.left = "-1000px"; 
        vessel_edit_box_position = 1;
    }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////// vessel Start ///////////////////////////////////////////////////////////////////////////////////////////////


var global_vessel_manager_data = ""; // this will be used to gather and update the data, for use in other functions such as the search function
function vessel_manager_retrieve_lines() {

    //console.log("vessel_manager_retrieve_lines()");

    vessel_manager_clear_lines()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '';
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_request.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(`VESSEL MANAGER RESPONSE TEXT: ${this.responseText}`);

            global_vessel_manager_data = this.responseText;

            if (global_vessel_manager_data === "") {
                // do nothing if data returned is <empty string>
            }

            else {
                vessel_manager_load_lines("");
            }
        
        }
    
    }
    ajax_request.send(data_to_send);
}


function vessel_manager_clear_lines() {

    //console.log("vessel_manager_clear_lines()");

    for (let x = 0; x <= vessel_total_lines; x++) {

        if (document.getElementById("vessel_line_" + x) !== null) {
                
            var line_to_delete = document.getElementById("vessel_line_" + x)
            line_to_delete.remove()

        }

    }

    vessel_total_lines = 0;

}


function vessel_manager_load_lines(imo_search_text) {

    // imo_search_text passed through, represents imo text to filter by
    var imo_text_chars = imo_search_text.length


    var vessel_manager_array = global_vessel_manager_data.split(',')

    var vessel_lines_to_load = vessel_manager_array.length / 7;

    let filtered_vessel_count = 0;

    for (let x = 0; x < vessel_lines_to_load; x++) {
        //console.log(`Line ${x} of ${vessel_lines_to_load}`);

        var vessel_number = vessel_manager_array[7*x + 0]
        var vessel_date = vessel_manager_array[7*x + 1]
        var vessel_imo = vessel_manager_array[7*x + 2]
        var vessel_name = vessel_manager_array[7*x + 3]
        var vessel_speed = vessel_manager_array[7*x + 4]
        var vessel_token = vessel_manager_array[7*x + 5]
        var vessel_company = vessel_manager_array[7*x + 6]

        if ( vessel_imo.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase() ||
            vessel_name.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase() ||
            vessel_date.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase() ||
            vessel_company.slice(0, imo_text_chars).toLowerCase() == imo_search_text.toLowerCase()
        ) {
            filtered_vessel_count++;
            vessel_manager_insert_line(vessel_number);

            var vessel_text_date = document.getElementById("vessel_text_date_" + vessel_total_lines)
            vessel_text_date.innerText = vessel_date;

            var vessel_text_imo = document.getElementById("vessel_text_imo_" + vessel_total_lines)
            vessel_text_imo.innerText = vessel_imo;
            vessel_text_imo.setAttribute('href', parent_folder + '/monitoring_page.php?alert_type=0&token='+vessel_token+'');
            vessel_text_imo.setAttribute('target', '_blank');

            var vessel_text_name = document.getElementById("vessel_text_name_" + vessel_total_lines)
            vessel_text_name.innerText = vessel_name;
            vessel_text_name.setAttribute('href', 'javascript:');
            vessel_text_name.setAttribute("onclick", "vessel_manager_edit_clicked(this.id)");

            var vessel_text_speed = document.getElementById("vessel_text_speed_" + vessel_total_lines)
            vessel_text_speed.innerText = vessel_speed;

            var vessel_text_company = document.getElementById("vessel_text_company_" + vessel_total_lines)
            vessel_text_company.innerText = vessel_company;
        }

        else {
            // do nothing
        }

    }
    if (imo_search_text.length > 0) {
        document.getElementById("tab_1").querySelector(".page_top_left").innerHTML = `<p>${filtered_vessel_count} of ${vessel_lines_to_load} vessels found</p>`;
    } else {
        document.getElementById("tab_1").querySelector(".page_top_left").innerHTML = `<p>${vessel_lines_to_load} vessels</p>`;
    }
}


var vessel_total_lines = 0;
function vessel_manager_insert_line(vessel_number) {


    vessel_total_lines++

    var vessel_line = document.createElement("div");
        vessel_line.setAttribute("class", "application_table_line");
        vessel_line.setAttribute("id", "vessel_line_" + vessel_total_lines);
        document.getElementById("vessel_table_body_id").appendChild(vessel_line);



    var vessel_cell_1 = document.createElement("div");
        vessel_cell_1.setAttribute("class", "vessel_table_cell");
        vessel_cell_1.setAttribute("id", "vessel_cell_date_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_1)

    var vessel_text_1 = document.createElement("p");
        vessel_text_1.setAttribute("class", "application_cell_text");
        vessel_text_1.setAttribute("id", "vessel_text_date_" + vessel_total_lines);
        vessel_text_1.innerText = "";
        document.getElementById("vessel_cell_date_" + vessel_total_lines).appendChild(vessel_text_1)   



    var vessel_cell_2 = document.createElement("div");
        vessel_cell_2.setAttribute("class", "vessel_table_cell");
        vessel_cell_2.setAttribute("id", "vessel_cell_imo_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_2)

    var vessel_text_2 = document.createElement("a");
        vessel_text_2.setAttribute("class", "application_href_cell_text");
        vessel_text_2.setAttribute("id", "vessel_text_imo_" + vessel_total_lines);
        vessel_text_2.setAttribute("data", vessel_number);
        vessel_text_2.innerText = "";
        document.getElementById("vessel_cell_imo_" + vessel_total_lines).appendChild(vessel_text_2) 



    var vessel_cell_3 = document.createElement("div");
        vessel_cell_3.setAttribute("class", "vessel_table_cell");
        vessel_cell_3.setAttribute("id", "vessel_cell_name_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_3)

    var vessel_text_3 = document.createElement("a");
        vessel_text_3.setAttribute("class", "application_href_cell_text");
        vessel_text_3.setAttribute("id", "vessel_text_name_" + vessel_total_lines);
        vessel_text_3.setAttribute("data", vessel_number);
        vessel_text_3.innerText = "";
        document.getElementById("vessel_cell_name_" + vessel_total_lines).appendChild(vessel_text_3) 



    var vessel_cell_4 = document.createElement("div");
        vessel_cell_4.setAttribute("class", "vessel_table_cell");
        vessel_cell_4.setAttribute("id", "vessel_cell_speed_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_4)

    var vessel_text_4 = document.createElement("p");
        vessel_text_4.setAttribute("class", "application_cell_text");
        vessel_text_4.setAttribute("id", "vessel_text_speed_" + vessel_total_lines);
        vessel_text_4.innerText = "";
        document.getElementById("vessel_cell_speed_" + vessel_total_lines).appendChild(vessel_text_4) 

    var vessel_cell_5 = document.createElement("div");
        vessel_cell_5.setAttribute("class", "vessel_table_cell");
        vessel_cell_5.setAttribute("id", "vessel_cell_company_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_5)

    var vessel_text_5 = document.createElement("p");
        vessel_text_5.setAttribute("class", "application_cell_text");
        vessel_text_5.setAttribute("id", "vessel_text_company_" + vessel_total_lines);
        vessel_text_5.innerText = "";
        document.getElementById("vessel_cell_company_" + vessel_total_lines).appendChild(vessel_text_5)


    
    var vessel_cell_view = document.createElement("div");
        vessel_cell_view.setAttribute("class", "vessel_table_cell_button");
        vessel_cell_view.setAttribute("id", "vessel_cell_view_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_view)

    var vessel_picture_view = document.createElement("div");
        vessel_picture_view.setAttribute("class", "application_view_button");
        vessel_picture_view.setAttribute("id", "vessel_picture_view_" + vessel_total_lines);
        vessel_picture_view.setAttribute("data", vessel_number);
        vessel_picture_view.setAttribute("onclick", "vessel_manager_view(this.id)");
        document.getElementById("vessel_cell_view_" + vessel_total_lines).appendChild(vessel_picture_view)



    var vessel_cell_log = document.createElement("div");
        vessel_cell_log.setAttribute("class", "vessel_table_cell_button");
        vessel_cell_log.setAttribute("id", "vessel_cell_log_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_log)

    var vessel_picture_log = document.createElement("div");
        vessel_picture_log.setAttribute("class", "vessel_log_view_button");
        vessel_picture_log.setAttribute("id", "vessel_picture_log_" + vessel_total_lines);
        vessel_picture_log.setAttribute("data", vessel_number);
        vessel_picture_log.setAttribute("onclick", "vessel_manager_log(this.id)");
        document.getElementById("vessel_cell_log_" + vessel_total_lines).appendChild(vessel_picture_log)


    if (resource_permissions.canAddVessels) { 
        var vessel_cell_addroute = document.createElement("div");
        vessel_cell_addroute.setAttribute("class", "vessel_table_cell_button");
        vessel_cell_addroute.setAttribute("id", "vessel_cell_addroute_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_addroute)

        var vessel_picture_addroute = document.createElement("div");
        vessel_picture_addroute.setAttribute("class", "vessel_addroute_view_button");
        vessel_picture_addroute.setAttribute("id", "vessel_picture_addroute_" + vessel_total_lines);
        vessel_picture_addroute.setAttribute("data", vessel_number);
        vessel_picture_addroute.setAttribute("onclick", "vessel_manager_addroute(this.id)");
        document.getElementById("vessel_cell_addroute_" + vessel_total_lines).appendChild(vessel_picture_addroute)
    }

    if (resource_permissions.canEditVessels) { 
        var vessel_cell_edit = document.createElement("div");
        vessel_cell_edit.classList.add("vessel_table_cell_button");
        vessel_cell_edit.setAttribute("id", "vessel_cell_edit_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_edit);
    
        var vessel_picture_edit = document.createElement("div");
        vessel_picture_edit.classList.add("application_edit_button");
        vessel_picture_edit.setAttribute("id", "vessel_picture_edit_" + vessel_total_lines);
        vessel_picture_edit.setAttribute("data", vessel_number);
        vessel_picture_edit.setAttribute("onclick", "vessel_manager_edit_clicked(this.id)");
        vessel_cell_edit.appendChild(vessel_picture_edit);
    }

    if (resource_permissions.canDeleteVessels) { 
        var vessel_cell_delete = document.createElement("div");
        vessel_cell_delete.setAttribute("class", "vessel_table_cell_button");
        vessel_cell_delete.setAttribute("id", "vessel_cell_delete_" + vessel_total_lines);
        document.getElementById("vessel_line_" + vessel_total_lines).appendChild(vessel_cell_delete)
    
      
        var vessel_picture_delete = document.createElement("div");
        vessel_picture_delete.setAttribute("class", "application_delete_button");
        vessel_picture_delete.setAttribute("id", "vessel_picture_delete_" + vessel_total_lines);
        vessel_picture_delete.setAttribute("data", vessel_number);
        vessel_picture_delete.setAttribute("onclick", "vessel_manager_delete_line(this.id)");
     
        document.getElementById("vessel_cell_delete_" + vessel_total_lines).appendChild(vessel_picture_delete)
    }



}


var vessel_number_clicked= "";
function vessel_manager_get_number(passed_id) {

    var button_clicked_data = document.getElementById(passed_id).getAttribute("data")
    vessel_number_clicked = button_clicked_data
}


function vessel_manager_edit_clicked(passed_id) {

    var row = document.getElementById(passed_id).parentElement.parentElement;

    // Clear email addresses
    clearContactList("edit_vessel_email_list");

    var imo_number = row.children[1].children[0].innerText;

    vessel_manager_open_edit(imo_number)


}


function vessel_manager_open_edit(imo_number) {
    
    closeMenuBox.style.display = "block"; // manually set close button incase user clicks in from vessel popup on map

    optionsClose(1);
    is_nothing_open = false;
    // document.getElementById("vessel_title").innerText = "Edit Vessel";
    vessel_edit_open();

    var request = new XMLHttpRequest();
    request.open("POST", '' + app_root + '/vessels/vessel_manager_edit_load.php', true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    request.onload = function() {
        if (request.status == 200) {

            console.log(this.responseText)
            // console.log("Vessel not found in vessel dynamic table")

            if (this.responseText == "Vessel not found in vessel dynamic table") { // temporary error message 28/01/2025 in response to Darren's email about Vessel MUMBAI not having any data in vessel_dynamic
                alert("Vessel Data not currently updated in the system, please wait 10 minutes and try again, if this issue persists please contact Sensor Magic");
            }

            else { // continue if vessel has proper response data

                var response = JSON.parse(request.responseText);

                // Set menu title
                document.getElementById("vessel_edit_title").innerText = "Edit " + response["vessel_name"];
                // Set editable fields
                const editVesselForm = document.getElementById("vessel_edit_form");
                editVesselForm.elements["vessel_imo"].value = imo_number;
                editVesselForm.elements["company_id"].value = response["company_id"];
                editVesselForm.elements["vessel_name"].value = response["vessel_name"];
                editVesselForm.elements["vessel_speed"].value = response["vessel_speed"];
                editVesselForm.elements["vessel_flag"].value = response["vessel_flag"];
                editVesselForm.elements["hra_route"].value = response["hra_route"];
                editVesselForm.elements["cargo_details"].value = response["cargo_details"];
                editVesselForm.elements["freeboard"].value = response["freeboard"];
                editVesselForm.elements["primary_email_address"].value = response["primary_email_address"];
                editVesselForm.elements["primary_phone_number"].value = response["primary_phone_number"];

                // Set uneditable fields
                document.getElementById("data_imo_edit").innerText = "IMO: " + imo_number;
                document.getElementById("data_name_edit").innerText = "Name: " + response["vessel_name"];
                document.getElementById("data_callsign_edit").innerText = "Callsign: " + response["callsign"];
                document.getElementById("data_shiptype_edit").innerText = "Ship type: " + response["ship_type"];
                document.getElementById("data_navigational_status_edit").innerText = "Navigational status: " + response["navigation_status"];
                document.getElementById("data_mmsi_edit").innerText = "MMSI: " + response["mmsi"];
                document.getElementById("data_speed_edit").innerText = "Speed: " + response["vessel_speed"];
                document.getElementById("data_destination_edit").innerText = "Destination: " + response["destination"];
                document.getElementById("vessel_6_hourly_link").setAttribute('href', parent_folder + '/live_monitoring_page.php?vessel_number=' + response["vessel_number"]);
                document.getElementById("vessel_6_hourly_link").setAttribute('target', '_blank');
                // Set slider values
                // editVesselForm.elements["polygon_alerts"].checked = response["polygon_alerts"] ? true : false;
                // editVesselForm.elements["route_alerts"].checked = response["route_alerts"] ? true : false;
                // editVesselForm.elements["speed_alerts"].checked = response["speed_alerts"] ? true : false;
                // editVesselForm.elements["ais_alerts"].checked = response["ais_alerts"] ? true : false;
                
                // Clear email addresses
                clearContactList("edit_vessel_email_list");

                // Populate existing emails
                for (let i = 0; i < response["emails"].length; i++) {
                    let address = response["emails"][i]["address"];
                    let alerts = response["emails"][i]["alerts"];
                    addEmailItem('edit_vessel_email_list', address, alerts, "");
                }

            }
        }
    }

    request.send('imo_number='+imo_number);
}



function vessel_manager_edit_send(event) {

    var date_in_seconds = new Date().getTime();

    var data = {};
    for (let i = 0; i < event.target.elements.length; i++) {
        let element = event.target.elements[i];
        // console.log(`${element.name} (${element.tagName}): ${element.value}`);
        if ((element.tagName !== "INPUT" && element.tagName !== "SELECT") || element.name === "emails[]" || element.name === "email_alerts[]") {
            continue;
        }
        if (element.type === "checkbox") {
            data[element.name] = element.checked;
            data["date_in_seconds"] = date_in_seconds;
        }
        else if (element.tagName === "INPUT") {
            data[element.name] = element.value;
        }
        else if (element.tagName === "SELECT") {
            data[element.name] = element.value;
        }
    }

    // Store email address objects from form
    var emails = [];
    if ("emails[]" in event.target.elements) {
        if (typeof event.target.elements["emails[]"].length === "number") {
            for (let i = 0; i < event.target.elements["emails[]"].length; i++) {
                if (event.target.elements["emails[]"][i].value.length > 0) {
                    let item = {};
                    item.address = event.target.elements["emails[]"][i].value;
                    item.alerts = event.target.elements["email_alerts[]"][i].checked;
                    emails.push(item);
                }
            }
        } else if (event.target.elements["emails[]"] instanceof Element && event.target.elements["emails[]"].tagName === "INPUT" && event.target.elements["emails[]"].value.length > 0) {
            let item = {};
            item.address = event.target.elements["emails[]"].value;
            item.alerts = event.target.elements["email_alerts[]"].checked;
            emails.push(item);
        }
    }
    data["emails"] = emails;

    var send = new XMLHttpRequest();
    send.open("POST", '' + app_root + '/vessels/vessel_manager_edit_send.php', true);
    send.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    send.onload = function() {
        console.log(send.responseText);
        // alert(JSON.stringify(send.responseText));
    }
    send.send(JSON.stringify(data));

    event.preventDefault();

    is_nothing_open = true;
    //console.log("is_nothing_open = true")
    optionsOpen();
    
    if (vessel_edit_box_position == 2) {
        document.getElementById("vessel_edit_box").style.left = "-1000px"; 
        vessel_edit_box_position = 1;
    }

    openVessels();
}


function vessel_manager_open_create() {
    
    const form = document.getElementById("vessel_create_box")
    if (form && form instanceof HTMLFormElement) {
        Array.from(form.elements).forEach((element) => {
            if (element instanceof HTMLInputElement) {
                 element.value = "";
            }
        });
    }

    //console.log("vessel_manager_open_create()");

    // Clear email addresses
    clearContactList("new_vessel_email_list");
    // 1 initial field
    addEmailItem("new_vessel_email_list", "", true, "");

    optionsClose(1);
    is_nothing_open = false;
    //console.log("is_nothing_open = false")


    document.getElementById("vessel_imo_to_edit").value = ""
    document.getElementById("vessel_speed_to_edit").value = ""

    document.getElementById("data_imo").innerText = "IMO: ";
    document.getElementById("data_name").innerText = "Name: ";
    document.getElementById("data_callsign").innerText = "Callsign: ";
    document.getElementById("data_shiptype").innerText = "shipType: ";
    document.getElementById("data_navigational_status").innerText = "navigationalStatus: ";
    document.getElementById("data_mmsi").innerText = "MMSI: ";
    document.getElementById("data_speed").innerText = "Speed: ";
    document.getElementById("data_destination").innerText = "Destination: ";

    document.getElementById("vessel_speed_to_edit").value = 5;

    // document.getElementById("save_hide").style.display = "none";
    document.getElementById("save_hide").setAttribute("disabled", '');

    vessel_create_open();
    // document.getElementById("vessel_create_box").style.left = "10px"; 
    //
    // vessel_create_box_position = 2;

}


function reset_company_selectors() {

    document.getElementById("vessel_company_input").length = ""; // resets company input
    document.getElementById("vessel_edit_company_sel").length = "";

    add_companies_to_vessel()

}

function reset_user_selectors() {
    const newUserForm = document.getElementById("newUserForm");
    const editUserForm = document.getElementById("editUserForm");

    if (typeof newUserForm.elements["company_id"] !== "undefined") newUserForm.elements["company_id"].length = ""; // resets user input

    if (typeof editUserForm.elements["company_id"] !== "undefined") editUserForm.elements["company_id"].length = ""; // resets user input

    if (newUserForm && newUserForm.elements["company_id"]) {
        newUserForm.elements["company_id"].length = 0; // Reset dropdown
    }
    
    if (editUserForm && editUserForm.elements["company_id"]) {
        editUserForm.elements["company_id"].length = 0; // Reset dropdown
    }

    add_companies_to_user();
}



function onDisableRead(event) {
    const tableRow = event.target.closest("tr");

    if (event.target.checked == false) {
        tableRow.querySelectorAll('input').forEach(i => {
            i.checked = false;
        });
    }
}

function onEnablePermission(event) {
    const tableRow = event.target.closest("tr");

    if (event.target.checked == true) {
        tableRow.querySelector('td:nth-child(5) > input[type="checkbox"]').checked = true;
    }
}

function restore_vessel(vessel_imo) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_imo=' + vessel_imo
    ajax_request.open('POST', '' + app_root + '/vessels/restore_deleted_vessel_company.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            if (this.responseText == "error_no_vessel_imo") {
                alert("Error: no vessel IMO found in database");
            }

            else {
                var vessel_name = this.responseText
                alert("Restored Vessel: " + vessel_name);

                document.getElementById("vessel_create_box").style.left = "-1000px";
                vessel_create_box_position = 1;

                optionsClose();
                optionsOpen();
                openVessels();
            }

        
        }
    
    }
    ajax_request.send(data_to_send);
}


function vessel_manager_create_load() {

    //console.log("vessel_manager_create_load()");

    const date = new Date();
    let day = date.getDate();
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    let current_date = day + "/" + month + "/" + year

    const vessel_imo_input = document.getElementById("vessel_imo_to_edit");
    // Trim IMO number
    vessel_imo_input.value = vessel_imo_input.value.trim();
    var vessel_imo = vessel_imo_input.value
    var vessel_speed = document.getElementById("vessel_speed_to_edit").value

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + '&vessel_date=' + current_date
    + '&vessel_imo=' + vessel_imo
    + '&vessel_speed=' + vessel_speed
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_load.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            if (this.responseText == "error_0") {
                alert("Please enter a vessel IMO");
            }

            else if (this.responseText == "error_1") {
                alert("Vessel already exists in database");
            }

            else if (this.responseText == "error_2") {
                alert("No data could be returned for this IMO number");
            }

            else if (this.responseText == "error_vessel_deleted") {

                let text = "Vessel has been deleted recently, do you want to restore it?";

                if (confirm(text) == true) {
                    
                    restore_vessel(vessel_imo); // fully restores vessel and associated company in database
                    reset_company_selectors(); // reloads company selectors, for use in the edit menu

                } 

                else {
                    // do nothing else if cancelled
                }

            }

            else {
                var confirm_array = this.responseText.split(",;");
                document.getElementById("data_imo").innerText = "IMO: " + confirm_array[0];
                document.getElementById("data_name").innerText = "Name: " + confirm_array[1];
                document.getElementById("data_callsign").innerText = "Callsign: " + confirm_array[2];
                document.getElementById("data_shiptype").innerText = "shipType: " + confirm_array[3];
                document.getElementById("data_navigational_status").innerText = "navigationalStatus: " + confirm_array[4];
                document.getElementById("data_mmsi").innerText = "MMSI: " + confirm_array[5];
                document.getElementById("data_speed").innerText = "Speed: " + confirm_array[6];
                document.getElementById("data_destination").innerText = "Destination: " + confirm_array[7];
                document.getElementById("vessel_flag_create").value = confirm_array[8];
                
                // document.getElementById("save_hide").style.display = "block";
                document.getElementById("save_hide").removeAttribute("disabled");
            }




        }
    
    }
    ajax_request.send(data_to_send);

}

function vessel_manager_create_save(event) {
    if (event) {
        event.preventDefault();
    }

    //console.log("vessel_manager_create_save()");

    const primaryEmailInput = document.getElementById("new_vessel_primary_email");
    if (!primaryEmailInput.checkValidity()) {
        alert("Please enter a valid primary email address.");
        return;
    }

    const date = new Date();
    let day = date.getDate();
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    let current_date = day + "/" + month + "/" + year

    var ajax_request = new XMLHttpRequest();
    var form = event.target;
    //var emailsForm = document.getElementById("new_vessel_email_list");
    var emails = '[]';
    if ("emails[]" in form.elements) {
        var emailList = [];
        if (typeof form.elements["emails[]"].length === "number") {
            for (let i = 0; i < form.elements["emails[]"].length; i++) {
                let emailObj = {};
                if (typeof form["emails[]"][i] !== 'undefined' && form["emails[]"][i].value.length > 0) {
                    emailObj["address"] = form["emails[]"][i].value;
                    if (typeof form.elements["email_alerts[]"][i] !== 'undefined') {
                        emailObj["alerts"] = form.elements["email_alerts[]"][i].checked;
                    } else {
                        emailObj["alerts"] = true;
                    }
                    emailList.push(emailObj);
                }
            }
        } else if (form.elements["emails[]"] instanceof Element && form.elements["emails[]"].tagName === "INPUT" && form.elements["emails[]"].value.length > 0) {
            let item = {};
            item.address = form.elements["emails[]"].value;
            item.alerts = form.elements["email_alerts[]"].checked;
            emailList.push(item);
        }
        emails = JSON.stringify(emailList);
    }
    
    var data_to_send = ''
    + '&vessel_date=' + current_date
    + '&vessel_imo=' + document.getElementById("vessel_imo_to_edit").value
    + '&vessel_speed=' + document.getElementById("vessel_speed_to_edit").value
    + '&vessel_flag=' + document.getElementById("vessel_flag_create").value
    + '&hra_route=' + document.getElementById("vessel_hra_route_create").value
    + '&cargo_details=' + document.getElementById("vessel_cargo_details_create").value
    + '&freeboard=' + document.getElementById("vessel_freeboard_create").value
    + '&vessel_company=' + document.getElementById("vessel_company_input").value
    + '&primary_email_address=' + document.getElementById("new_vessel_primary_email").value
    + '&primary_phone_number=' + document.getElementById("new_vessel_primary_phone_number").value
    + '&emails=' + emails
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_create.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // alert(ajax_request.responseText);
            console.log(this.responseText);
            alert("Vessel Added to Database");

            optionsClose();
            optionsOpen();
            openVessels();

        }
    
    }
    ajax_request.send(data_to_send);

    route_manager_get_imos()
    reload_route_imo_selector()


}




// For creating lists of email addresses
function clearContactList(container_id) {
    const container = document.getElementById(container_id);
    container.innerHTML = "";
}

// Action for delete button in email form entries
function deleteEmail(e) {
    e.parentElement.remove();
}

function deletePhone(e) {
    e.parentElement.remove();
}

// Create an email form entry and set provided values
function createEmailListItem(address, checked, prefix) {
    const li = document.createElement("span");
    li.classList.add("email_list_item");

    const input = document.createElement("input");
    input.name = prefix ? prefix + "emails[]" : "emails[]";
    input.type = "email";
    if (address) input.value = address;
    li.appendChild(input);

    const label = document.createElement("label");
    label.innerText = "Enable alerts:";
    li.appendChild(label);

    const check = document.createElement("input");
    check.type = "checkbox";
    check.setAttribute("name", prefix ? prefix + "email_alerts[]" : "email_alerts[]");
    if (checked) {
        check.setAttribute("checked", "");
    }
    li.appendChild(check);

    // const swit = document.createElement("label");
    // swit.classList.add("switch");
    // const check = document.createElement("input");
    // check.type = "checkbox";
    // check.setAttribute("name", prefix ? prefix + "email_alerts[]" : "email_alerts[]");
    // if (checked) {
    //     check.setAttribute("checked", "");
    // }
    // swit.appendChild(check);
    // const slider = document.createElement("span");
    // slider.classList.add("slider");
    // swit.appendChild(slider);
    // li.appendChild(swit);

    const delButton = document.createElement("button");
    delButton.type = "button";
    delButton.innerText = "-";
    delButton.classList.add("subtract_button");
    delButton.setAttribute("onclick", "deleteEmail(this)");
    li.appendChild(delButton);

    return li;
}

// Create a phone number form entry and set provided value
function createPhoneListItem(number) {
    const li = document.createElement("span");
    li.classList.add("phone_list_item");

    const input = document.createElement("input");
    input.name = "phones[]";
    if (number) input.value = number;
    li.appendChild(input)

    const delButton = document.createElement("button");
    delButton.type = "button";
    delButton.innerText = "-";
    delButton.classList.add("subtract_button");
    delButton.setAttribute("onclick", "deletePhone(this)");
    li.appendChild(delButton);

    return li;
}

// Add email form entry to specified element, and set provided values
function addEmailItem(container_id, address, checked, prefix) {
    const container = document.getElementById(container_id);
    // Trim empty inputs
    // for (let i = 0; i < container.children.length; i++) {
    //     if (container.children[i].tagName === "SPAN"
    //     && container.children[i].children[0].value === "") {
    //         container.children[i].remove();
    //     }
    // }
    container.appendChild(createEmailListItem(address, checked, prefix));
}

// Add phone number form entry to specified element, and set provided value
function addPhoneItem(container_id, number) {
    const container = document.getElementById(container_id);
    container.appendChild(createPhoneListItem(number));
}


function vessel_manager_view(passed_id) {

    var vessel_number = document.getElementById(passed_id).getAttribute("data")

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number=' + vessel_number
    ajax_request.open('POST', '' + 'https://service.eos-assure.com/php/vessels/vessel_manager_view_data.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);
            var response = JSON.parse(this.responseText);


            var vessel_imo = response["vessel_imo"];
            var latitude = Number(response["latitude"]);
            var longitude = Number(response["longitude"]);
            var heading = response["heading"];
            var name = response["name"];
            var callsign = response["callsign"];
            var shipType = response["shipType"];
            var is_vessel_inside_eos_dmz = response["is_vessel_inside_eos_dmz"];
            var is_vessel_inside_route = response["is_vessel_inside_route"];
            var navigationalStatus = response["navigationalStatus"];
            var mmsi = response["mmsi"];
            var speed = response["speed"];
            var destination = response["destination"];
            var date_received = response["date_received"];

            var current_date_seconds = new Date().getTime()
            var date_received_seconds = new Date(date_received).getTime()
            var time_difference_milliseconds = current_date_seconds - date_received_seconds
            var time_difference_seconds = time_difference_milliseconds / 1000
            var time_difference_minutes = time_difference_seconds / 60
            var time_difference_hours = time_difference_minutes / 60


            console.log(!document.getElementById("marker_" + Number(vessel_imo)))

            if (!vessel_imo || !latitude || !longitude) { // temporary error message 28/01/2025 in response to Darren's email about Vessel MUMBAI not having any data in vessel_dynamic
                alert("Vessel Data not currently updated in the system, please wait 10 minutes and try again, if this issue persists please contact Sensor Magic");
            }

            else if (!document.getElementById("marker_" + Number(vessel_imo))) { // if marker is not shown, but user wants to view vessel, add marker and add vessel to global array to be loaded regardless of filter

                create_vessel_marker(vessel_imo, latitude, longitude, heading, name, callsign, shipType, is_vessel_inside_eos_dmz, is_vessel_inside_route, navigationalStatus, mmsi, speed, destination, date_received, time_difference_hours)

                global_filtered_vessels_loaded_array.push(vessel_imo); // push vessel_imo to global array, vessels here will be loaded regardless of filter

                optionsClose()
                map.flyTo({center: [Number(longitude),Number(latitude)], zoom:5});
                document.getElementById("marker_" + Number(vessel_imo)).click()
            }

            else { // if vessel is already on map and has valid data, move the map to it automatically
                optionsClose()
                map.flyTo({center: [Number(longitude),Number(latitude)], zoom:5});
                document.getElementById("marker_" + Number(vessel_imo)).click()
            }


        }
    
    }
    ajax_request.send(data_to_send);

}


var global_vessel_view_imo = "";
var global_vessel_view_long = "";
var global_vessel_view_lat = "";
function vessel_manager_get_location(vessel_number_clicked) {


    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number_clicked=' + vessel_number_clicked
    //console.log(vessel_number_clicked)
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_view_position.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);

            location_response_data = this.responseText;
            var location_array = location_response_data.split(',')

            var location_imo = location_array[0];
            var location_lat = location_array[1];
            var location_long = location_array[2];

            map.flyTo({center: [location_long,location_lat], zoom:3.5});

            optionsClose();



        }
    
    }
    ajax_request.send(data_to_send);

}


function vessel_manager_delete_line(passed_id) {

  let text = "Do you really want to delete this Vessel?\nPress OK to confirm.";

  if (confirm(text) == true) {

    var vessel_number = document.getElementById(passed_id).getAttribute("data")
    vessel_manager_delete(vessel_number);

    document.getElementById(passed_id).parentElement.parentElement.remove();

    alert("Vessel Deleted")

  } 

  else {
    // do nothing else if cancelled
  }

}


function vessel_manager_delete(vessel_number) {

    // console.log(vessel_number)

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number=' + vessel_number
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_delete.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

        }
    
    }
    ajax_request.send(data_to_send);


}

function load_ports() {

    //console.log("load_ports()");

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/load_ports.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);

            var port_data = this.responseText;
            var port_data_array = port_data.split(',;')

            var port_lines_to_load = port_data_array.length / 4;
            var arr = []
            for (let x = 0; x < port_lines_to_load; x++) {

                var port_name = port_data_array[4*x + 0];
                var country_name = port_data_array[4*x + 1];
                var latitude = port_data_array[4*x + 2];
                var longitude = port_data_array[4*x + 3];

                arr[x] = {
                    'type': 'Feature',
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [longitude, latitude]
                    },
                    'properties': {
                        'description':
                            "<b>Port: </b>"+port_name+"<br>"+"<b>Country: </b>"+country_name
                    },
                }

            }


      

//console.log(arr);



// Load an image from an external URL.
map.loadImage(
'' + document_root + '/assets/anchor.png',
(error, image) => {
if (error) throw error;
 
// Add the image to the map style.
map.addImage('cat', image);
 
 
// Add a layer to use the image to represent the data.
map.addLayer({
    'id': 'path',
    'type': 'symbol',
    'source': {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: arr
        }

    },
    'layout': {
    'visibility': 'none',
    'icon-image': 'cat', // reference the image
    'icon-size': 0.055,
    "icon-allow-overlap": true
    },
    "minzoom": 2.0, // port zoom level



});

map.on('click', 'path', (e) => {
// Copy coordinates array.
const coordinates = e.features[0].geometry.coordinates.slice();
const description = e.features[0].properties.description;
 
// Ensure that if the map is zoomed out such that multiple
// copies of the feature are visible, the popup appears
// over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
 
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});


}
);


        }
    
    }
    ajax_request.send(data_to_send);


}



load_ports()

global_log_action_imo = "";
log_action_box_position = 1
function log_action(imo) {
    
    console.log(imo);
    console.log(log_action_box_position);
    console.log(document.getElementById("log_action_box"))

    document.getElementById("log_action_description_box").value = "";
    document.getElementById("log_type_select").selectedIndex = 0;

    if (log_action_box_position == 1) {

        optionsOpen()
        optionsClose(1)
        is_nothing_open = false;
        
        document.getElementById("log_action_box").style.left = "10px"; 
        log_action_box_position = 2;


    }

    document.getElementById("log_imo_title").innerHTML = imo;
    global_log_action_imo = imo;

}

function new_log() {
    log_action(global_vessel_log_imo)
}

function save_log_action() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'imo_number=' + global_log_action_imo
    + '&log_type=' + document.getElementById("log_type_select").value
    + '&log_action_text=' + document.getElementById("log_action_description_box").value
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_log_action_send.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);
            alert("Action Logged");
            document.getElementById("log_action_box").style.left = "-1000px"; 
            log_action_box_position = 1;
            optionsClose();

        }
    }
    ajax_request.send(data_to_send);
}



var log_total_lines = 0;
function log_insert_line() {

    //console.log("log_insert_line()");

    log_total_lines++

    var log_line = document.createElement("div");
        log_line.setAttribute("class", "application_table_line");
        log_line.setAttribute("id", "log_line_" + log_total_lines);
        document.getElementById("log_table_body_id").appendChild(log_line);



    var log_cell_1 = document.createElement("div");
        log_cell_1.setAttribute("class", "log_table_cell");
        log_cell_1.setAttribute("id", "log_cell_date_" + log_total_lines);
        document.getElementById("log_line_" + log_total_lines).appendChild(log_cell_1)

    var log_text_1 = document.createElement("p");
        log_text_1.setAttribute("class", "application_cell_text");
        log_text_1.setAttribute("id", "log_text_date_" + log_total_lines);
        log_text_1.innerText = "DATE";
        document.getElementById("log_cell_date_" + log_total_lines).appendChild(log_text_1)   



    var log_cell_2 = document.createElement("div");
        log_cell_2.setAttribute("class", "log_table_cell");
        log_cell_2.setAttribute("id", "log_cell_imo_" + log_total_lines);
        document.getElementById("log_line_" + log_total_lines).appendChild(log_cell_2)

    var log_text_2 = document.createElement("p");
        log_text_2.setAttribute("class", "application_cell_text");
        log_text_2.setAttribute("id", "log_text_imo_" + log_total_lines);
        log_text_2.innerText = "IMO";
        document.getElementById("log_cell_imo_" + log_total_lines).appendChild(log_text_2) 



    var log_cell_3 = document.createElement("div");
        log_cell_3.setAttribute("class", "log_table_cell");
        log_cell_3.setAttribute("id", "log_cell_type_" + log_total_lines);
        document.getElementById("log_line_" + log_total_lines).appendChild(log_cell_3)

    var log_text_3 = document.createElement("p");
        log_text_3.setAttribute("class", "application_cell_text");
        log_text_3.setAttribute("id", "log_text_type_" + log_total_lines);
        log_text_3.innerText = "TYPE";
        document.getElementById("log_cell_type_" + log_total_lines).appendChild(log_text_3) 


    var log_cell_4 = document.createElement("div");
        log_cell_4.setAttribute("class", "log_table_cell");
        log_cell_4.setAttribute("id", "log_cell_summary_" + log_total_lines);
        document.getElementById("log_line_" + log_total_lines).appendChild(log_cell_4)

    var log_text_4 = document.createElement("p");
        log_text_4.setAttribute("class", "application_cell_text");
        log_text_4.setAttribute("id", "log_text_summary_" + log_total_lines);
        log_text_4.innerText = "SUMMARY";
        document.getElementById("log_cell_summary_" + log_total_lines).appendChild(log_text_4) 


    
    var log_cell_view = document.createElement("div");
        log_cell_view.setAttribute("class", "log_table_cell");
        log_cell_view.setAttribute("id", "log_cell_view_" + log_total_lines);
        document.getElementById("log_line_" + log_total_lines).appendChild(log_cell_view)

    var log_picture_view = document.createElement("div");
        log_picture_view.setAttribute("class", "application_view_button");
        log_picture_view.setAttribute("id", "log_picture_view_" + log_total_lines);
        log_picture_view.setAttribute("data", log_total_lines);
        log_picture_view.setAttribute("onclick", "log_alert_data(this.id)");
        document.getElementById("log_cell_view_" + log_total_lines).appendChild(log_picture_view)


    log_colour_lines();

}


function log_colour_lines() {

    //console.log(log_total_lines);
    document.getElementById("log_line_" + log_total_lines)

    var log_array = [];
    for (let x = 0; x <= log_total_lines; x++) {

        if (document.getElementById("log_line_" + x) !== null) {
            
            log_array.push(x)

        }

    }

    var log_array_length = log_array.length - 1;
    for (let x = 0; x <= log_array_length; x++) {

        var log_array_value = log_array[x];

        if (x % 2 == 0) {
            //console.log(x + " is even")
            document.getElementById("log_line_" + log_array_value).style.backgroundColor = "white";
        }

        else if (x % 2 == 1) {
            //console.log(x + " is odd")
            document.getElementById("log_line_" + log_array_value).style.backgroundColor = "#2A3C46";
        }

    }

}


function vessel_manager_log(passed_id) {

    //console.log("vessel_manager_log()");
    openLogs()

    vessel_manager_get_number(passed_id);

    // alert(vessel_number_clicked);

    logs_load_name(vessel_number_clicked);
    logs_load_imo(vessel_number_clicked);
    logs_retrieve_data(vessel_number_clicked);
}

function logs_load_name(vessel_number_clicked) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number_clicked=' + vessel_number_clicked
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_load_name.php', false);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            document.getElementById("log_name_tochange").innerHTML = this.responseText;

        }
    
    }
    ajax_request.send(data_to_send);

}

var global_vessel_log_imo = "";
function logs_load_imo(vessel_number_clicked) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number_clicked=' + vessel_number_clicked
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_load_imo.php', false);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            global_vessel_log_imo = this.responseText;

        }
    
    }
    ajax_request.send(data_to_send);

}

function logs_retrieve_data(vessel_number_clicked) {

    log_clear_lines()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number_clicked=' + vessel_number_clicked
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_view_logs.php', false);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            log_load_lines(this.responseText);

        }
    
    }
    ajax_request.send(data_to_send);

}


function log_load_lines(log_data) {


    var log_array = log_data.split(';')
    //console.log(log_array)
    var log_lines_to_load = log_array.length / 4;

    if (log_lines_to_load >= 1) {
        for (let x = 0; x < log_lines_to_load; x++) {

            log_insert_line()

            //console.log(log_array[4*x + 0])
            //console.log(log_array[4*x + 1])
            //console.log(log_array[4*x + 2])
            //console.log(log_array[4*x + 3])

            var log_text_date = document.getElementById("log_text_date_" + (x+1))
            log_text_date.innerText = log_array[4*x + 0];

            var log_text_imo = document.getElementById("log_text_imo_" + (x+1))
            log_text_imo.innerText = log_array[4*x + 1];

            var log_text_type = document.getElementById("log_text_type_" + (x+1))
            log_text_type.innerText = log_array[4*x + 2];

            var log_text_summary = document.getElementById("log_text_summary_" + (x+1))
            log_text_summary.innerText = log_array[4*x + 3];

            document.getElementById("log_picture_view_" + (x+1)).setAttribute("data", log_array[4*x + 3]);

        }
    }
}

function log_alert_data(passed_id) {
    var clicked_data = document.getElementById(passed_id).getAttribute("data")
    alert(clicked_data);
}

function log_clear_lines() {


    for (let x = 0; x <= log_total_lines; x++) {

        if (document.getElementById("log_line_" + x) !== null) {
                
            var line_to_delete = document.getElementById("log_line_" + x)
            line_to_delete.remove()

        }

    }

    log_total_lines = 0;

}

function add_companies_to_vessel() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/get_companies_for_vessels.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);
            var company_array = this.responseText.split(";")
            var company_amount = company_array.length / 2

            for (let x = 0; x < company_amount; x++) {
                //console.log(company_array[2*x + 1])
                //console.log(company_array[2*x + 0])

                var vessel_company_input = document.getElementById("vessel_company_input");
                var vessel_edit_company_input = document.getElementById("vessel_edit_company_sel");
                var option = document.createElement("option");
                option.text = company_array[2*x + 1];
                option.value = company_array[2*x + 0];
                var option2 = option.cloneNode(true);
                vessel_company_input.add(option); 
                vessel_edit_company_input.add(option2);

            }

        }
    
    }
    ajax_request.send(data_to_send);
}

function add_companies_to_vessel() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/get_companies_for_vessels.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);
            var company_array = this.responseText.split(";")
            var company_amount = company_array.length / 2

            for (let x = 0; x < company_amount; x++) {
                //console.log(company_array[2*x + 1])
                //console.log(company_array[2*x + 0])

                var vessel_company_input = document.getElementById("vessel_company_input");
                var vessel_edit_company_input = document.getElementById("vessel_edit_company_sel");
                var option = document.createElement("option");
                option.text = company_array[2*x + 1];
                option.value = company_array[2*x + 0];
                var option2 = option.cloneNode(true);
                vessel_company_input.add(option); 
                vessel_edit_company_input.add(option2);

            }

        }
    
    }
    ajax_request.send(data_to_send);
}

add_companies_to_vessel();

function add_companies_to_user() {
    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/get_companies_for_vessels.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);
            var company_array = this.responseText.split(";")
            var company_amount = company_array.length / 2

            const newUserForm = document.getElementById("newUserForm");
            const editUserForm = document.getElementById("editUserForm");

            for (let x = 0; x < company_amount; x++) {
                //console.log(company_array[2*x + 1])
                //console.log(company_array[2*x + 0])

                var option = document.createElement("option");
                option.text = company_array[2*x + 1];
                option.value = company_array[2*x + 0];
                var option2 = option.cloneNode(true);

                if (newUserForm.elements["company_id"] !== null &&
                    newUserForm.elements["company_id"] !== undefined)
                    newUserForm.elements["company_id"].add(option); 
                if (editUserForm.elements["company_id"] !== null &&
                    editUserForm.elements["company_id"] !== undefined)
                    editUserForm.elements["company_id"].add(option2);

            }

        }
    
    }
    ajax_request.send(data_to_send);
}

//////////////////////////////////////////////////////////////////////////////


document.getElementById("route_imo_search_box").addEventListener("input", update_imo_search_box);

function update_imo_search_box() {

    var imo_search_text = document.getElementById("route_imo_search_input").value
    console.log(imo_search_text)

    route_manager_clear_lines()
    route_manager_load_lines(imo_search_text)


    var route_selected_value = document.getElementById("route_imo_dropdown").value // saves value

    var imo_text_entered = document.getElementById("route_imo_search_input").value
    var imo_chars_entered = imo_text_entered.length
    console.log(imo_text_entered)
    console.log(imo_chars_entered)


    document.getElementById("route_imo_dropdown").length = ""; // wipes selector

    var route_option = document.createElement('option'); // sets first option to "All Vessels"
    route_option.value = "All Vessels";
    route_option.innerHTML = "All Vessels";
    document.getElementById("route_imo_dropdown").appendChild(route_option)


    // var was_change_made = false
    var imo_array_length = imo_array.length - 1;
    for (let x = 0; x <= imo_array_length; x++) {

        if (imo_array[x].slice(0, imo_chars_entered) == imo_text_entered) {
            var route_option = document.createElement('option');
            route_option.value = imo_array[x];
            route_option.innerHTML = imo_array[x];
            document.getElementById("route_imo_dropdown").appendChild(route_option)

            if (imo_array[x] == route_selected_value) {
                // was_change_made = true
                document.getElementById("route_imo_dropdown").value = route_selected_value
            }


            else if (imo_array[x] == imo_text_entered) {
                // was_change_made = true
                document.getElementById("route_imo_dropdown").value = imo_text_entered
                route_manager_retrieve_lines()
            }

        }

    }

}




document.getElementById("vessel_imo_search_box").addEventListener("input", update_vessel_page);

function update_vessel_page() {

    var imo_search_text = document.getElementById("vessel_imo_search_input").value
    console.log(imo_search_text)

    vessel_manager_clear_lines()
    vessel_manager_load_lines(imo_search_text)


}



var long_pass_route_add = "";
var lat_pass_route_add = "";
function route_add_getCoordData() {

    long_pass_route_add = ""; // resets incase something is being added more than once
    lat_pass_route_add = "";

    route_convert_coordinates("route_add_textbox");
    // global_route_coordinates now defined

    for (let x = 0; x < global_route_coordinates.length; x++) {
        lat_pass_route_add = lat_pass_route_add + global_route_coordinates[x][0] + ","
        long_pass_route_add = long_pass_route_add + global_route_coordinates[x][1] + ","

    }

    long_pass_route_add = long_pass_route_add.slice(0,-1);
    lat_pass_route_add = lat_pass_route_add.slice(0,-1);
    
}








function route_manager_create_save() {

    get_radio_value_add()

    alert("route created");

    // load empty routes menu before filling it with new data

    route_manager_clear_lines();

    openRoutes();

    map.setLayoutProperty('route_line', 'visibility', 'none');
    document.getElementById("route_add_box").style.left = "-1000px"; 
    route_add_box_position = 1;

    fullMenuBox.style.left = "10px";
    closeMenuBox.style.display = "block";

    // load empty routes menu before filling it with new data


    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number=' + route_add_vessel_number_global
    + '&route_name=' + document.getElementById("route_add_name_input").value
    + '&route_start_date=' + document.getElementById("route_add_start_date_input").value
    + '&route_arrival_date=' + document.getElementById("route_add_arrival_date_input").value
    + '&port_id_start=' + document.getElementById("route_add_port_id_start").value
    + '&route_start=' + document.getElementById("route_add_start_input").value
    + '&port_id_destination=' + document.getElementById("route_add_port_id_destination").value
    + '&route_destination=' + document.getElementById("route_add_destination_input").value
    + '&transit_risk_rating=' + radio_value_add
    + '&transit_risk_area=' + document.getElementById("route_create_risk_area_sel").value;
    ajax_request.open('POST', '' + app_root + '/routes/route_manager_create.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {

            console.log(this.responseText);

            var route_last_id = this.responseText;

            ///////// Function to save current coordinate data to the id created

            route_add_getCoordData()

            var ajax_request_2 = new XMLHttpRequest();
            var data_to_send_2 = ''
            + 'vessel_number=' + route_add_vessel_number_global
            + '&route_number=' + route_last_id
            + '&long_pass=' + long_pass_route_add
            + '&lat_pass=' + lat_pass_route_add
            ajax_request_2.open('POST', '' + app_root + '/routes/route_add_send.php', true);
            ajax_request_2.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

            ajax_request_2.onreadystatechange = function() {
                if(ajax_request_2.readyState == 4 && this.status == 200) {
                    console.log(this.responseText);

                    // there is no response, only data sent and inputted

                    route_manager_retrieve_lines() // load new data onto empty routes menu


                }
            }
            ajax_request_2.send(data_to_send_2);

            ///////// Function to save current coordinate data to the id created

        }
    
    }
    ajax_request.send(data_to_send);

}



var vessel_selected_imo = "";
var vessel_selected_date = "";
var vessel_selected_estimate = "";
var vessel_selected_name = "";
var vessel_selected_start = "";
var vessel_selected_destination = "";

function vessel_manager_getDataFromNumber(vessel_number) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_number=' + vessel_number
    ajax_request.open('POST', '' + app_root + '/vessels/vessel_manager_getDataFromNumber.php', false);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);
            var vessel_selected_array = this.responseText.split(',');

            //console.log(vessel_number_clicked)
            //console.log(vessel_selected_array);

            vessel_selected_imo = vessel_selected_array[0];
            vessel_selected_date = vessel_selected_array[1];
            vessel_selected_estimate = vessel_selected_array[2];
            vessel_selected_name = vessel_selected_array[3];
            vessel_selected_start = vessel_selected_array[4];
            vessel_selected_destination = vessel_selected_array[5];

        }
    
    }
    ajax_request.send(data_to_send);

}


route_add_box_position = 1;

var route_add_vessel_number_global = "";
function vessel_manager_addroute(passed_id) {

    optionsClose(1);
    is_nothing_open = false;

    vessel_manager_get_number(passed_id); 
    // vessel_number_clicked now defined

    route_add_vessel_number_global = vessel_number_clicked

    vessel_manager_getDataFromNumber(vessel_number_clicked)

    document.getElementById("route_add_imo_title").innerText = vessel_selected_name
    document.getElementById("route_add_box").style.left = "10px"; 
    route_add_box_position = 2;

    document.getElementById("route_add_textbox").value = "";

    document.getElementById("route_add_start_date_input").value = "";
    document.getElementById("route_add_arrival_date_input").value = "";
    document.getElementById("route_add_name_input").value = "";
    document.getElementById("route_add_start_input").value = "";
    document.getElementById("route_add_destination_input").value = "";

    document.getElementById("route_add_start_input").readOnly = false;
    document.getElementById("route_add_start_input").disabled = false;
    document.getElementById("route_add_destination_input").readOnly = false;
    document.getElementById("route_add_destination_input").disabled = false;
    document.getElementById("route_add_port_id_start").value = "";
    document.getElementById("route_add_port_id_destination").value = "";
    document.getElementById("cross-btn-start-new").style.display = "none";
    document.getElementById("cross-btn-destination-new").style.display = "none";
    document.getElementById("route_create_risk_area_sel").selectedIndex = 0;

}




function change_low_edit() {
    risk_rating_edit.style.backgroundColor = '#38cccc';
    risk_text_edit.innerText = "LOW"
}

function change_moderate_edit() {
    risk_rating_edit.style.backgroundColor = '#a0cc04';
    risk_text_edit.innerText = "MODERATE"
}

function change_substantial_edit() {
    risk_rating_edit.style.backgroundColor = '#ffc404';
    risk_text_edit.innerText = "SUBSTANTIAL"
}

function change_high_edit() {
    risk_rating_edit.style.backgroundColor = '#ff6404';
    risk_text_edit.innerText = "HIGH"
}

function change_extreme_edit() {
    risk_rating_edit.style.backgroundColor = '#e81c24';
    risk_text_edit.innerText = "EXTREME"
}
change_low_edit()
document.getElementById("radio_1_edit").checked = true;


function change_low_add() {

    risk_rating_add.style.backgroundColor = '#38cccc';
    risk_text_add.innerText = "LOW"
}

function change_moderate_add() {
    risk_rating_add.style.backgroundColor = '#a0cc04';
    risk_text_add.innerText = "MODERATE"
}

function change_substantial_add() {
    risk_rating_add.style.backgroundColor = '#ffc404';
    risk_text_add.innerText = "SUBSTANTIAL"
}

function change_high_add() {
    risk_rating_add.style.backgroundColor = '#ff6404';
    risk_text_add.innerText = "HIGH"
}

function change_extreme_add() {
    risk_rating_add.style.backgroundColor = '#e81c24';
    risk_text_add.innerText = "EXTREME"
}
change_low_add()
document.getElementById("radio_1_add").checked = true;



var radio_value_edit = "";
function get_radio_value_edit() {

    if (document.getElementById("radio_1_edit").checked == true) {
        radio_value_edit = 1;
    }

    else if (document.getElementById("radio_2_edit").checked == true) {
        radio_value_edit = 2;
    }

    else if (document.getElementById("radio_3_edit").checked == true) {
        radio_value_edit = 3;
    }

    else if (document.getElementById("radio_4_edit").checked == true) {
        radio_value_edit = 4;
    }

    else if (document.getElementById("radio_5_edit").checked == true) {
        radio_value_edit = 5;
    }

}


var radio_value_add = "";
function get_radio_value_add() {

    if (document.getElementById("radio_1_add").checked == true) {
        radio_value_add = 1;
    }

    else if (document.getElementById("radio_2_add").checked == true) {
        radio_value_add = 2;
    }

    else if (document.getElementById("radio_3_add").checked == true) {
        radio_value_add = 3;
    }

    else if (document.getElementById("radio_4_add").checked == true) {
        radio_value_add = 4;
    }

    else if (document.getElementById("radio_5_add").checked == true) {
        radio_value_add = 5;
    }

}





var alerts_total_lines = 0;
function alerts_console_insert_line(vessel_imo, vessel_name, inside_dmz, inside_route) {

    alerts_total_lines++

    var alert_line = document.createElement("div");
        alert_line.setAttribute("class", "alert_table_line");
        alert_line.setAttribute("id", "alert_line_" + alerts_total_lines);
        document.getElementById("alerts_table_body_id").appendChild(alert_line);



    var alert_cell_1 = document.createElement("div");
        alert_cell_1.setAttribute("class", "alert_table_cell");
        alert_cell_1.setAttribute("id", "alert_cell_imo_" + alerts_total_lines);
        document.getElementById("alert_line_" + alerts_total_lines).appendChild(alert_cell_1)


    var alert_text_1 = document.createElement("p");
        alert_text_1.setAttribute("class", "alert_cell_text");
        alert_text_1.setAttribute("id", "alert_text_imo_" + alerts_total_lines);
        alert_text_1.innerText = "";
        document.getElementById("alert_cell_imo_" + alerts_total_lines).appendChild(alert_text_1)  



    var alert_cell_2 = document.createElement("div");
        alert_cell_2.setAttribute("class", "alert_table_cell");
        alert_cell_2.setAttribute("id", "alert_cell_name_" + alerts_total_lines);
        document.getElementById("alert_line_" + alerts_total_lines).appendChild(alert_cell_2)

    var alert_text_2 = document.createElement("p");
        alert_text_2.setAttribute("class", "alert_cell_text");
        alert_text_2.setAttribute("id", "alert_text_name_" + alerts_total_lines);
        alert_text_2.innerText = "";
        document.getElementById("alert_cell_name_" + alerts_total_lines).appendChild(alert_text_2)




    var alert_cell_3 = document.createElement("div");
        alert_cell_3.setAttribute("class", "alert_table_cell_light");
        alert_cell_3.setAttribute("id", "alert_cell_ais_" + alerts_total_lines);
        document.getElementById("alert_line_" + alerts_total_lines).appendChild(alert_cell_3)

    var alert_text_3 = document.createElement("div");
        alert_text_3.type = "checkbox";
        alert_text_3.setAttribute("class", "alert_light");
        alert_text_3.setAttribute("id", "alert_checkbox_ais_" + alerts_total_lines);
        alert_text_3.setAttribute("data-imo", vessel_imo);
        alert_text_3.setAttribute("data-name", vessel_name);
        alert_text_3.setAttribute("data-alert_type", "ais");
        document.getElementById("alert_cell_ais_" + alerts_total_lines).appendChild(alert_text_3)   




    var alert_cell_4 = document.createElement("div");
        alert_cell_4.setAttribute("class", "alert_table_cell_light");
        alert_cell_4.setAttribute("id", "alert_cell_speed_" + alerts_total_lines);
        document.getElementById("alert_line_" + alerts_total_lines).appendChild(alert_cell_4)

    var alert_text_4 = document.createElement("div");
        alert_text_4.type = "checkbox";
        alert_text_4.setAttribute("class", "alert_light");
        alert_text_4.setAttribute("id", "alert_checkbox_speed_" + alerts_total_lines);
        alert_text_4.setAttribute("data-imo", vessel_imo);
        alert_text_4.setAttribute("data-name", vessel_name);
        alert_text_4.setAttribute("data-alert_type", "speed");
        document.getElementById("alert_cell_speed_" + alerts_total_lines).appendChild(alert_text_4)   




    var alert_cell_5 = document.createElement("div");
        alert_cell_5.setAttribute("class", "alert_table_cell_light");
        alert_cell_5.setAttribute("id", "alert_cell_dmz_" + alerts_total_lines);
        document.getElementById("alert_line_" + alerts_total_lines).appendChild(alert_cell_5)

    var alert_text_5 = document.createElement("div");
        alert_text_5.type = "checkbox";
        alert_text_5.setAttribute("class", "alert_light");
        alert_text_5.setAttribute("id", "alert_checkbox_dmz_" + alerts_total_lines);
        alert_text_5.setAttribute("data-imo", vessel_imo);
        alert_text_5.setAttribute("data-name", vessel_name);
        alert_text_5.setAttribute("data-alert_type", "dmz");
        document.getElementById("alert_cell_dmz_" + alerts_total_lines).appendChild(alert_text_5)   




    var alert_cell_6 = document.createElement("div");
        alert_cell_6.setAttribute("class", "alert_table_cell_light");
        alert_cell_6.setAttribute("id", "alert_cell_route_" + alerts_total_lines);
        document.getElementById("alert_line_" + alerts_total_lines).appendChild(alert_cell_6)

    var alert_text_6 = document.createElement("div");
        alert_text_6.type = "checkbox";
        alert_text_6.setAttribute("class", "alert_light");
        alert_text_6.setAttribute("id", "alert_checkbox_route_" + alerts_total_lines);
        alert_text_6.setAttribute("data-imo", vessel_imo);
        alert_text_6.setAttribute("data-name", vessel_name);
        alert_text_6.setAttribute("data-alert_type", "route");
        document.getElementById("alert_cell_route_" + alerts_total_lines).appendChild(alert_text_6)      




    if (inside_dmz == 1) { // alert_cell_imo_
        document.getElementById("alert_line_" + alerts_total_lines).style.backgroundColor = "#ffabb3"
    }

    else if (inside_route == 1) {
        document.getElementById("alert_line_" + alerts_total_lines).style.backgroundColor = "#affacc"
    }

    else {
        // do nothing
    }

}



function alerts_console_retrieve_lines() {

    // clear all alert lines()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    ajax_request.open('POST', '' + app_root + '/alerts_console/alerts_console_request.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {

            alert_clear()

            // console.log(this.responseText);

            var alerts_returned_data = this.responseText

            var alerts_console_array = alerts_returned_data.split(',')

            var alerts_lines_to_load = alerts_console_array.length / 14;

            for (let x = 0; x < alerts_lines_to_load; x++) {

                var vessel_number = alerts_console_array[14*x + 0]
                var vessel_imo = alerts_console_array[14*x + 1]
                var vessel_name = alerts_console_array[14*x + 2]
                var vessel_token = alerts_console_array[14*x + 3]
                var ais_alerts = alerts_console_array[14*x + 4]
                var speed_alerts = alerts_console_array[14*x + 5]
                var polygon_alerts = alerts_console_array[14*x + 6]
                var route_alerts = alerts_console_array[14*x + 7]
                var ais_alerts_time = alerts_console_array[14*x + 8]
                var speed_alerts_time = alerts_console_array[14*x + 9]
                var polygon_alerts_time = alerts_console_array[14*x + 10]
                var route_alerts_time = alerts_console_array[14*x + 11]
                var inside_dmz = alerts_console_array[14*x + 12]
                var inside_route = alerts_console_array[14*x + 13]

                if (ais_alerts == 1 || speed_alerts == 1 || polygon_alerts == 1 || route_alerts == 1) { // checks if any alert value is set to 1

                    alerts_console_insert_line(vessel_imo, vessel_name, inside_dmz, inside_route);

                    var alert_text_imo = document.getElementById("alert_text_imo_" + alerts_total_lines)
                    alert_text_imo.innerText = vessel_imo;

                    var alert_text_name = document.getElementById("alert_text_name_" + alerts_total_lines)
                    var alert_name_link = document.createElement('a'); 
                    alert_name_link.innerText = vessel_name;
                    // alert_name_link.setAttribute('href', parent_folder + '/monitoring_page.php?alert_type=0&token='+vessel_token+'');
                    alert_name_link.setAttribute("id", "a_href_" + alerts_total_lines);
                    alert_name_link.setAttribute('data', vessel_number);
                    alert_name_link.setAttribute('href', '#');
                    alert_name_link.setAttribute("onclick", "vessel_manager_view(this.id)");
                    alert_text_name.appendChild(alert_name_link)

                    var alert_text_ais = document.getElementById("alert_checkbox_ais_" + alerts_total_lines)
                    if (ais_alerts == 1) {
                        alert_text_ais.setAttribute('onclick', 'alert_action_clicked(this.id)');
                        alert_text_ais.setAttribute('title', ais_alerts_time);
                        alert_text_ais.classList.add('alert_red_button_class');
                    }
                    else if (ais_alerts == 2) {
                        alert_text_ais.classList.add('alert_green_button_class');
                    }


                    var alert_text_speed = document.getElementById("alert_checkbox_speed_" + alerts_total_lines)
                    if (speed_alerts == 1) {
                        alert_text_speed.setAttribute('onclick', 'alert_action_clicked(this.id)');
                        alert_text_speed.setAttribute('title', speed_alerts_time);
                        alert_text_speed.classList.add('alert_red_button_class');
                    }
                    else if (speed_alerts == 2) {
                        alert_text_speed.classList.add('alert_green_button_class');
                    }


                    var alert_text_dmz = document.getElementById("alert_checkbox_dmz_" + alerts_total_lines)
                    if (polygon_alerts == 1) {
                        alert_text_dmz.setAttribute('onclick', 'alert_action_clicked(this.id)');
                        alert_text_dmz.setAttribute('title', polygon_alerts_time);
                        alert_text_dmz.classList.add('alert_red_button_class');
                    }
                    else if (polygon_alerts == 2) {
                        alert_text_dmz.classList.add('alert_green_button_class');
                    }


                    var alert_text_route = document.getElementById("alert_checkbox_route_" + alerts_total_lines)
                    if (route_alerts == 1) {
                        alert_text_route.setAttribute('onclick', 'alert_action_clicked(this.id)');
                        alert_text_route.setAttribute('title', route_alerts_time);
                        alert_text_route.classList.add('alert_red_button_class');
                    }
                    else if (route_alerts == 2) {
                        alert_text_route.classList.add('alert_green_button_class');
                    }


                }

                else {

                    // dont insert this rows data, as the vessel is not in any danger

                }

            }
    
        }
    }
    ajax_request.send(data_to_send);

}
alerts_console_retrieve_lines()

function alert_clear() {

    // console.log("alert_clear()")

    for (let x = 1; x <= alerts_total_lines; x++) {

        if (document.getElementById("alert_line_" + x) !== null) {

            var alert_line_to_clear = document.getElementById("alert_line_" + x);

            alert_line_to_clear.remove();


        }
    }

    alerts_total_lines = 0
}


var console_shown = false
// function toggleAlerts() {
//   const alertBox = document.getElementById("alert_console_box");
//   const isHidden = alertBox.style.display === 'none' || alertBox.style.display === '';

//   closeAllPanels();

//   if (isHidden) {
//     alertBox.style.display = 'block';
//     console_shown = true;
//   }
// }


function toggleAlertsNew() {
  const consoleContainer = document.getElementById('alert_console_container');

  // If already visible, hide it
  if (consoleContainer.style.display === 'block') {
    consoleContainer.style.display = 'none';
  } else {
    // Hide other panels first
    closeAllPanels();

    // Then show the alert console
    consoleContainer.style.display = 'block';
  }
}


function alert_action_clicked(button_id) {

    var button_clicked = document.getElementById(button_id)

    var vessel_imo = button_clicked.getAttribute("data-imo")
    var vessel_name = button_clicked.getAttribute("data-name")
    var alert_type = button_clicked.getAttribute("data-alert_type")

    let prompt_text = "Do you want to action " + alert_type + " alerts for Vessel: " + vessel_name + "?" + "\n\n" + "Action Log Text:";
    var user_response = prompt(prompt_text)

    if (user_response !== null && user_response !== "") {

        alert_action_confirmed(vessel_imo, alert_type, user_response)

    } 

    else {
        // do nothing else if cancelled
    }


}


function alert_action_confirmed(vessel_imo, alert_type, user_response) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_imo=' + vessel_imo
    + '&alert_type=' + alert_type
    + '&user_response=' + user_response
    ajax_request.open('POST', '' + app_root + '/alerts_console/alerts_action_confirmed.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {

            console.log(this.responseText);
            refresh_alerts()
        }
    }
    ajax_request.send(data_to_send);

}



function refresh_alerts() {
    alerts_console_retrieve_lines()
}
setInterval(refresh_alerts, 300000); // refreshes alerts at 5 minute intervals (300,000 milliseconds)


function refresh_vessels() {
    load_vessel_data()
}
setInterval(refresh_vessels, 300000); // refreshes vessels at 5 minute intervals (300,000 milliseconds)



function route_add_update_visual() {

    route_convert_coordinates("route_add_textbox")
    map.setLayoutProperty('route_line', 'visibility', 'visible');
    route_update_line()

}

function route_edit_update_visual() {

    route_convert_coordinates("route_edit_textbox")
    map.setLayoutProperty('route_line', 'visibility', 'visible');
    route_update_line()

}

var global_route_coordinates = []; // this array will hold the raw decimal converted values
function route_convert_coordinates(input_box) {

    var route_input_box = document.getElementById(input_box);
    var text_to_convert = route_input_box.innerText; // gets the text the user has entered in the coordinate box

    var text_string = "";
    global_route_coordinates = []; // resets array incase it has already been defined



    // Decimal Conversion
    if (text_to_convert.includes("Â°") == false) { // if no Â° symbol, the text must be in DD format

        // alert("text is DD");

        text_to_convert = text_to_convert.replace(/\s+/g, ":"); // replaces any length of \s whitespace with a single :
        text_to_convert = text_to_convert.replace(/^:*/, ""); // replaces all : at start of string with ""
        text_to_convert = text_to_convert.replace(/:*$/, ""); // replaces all : at end of string with ""

        var single_coordinate_array = text_to_convert.split(":"); // splits the newly segmented string into an array, between every :

        for (let x = 0; x < single_coordinate_array.length; x+=2) { // increments by 2 each time

            if (x+1 == single_coordinate_array.length) {
                text_string = text_string + '<span id="bold_test">' + single_coordinate_array[x] + '</span>' + '  '
            }

            else {

                var latitude_raw = single_coordinate_array[x]
                var longitude_raw = single_coordinate_array[x+1]

                var latitude_decimal = Number(single_coordinate_array[x]).toFixed(5); // conversion equation removes front 0s and limits decimal length to 5 decimal places
                var longitude_decimal = Number(single_coordinate_array[x+1]).toFixed(5);

                if (latitude_decimal > -90 && latitude_decimal < 90) { // if lat is correct, add it without error marker
                    text_string = text_string + latitude_decimal + '  '
                }
                else { // if lat is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + latitude_raw + '</span>' + '  '
                }


                if (longitude_decimal > -180 && longitude_decimal < 180) { // if long is correct, add it without error marker
                    text_string = text_string + longitude_decimal + '<br>'
                }
                else { // if long is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + longitude_raw + '</span>' + '<br>'
                }


                if (latitude_decimal > -90 && latitude_decimal < 90 && longitude_decimal > -180 && longitude_decimal < 180) { // if both coordinates are correct, add them to creation array to be displayed on map
                    global_route_coordinates.push([latitude_decimal, longitude_decimal])
                }
                else {
                    // do nothing, dont try to display the coordinates on map
                }

            }

        }

    }












    // Degrees Minutes Conversion
    else if (text_to_convert.includes("Â°") == true && text_to_convert.includes(".") == true && text_to_convert.includes("\"") == false) { // if Â° and . but no " the text must be in DMS format
        
        // alert("text is DM");
        
        text_to_convert = text_to_convert.replace(/\s/g, ""); // replaces all \s whitespace with ""

        text_to_convert = text_to_convert.replace(/N/g, "N:"); // replaces all N with N:
        text_to_convert = text_to_convert.replace(/E/g, "E:"); // replaces all E with E:
        text_to_convert = text_to_convert.replace(/S/g, "S:"); // replaces all S with S:
        text_to_convert = text_to_convert.replace(/W/g, "W:"); // replaces all W with W:

        text_to_convert = text_to_convert.replace(/:*$/, ""); // replaces all : at end of string with ""

        var single_coordinate_array = text_to_convert.split(":"); // splits the newly segmented string into an array, between every :
        var amount_of_coordinates = single_coordinate_array.length;

        var evaluated_coordinate_array = [];
        for (let x = 0; x < amount_of_coordinates; x++) { // converts single_coordinate_array to evaluated_coordinate_array

            var coordinate_dm = single_coordinate_array[x];
            var coordinate_dm_array = coordinate_dm.replace(/Â°/g, ":").replace(/\'/g, ":").split(":"); // replaces the Â° ' " symbols with : breaks to split to array, and calculate the raw value of the DM coordinate
            var coordinate_correct = "";
            var coordinate_type = "";

            // DM Latitude Check
            if (coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "N" || coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "S") { // validates the coordinate is Latitude and contains 5 segments

                coordinate_type = "latitude";

                var latitude_degrees = Number(coordinate_dm_array[0]); // splits latitude into sections, for use in conversion equation
                var latitude_minutes = Number(coordinate_dm_array[1]/60);
                var latitude_direction = Number(coordinate_dm_array[2].replace(/N/g, "1").replace(/S/g, "-1")); // replaces N with 1 and S with -1, for use in conversion equation
                
                var coordinate_raw = Number((latitude_degrees + latitude_minutes) * latitude_direction).toFixed(5); // conversion equation

                if (coordinate_raw >= -90 && coordinate_raw <= 90 && coordinate_dm_array[1] >= 0 && coordinate_dm_array[1] <= 60) { // validates all the lat are within the 180 bounds, and the minutes are within [0,60] bounds
                     coordinate_correct = true // latitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // dm Longitude Check
            else if (coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "E" || coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "W") {

                coordinate_type = "longitude";

                var longitude_degrees = Number(coordinate_dm_array[0]);
                var longitude_minutes = Number(coordinate_dm_array[1]/60);
                var longitude_direction = Number(coordinate_dm_array[2].replace(/E/g, "1").replace(/W/g, "-1"));

                var coordinate_raw = Number((longitude_degrees + longitude_minutes) * longitude_direction).toFixed(5);

                if (coordinate_raw >= -180 && coordinate_raw <= 180 && coordinate_dm_array[1] >= 0 && coordinate_dm_array[1] <= 60) { // validates all the long are within 360 bounds, and the minutes are within [0,60] bounds
                    coordinate_correct = true // longitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // Only occurs if coordinate isnt in Latitude or Longitude format
            else {
                coordinate_type = "undefined"; // only sets these parameters to these values if an error occurs
                coordinate_correct = false;
                var coordinate_raw = "0";
            }

            evaluated_coordinate_array.push([coordinate_dm, coordinate_type, coordinate_correct, coordinate_raw]);

        }

        var text_output_array = [];
        for (let x = 0; x < evaluated_coordinate_array.length; x++) { // converts evaluated_coordinate_array to text_output_array

            if (x+1 == evaluated_coordinate_array.length) { // if x is at the final item in array, add it and dont look at x+1 to prevent errors
                text_output_array.push([evaluated_coordinate_array[x][0]])
            }

            else { // otherwise look normally at x and x+1 pairs

                if (evaluated_coordinate_array[x][1] == "latitude" && evaluated_coordinate_array[x+1][1] == "longitude") { // if lat long pair add them to the array and increment one extra to skip x+1
                    console.log(evaluated_coordinate_array[x][0] + ", " + evaluated_coordinate_array[x+1][0])
                    text_output_array.push([evaluated_coordinate_array[x][0], evaluated_coordinate_array[x][2], evaluated_coordinate_array[x][3], evaluated_coordinate_array[x+1][0], evaluated_coordinate_array[x+1][2], evaluated_coordinate_array[x+1][3]])
                    x++ // increment one extra x to skip x+1
                }

                else { // else just add the single coordinate
                    text_output_array.push([evaluated_coordinate_array[x][0]])
                }

            }
            
        }

        for (let x = 0; x < text_output_array.length; x++) { // converts text_output_array to text_string

            if (text_output_array[x].length == 6) {

                var lat_dm = text_output_array[x][0]
                var lat_correct = text_output_array[x][1]
                var lat_decimal = text_output_array[x][2]
                var long_dm = text_output_array[x][3]
                var long_correct = text_output_array[x][4]
                var long_decimal = text_output_array[x][5]

                if (lat_correct == true) { // if lat is correct, add it without error marker
                    text_string = text_string + lat_dm + '  '
                }
                else { // if lat is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + lat_dm + '</span>' + '  '
                }


                if (long_correct == true) { // if long is correct, add it without error marker
                    text_string = text_string + long_dm + '<br>'
                }
                else { // if long is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + long_dm + '</span>' + '<br>'
                }


                if (lat_correct == true && long_correct == true) { // if both coordinates are correct, add them to creation array to be displayed on map
                    global_route_coordinates.push([lat_decimal, long_decimal])
                }
                else {
                    // do nothing, dont try to display the coordinates on map
                }

            }

            else { // coordinate is by itself on a line, add it with an error marker
                text_string = text_string + '<span id="bold_test">' + text_output_array[x] + '</span>' + '<br>'
            }

        }
    console.log(evaluated_coordinate_array); // console logs the finished conversion array
    console.log(text_output_array)

    }















    // Degrees Minutes Seconds Conversion
    else if (text_to_convert.includes("Â°") == true && text_to_convert.includes("\"") == true) { // if Â° and " the text must be in DMS format
        
        // alert("text is DMS");
        
        text_to_convert = text_to_convert.replace(/\s/g, ""); // replaces all \s whitespace with ""

        text_to_convert = text_to_convert.replace(/N/g, "N:"); // replaces all N with N:
        text_to_convert = text_to_convert.replace(/E/g, "E:"); // replaces all E with E:
        text_to_convert = text_to_convert.replace(/S/g, "S:"); // replaces all S with S:
        text_to_convert = text_to_convert.replace(/W/g, "W:"); // replaces all W with W:

        text_to_convert = text_to_convert.replace(/:*$/, ""); // replaces all : at end of string with ""

        var single_coordinate_array = text_to_convert.split(":"); // splits the newly segmented string into an array, between every :
        var amount_of_coordinates = single_coordinate_array.length;

        var evaluated_coordinate_array = [];
        for (let x = 0; x < amount_of_coordinates; x++) { // converts single_coordinate_array to evaluated_coordinate_array

            var coordinate_dms = single_coordinate_array[x];
            var coordinate_dms_array = coordinate_dms.replace(/Â°/g, ":").replace(/\'/g, ":").replace(/\"/g, ":").split(":"); // replaces the Â° ' " symbols with : breaks to split to array, and calculate the raw value of the DMS coordinate
            var coordinate_correct = "";
            var coordinate_type = "";

            // DMS Latitude Check
            if (coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "N" || coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "S") { // validates the coordinate is Latitude and contains 5 segments

                coordinate_type = "latitude";

                var latitude_degrees = Number(coordinate_dms_array[0]); // splits latitude into sections, for use in conversion equation
                var latitude_minutes = Number(coordinate_dms_array[1]/60);
                var latitude_seconds = Number(coordinate_dms_array[2]/3600);
                var latitude_direction = Number(coordinate_dms_array[3].replace(/N/g, "1").replace(/S/g, "-1")); // replaces N with 1 and S with -1, for use in conversion equation
                
                var coordinate_raw = Number((latitude_degrees + latitude_minutes + latitude_seconds) * latitude_direction).toFixed(5); // conversion equation

                if (coordinate_raw >= -90 && coordinate_raw <= 90 && coordinate_dms_array[1] >= 0 && coordinate_dms_array[1] <= 60 && coordinate_dms_array[2] >= 0 && coordinate_dms_array[2] <= 60) { // validates all the lat are within the 180 bounds, and the minutes seconds are within [0,60] bounds
                    coordinate_correct = true // latitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // DMS Longitude Check
            else if (coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "E" || coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "W") {

                coordinate_type = "longitude";

                var longitude_degrees = Number(coordinate_dms_array[0]);
                var longitude_minutes = Number(coordinate_dms_array[1]/60);
                var longitude_seconds = Number(coordinate_dms_array[2]/3600);
                var longitude_direction = Number(coordinate_dms_array[3].replace(/E/g, "1").replace(/W/g, "-1"));

                var coordinate_raw = Number((longitude_degrees + longitude_minutes + longitude_seconds) * longitude_direction).toFixed(5);

                if (coordinate_raw >= -180 && coordinate_raw <= 180 && coordinate_dms_array[1] >= 0 && coordinate_dms_array[1] <= 60 && coordinate_dms_array[2] >= 0 && coordinate_dms_array[2] <= 60) { // validates all the long are within 360 bounds, and the minutes seconds are within [0,60] bounds
                    coordinate_correct = true // longitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // Only occurs if coordinate isnt in Latitude or Longitude format
            else {
                coordinate_type = "undefined"; // only sets these parameters to these values if an error occurs
                coordinate_correct = false;
                var coordinate_raw = "0";
            }

            evaluated_coordinate_array.push([coordinate_dms, coordinate_type, coordinate_correct, coordinate_raw]);

        }

        var text_output_array = [];
        for (let x = 0; x < evaluated_coordinate_array.length; x++) { // converts evaluated_coordinate_array to text_output_array

            if (x+1 == evaluated_coordinate_array.length) { // if x is at the final item in array, add it and dont look at x+1 to prevent errors
                text_output_array.push([evaluated_coordinate_array[x][0]])
            }

            else { // otherwise look normally at x and x+1 pairs

                if (evaluated_coordinate_array[x][1] == "latitude" && evaluated_coordinate_array[x+1][1] == "longitude") { // if lat long pair add them to the array and increment one extra to skip x+1
                    console.log(evaluated_coordinate_array[x][0] + ", " + evaluated_coordinate_array[x+1][0])
                    text_output_array.push([evaluated_coordinate_array[x][0], evaluated_coordinate_array[x][2], evaluated_coordinate_array[x][3], evaluated_coordinate_array[x+1][0], evaluated_coordinate_array[x+1][2], evaluated_coordinate_array[x+1][3]])
                    x++
                }

                else { // else just add the single coordinate
                    text_output_array.push([evaluated_coordinate_array[x][0]])
                }

            }
            
        }

        for (let x = 0; x < text_output_array.length; x++) { // converts text_output_array to text_string

            if (text_output_array[x].length == 6) {

                var lat_dms = text_output_array[x][0]
                var lat_correct = text_output_array[x][1]
                var lat_decimal = text_output_array[x][2]
                var long_dms = text_output_array[x][3]
                var long_correct = text_output_array[x][4]
                var long_decimal = text_output_array[x][5]

                if (lat_correct == true) { // if lat is correct, add it without error marker
                    text_string = text_string + lat_dms + '  '
                }
                else { // if lat is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + lat_dms + '</span>' + '  '
                }


                if (long_correct == true) { // if long is correct, add it without error marker
                    text_string = text_string + long_dms + '<br>'
                }
                else { // if long is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + long_dms + '</span>' + '<br>'
                }


                if (lat_correct == true && long_correct == true) { // if both coordinates are correct, add them to creation array to be displayed on map
                    global_route_coordinates.push([lat_decimal, long_decimal])
                }
                else {
                    // do nothing, dont try to display the coordinates on map
                }

            }

            else { // coordinate is by itself on a line, add it with an error marker
                text_string = text_string + '<span id="bold_test">' + text_output_array[x] + '</span>' + '<br>'
            }
            console.log(evaluated_coordinate_array); // console logs the finished conversion array
            console.log(text_output_array)
        }


    }







    else {
        alert("The coordinates do not belong to any of the shown formats, please check them and try again");

    }


    route_input_box.innerHTML = text_string; // puts appended (bold/wavy underline) text back into contenteditable div

    console.log(global_route_coordinates); // console logs the finished conversion array

}

document.getElementById("route_add_name_input").addEventListener("input", verify_create_route_has_correct_data);
document.getElementById("route_add_start_date_input").addEventListener("input", verify_create_route_has_correct_data);
document.getElementById("route_add_arrival_date_input").addEventListener("input", verify_create_route_has_correct_data);
document.getElementById("route_add_start_input").addEventListener("input", verify_create_route_has_correct_data);
document.getElementById("route_add_destination_input").addEventListener("input", verify_create_route_has_correct_data);
// document.getElementById("route_create_risk_area_sel").addEventListener("input", verify_create_route_has_correct_data);

function verify_create_route_has_correct_data() {

    var route_name = document.getElementById("route_add_name_input").value
    var route_start_date = document.getElementById("route_add_start_date_input").value
    var route_arrival_date = document.getElementById("route_add_arrival_date_input").value
    var route_start_location = document.getElementById("route_add_start_input").value
    // var route_destination_location = document.getElementById("route_add_destination_input").value
    var port_id_start = document.getElementById("route_add_port_id_start").value;
    var port_id_destination = document.getElementById("route_add_port_id_destination").value;
    var route_tra = (document.getElementById("route_create_risk_area_sel").value != "") ? true : false;

    if (route_name && route_start_date && route_arrival_date && route_start_location && ((port_id_start === "7602" && port_id_destination === "7603" && route_tra) || (port_id_start && port_id_destination && route_tra == ""))) {
        enable_create_route_button()
    }

    else {
        disable_create_route_button()
    }

}


function disable_create_route_button() {
    document.getElementById("route_add_save_button").disabled = true;
    document.getElementById("route_add_save_button").style.cursor = "not-allowed";
}


function enable_create_route_button() {
    document.getElementById("route_add_save_button").disabled = false;
    document.getElementById("route_add_save_button").style.cursor = "pointer";
}




function route_update_line() {

    console.log(global_route_coordinates)
    // global_route_coordinates already defined as global variable
    var updated_coordList = [];

    for (var x = 0; x < global_route_coordinates.length; x++) {

        var latitude = global_route_coordinates[x][0]; // converts string to number, this is needed so the array doesnt quote the values
        var longitude = global_route_coordinates[x][1];

        updated_coordList[x] = [longitude, latitude];
    }

    var map_route_line = map.getSource('route_line');

    map_route_line.setData({
        'type': 'Feature',
        'properties': {},
        'geometry': {
        'type': 'LineString',
        'coordinates': updated_coordList
        }
    });

    map.flyTo({center: updated_coordList[0], zoom:4});


    
}













function port_manager_letter_selected() {
    document.getElementById("port_search_input").value = ""
    port_manager_retrieve_data()
}




var global_port_manager_data = ""; // this will be used to gather and update the data, for use in other functions such as the search function
function port_manager_retrieve_data() {

    var letter_selected = document.getElementById("port_letter_selected").value

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + '&letter_selected=' + letter_selected
    ajax_request.open('POST', '' + app_root + '/ports/port_manager_request.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);

            global_port_manager_data = this.responseText;

            if (global_port_manager_data === "") {
                // do nothing if data returned is <empty string>
            }

            else {
                port_manager_load_lines();
            }

        }
    
    }
    ajax_request.send(data_to_send);

}



document.getElementById("port_search_box").addEventListener("input", port_manager_load_lines);

function port_manager_load_lines() {

    var port_searched_name = document.getElementById("port_search_input").value

    var first_char = port_searched_name.slice(0, 1).toUpperCase()
    var a_z_check = new RegExp("^[A-Z].*")
    var a_z_result = a_z_check.test(first_char)
    var dropdown_value = document.getElementById("port_letter_selected").value

    if (a_z_result == true && first_char != dropdown_value) {

        document.getElementById("port_letter_selected").value = first_char
        port_manager_retrieve_data()
        return;

    }

    else {
        // do nothing
    }

    var port_searched_chars = port_searched_name.length // search this many characters of each port name (length of text entered)

    var port_manager_array = global_port_manager_data.split(',;')
    // console.log(port_manager_array)

    var port_lines_to_load = port_manager_array.length / 5;

    port_manager_clear_lines();
    for (let x = 0; x < port_lines_to_load; x++) {

        var port_id = port_manager_array[5*x + 0]
        var port_name = port_manager_array[5*x + 1]
        var country = port_manager_array[5*x + 2]
        var latitude_decimal = port_manager_array[5*x + 3]
        var longitude_decimal = port_manager_array[5*x + 4]

        var latitude_dms = lat_to_dms(latitude_decimal)
        var longitude_dms = long_to_dms(longitude_decimal)

        if (port_name.slice(0, port_searched_chars).toLowerCase() == port_searched_name.toLowerCase()) {

            port_manager_insert_line(port_id, port_name, country, latitude_dms, longitude_dms, latitude_decimal, longitude_decimal);

        }

        else {
            // do nothing
        }

    }
}




var port_total_lines = 0;
function port_manager_insert_line(port_id, port_name, country, latitude_dms, longitude_dms, latitude_decimal, longitude_decimal) {

    //console.log("route_manager_insert_line()");

    port_total_lines++

    var port_line = document.createElement("div");
        port_line.setAttribute("class", "application_table_line");
        port_line.setAttribute("id", "port_line_" + port_total_lines);
        document.getElementById("port_table_body_id").appendChild(port_line);



    var port_cell_id = document.createElement("div");
        port_cell_id.setAttribute("class", "port_table_cell");
        port_cell_id.setAttribute("id", "port_cell_id_" + port_total_lines);
        document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_id)

    var port_text_id = document.createElement("p");
        port_text_id.setAttribute("class", "application_cell_text");
        port_text_id.setAttribute("id", "port_text_id_" + port_total_lines);
        port_text_id.innerText = port_id;
        document.getElementById("port_cell_id_" + port_total_lines).appendChild(port_text_id) 



    var port_cell_name = document.createElement("div");
        port_cell_name.setAttribute("class", "port_table_cell");
        port_cell_name.setAttribute("id", "port_cell_name_" + port_total_lines);
        document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_name)

    var port_text_name = document.createElement("p");
        port_text_name.setAttribute("class", "application_cell_text");
        port_text_name.setAttribute("id", "port_text_name_" + port_total_lines);
        port_text_name.innerText = port_name;
        document.getElementById("port_cell_name_" + port_total_lines).appendChild(port_text_name) 



    var port_cell_country = document.createElement("div");
        port_cell_country.setAttribute("class", "port_table_cell");
        port_cell_country.setAttribute("id", "port_cell_country_" + port_total_lines);
        document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_country)

    var port_text_country = document.createElement("p");
        port_text_country.setAttribute("class", "application_cell_text");
        port_text_country.setAttribute("id", "port_text_country_" + port_total_lines);
        port_text_country.innerText = country;
        document.getElementById("port_cell_country_" + port_total_lines).appendChild(port_text_country) 



    var port_cell_latitude = document.createElement("div");
        port_cell_latitude.setAttribute("class", "port_table_cell");
        port_cell_latitude.setAttribute("id", "port_cell_latitude_" + port_total_lines);
        document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_latitude)

    var port_text_latitude = document.createElement("p");
        port_text_latitude.setAttribute("class", "application_cell_text");
        port_text_latitude.setAttribute("id", "port_text_latitude_" + port_total_lines);
        port_text_latitude.innerText = latitude_dms;
        document.getElementById("port_cell_latitude_" + port_total_lines).appendChild(port_text_latitude)   



    var port_cell_longitude = document.createElement("div");
        port_cell_longitude.setAttribute("class", "port_table_cell");
        port_cell_longitude.setAttribute("id", "port_cell_longitude_" + port_total_lines);
        document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_longitude)

    var port_text_longitude = document.createElement("p");
        port_text_longitude.setAttribute("class", "application_cell_text");
        port_text_longitude.setAttribute("id", "port_text_longitude_" + port_total_lines);
        port_text_longitude.innerText = longitude_dms;
        document.getElementById("port_cell_longitude_" + port_total_lines).appendChild(port_text_longitude)   



    var port_cell_view = document.createElement("div");
        port_cell_view.setAttribute("class", "port_table_cell_button");
        port_cell_view.setAttribute("id", "port_cell_view_" + port_total_lines);
        document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_view)

    var port_picture_view = document.createElement("div");
        port_picture_view.setAttribute("class", "application_view_button");
        port_picture_view.setAttribute("id", "port_picture_view_" + port_total_lines);
        port_picture_view.setAttribute("data-port_id", port_id);
        port_picture_view.setAttribute("data-port_name", port_name);
        port_picture_view.setAttribute("data-latitude_dms", latitude_dms);
        port_picture_view.setAttribute("data-longitude_dms", longitude_dms);
        port_picture_view.setAttribute("data-latitude_decimal", latitude_decimal);
        port_picture_view.setAttribute("data-longitude_decimal", longitude_decimal);
        port_picture_view.setAttribute("onclick", "port_manager_view_clicked(this.id)");
        document.getElementById("port_cell_view_" + port_total_lines).appendChild(port_picture_view) 


    if (resource_permissions.canEditPorts){
        var port_cell_edit = document.createElement("div");
            port_cell_edit.setAttribute("class", "port_table_cell_button");
            port_cell_edit.setAttribute("id", "port_cell_edit_" + port_total_lines);
            document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_edit)

        var port_picture_edit = document.createElement("div");
            port_picture_edit.setAttribute("class", "application_edit_button");
            port_picture_edit.setAttribute("id", "port_picture_edit_" + port_total_lines);
            port_picture_edit.setAttribute("data-port_id", port_id);
            port_picture_edit.setAttribute("onclick", "port_manager_edit_clicked(this.id)");
            document.getElementById("port_cell_edit_" + port_total_lines).appendChild(port_picture_edit)
    }

    if (resource_permissions.canDeletePorts){
        var port_cell_delete = document.createElement("div");
            port_cell_delete.setAttribute("class", "port_table_cell_button");
            port_cell_delete.setAttribute("id", "port_cell_delete_" + port_total_lines);
            document.getElementById("port_line_" + port_total_lines).appendChild(port_cell_delete)

        var port_picture_delete = document.createElement("div");
            port_picture_delete.setAttribute("class", "application_delete_button");
            port_picture_delete.setAttribute("id", "port_picture_delete_" + port_total_lines);
            port_picture_delete.setAttribute("data-port_id", port_id);
            port_picture_delete.setAttribute("onclick", "port_manager_delete_clicked(this.id)");
            document.getElementById("port_cell_delete_" + port_total_lines).appendChild(port_picture_delete)
    }
}




function port_manager_clear_lines() {

    //console.log("port_manager_clear_lines()");

    for (let x = 0; x <= port_total_lines; x++) {

        if (document.getElementById("port_line_" + x) !== null) {
                
            var line_to_delete = document.getElementById("port_line_" + x)
            line_to_delete.remove()

        }

    }

    port_total_lines = 0;

}


function port_manager_view_clicked(port_view_button_clicked) {

    var port_id = document.getElementById(port_view_button_clicked).getAttribute("data-port_id")
    var port_name = document.getElementById(port_view_button_clicked).getAttribute("data-port_name")
    var latitude_dms = document.getElementById(port_view_button_clicked).getAttribute("data-latitude_dms")
    var longitude_dms = document.getElementById(port_view_button_clicked).getAttribute("data-longitude_dms")
    var latitude_decimal = document.getElementById(port_view_button_clicked).getAttribute("data-latitude_decimal")
    var longitude_decimal = document.getElementById(port_view_button_clicked).getAttribute("data-longitude_decimal")

    optionsClose() // could potentially keep a close button, when clicked returns you to the port page with search box and left menu bar intact
    
    display_port_anchor(port_id, port_name, latitude_dms, longitude_dms, latitude_decimal, longitude_decimal)
    map.flyTo({center: [longitude_decimal, latitude_decimal], zoom:5});

}


var port_on_map_marker = null;
function display_port_anchor(port_id, port_name, latitude_dms, longitude_dms, latitude_decimal, longitude_decimal) {

    if (port_on_map_marker !== null) { // removes the old port marker if it exists
        port_on_map_marker.remove()
    }

    const port_anchor = document.createElement('div');
    port_anchor.style.backgroundImage = 'url(' + document_root + '/assets/anchor.png)';
    port_anchor.style.backgroundSize = 'cover';
    port_anchor.style.backgroundPosition = 'center';
    port_anchor.style.width = '30px';
    port_anchor.style.height = '30px';

    const popup = new mapboxgl.Popup().setHTML("<b>Port ID: </b>"+port_id+"<br>"+"<b>Port Name: </b>"+port_name+"<br>"+"<b>Latitude: </b>"+latitude_dms+"<br>"+"<b>Longitude: </b>"+longitude_dms)

    port_on_map_marker = new mapboxgl.Marker({
        anchor: 'center',
        element: port_anchor,
        rotation: 0
      })
    .setLngLat([longitude_decimal, latitude_decimal])
    .setPopup(popup) // add popup
    .addTo(map);
}


function port_manager_open_create() {

    optionsClose(1);
    is_nothing_open = false;
    open_add_port()

}


function open_add_port() {
    
    document.getElementById("port_add_name_input").value = ""
    document.getElementById("port_add_latitude_input").value = ""
    document.getElementById("port_add_longitude_input").value = ""


    document.getElementById("port_add_box").style.left = "10px";
    port_add_enable_plotting() // means when map is clicked, port coordinate is filled in
}

function close_add_port() {
    document.getElementById("port_add_box").style.left = "-1000px";
    port_add_disable_plotting() // false means when map is clicked, port coordinate is not filled in
}


function open_port_risk_analysis_box() {
    port_risk_analysis_box.style.right = "10px"; 
}


function close_port_risk_analysis_box() {
    port_risk_analysis_box.style.right = "-200vw"; 
}


port_add_plotting_enabled = false;
function port_add_enable_plotting() {
    port_add_plotting_enabled = true
    // enable_crosshair()
}
function port_add_disable_plotting() {
    port_add_plotting_enabled = false
    // enable_grabber()

}


function port_add_preview() {

    var port_name = document.getElementById("port_add_name_input").value
    var latitude_decimal = document.getElementById("port_add_latitude_input").value
    var longitude_decimal = document.getElementById("port_add_longitude_input").value
    var latitude_dms = lat_to_dms(latitude_decimal)
    var longitude_dms = long_to_dms(longitude_decimal)

    if (latitude_decimal > -90 && latitude_decimal < 90 && longitude_decimal > -180 && longitude_decimal < 180) {
        display_port_anchor("", port_name, latitude_dms, longitude_dms, latitude_decimal, longitude_decimal)
        map.flyTo({center: [longitude_decimal, latitude_decimal], zoom:5});
        port_add_disable_plotting()
    }

    else {
        alert("There is an error with one or more of the coordinates, please check they are correct and in decimal format")
    }
}


function port_add_insert_coordinate(lat_raw, long_raw) {

    document.getElementById("port_add_latitude_input").value = Number(lat_raw).toFixed(5)
    document.getElementById("port_add_longitude_input").value = Number(long_raw).toFixed(5)

    var port_name = document.getElementById("port_add_name_input").value
    var latitude_decimal = document.getElementById("port_add_latitude_input").value
    var longitude_decimal = document.getElementById("port_add_longitude_input").value
    var latitude_dms = lat_to_dms(latitude_decimal)
    var longitude_dms = long_to_dms(longitude_decimal)

    if (latitude_decimal > -90 && latitude_decimal < 90 && longitude_decimal > -180 && longitude_decimal < 180) {
        display_port_anchor("", port_name, latitude_dms, longitude_dms, latitude_decimal, longitude_decimal)
    }

}


function port_add_save() {

    var port_name = document.getElementById("port_add_name_input").value
    var country = document.getElementById("port_add_country_input").value
    var latitude = document.getElementById("port_add_latitude_input").value
    var longitude = document.getElementById("port_add_longitude_input").value

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'port_name=' + port_name
    + '&country=' + country
    + '&latitude=' + latitude
    + '&longitude=' + longitude
    ajax_request.open('POST', '' + app_root + '/ports/port_add_save.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            global_port_id_being_edited = this.responseText // sets global_port_id_being_edited to the port_id just created, so when the user adds a risk it saves to this port_id

            alert("Port Added")
            port_manager_retrieve_data()

            optionsClose()
        }
    
    }
    ajax_request.send(data_to_send);

}


function open_edit_port() {
    
    document.getElementById("port_edit_name_input").value = ""
    document.getElementById("port_edit_country_input").value = ""
    document.getElementById("port_edit_latitude_input").value = ""
    document.getElementById("port_edit_longitude_input").value = ""


    document.getElementById("port_edit_box").style.left = "10px";
}


function close_edit_port() {
    document.getElementById("port_edit_box").style.left = "-1000px";
}


var global_port_id_being_edited = "";
function port_manager_edit_clicked(port_edit_button_clicked) {

    optionsClose(1);
    is_nothing_open = false;

    open_edit_port()
    open_port_risk_analysis_box()

    var port_id = document.getElementById(port_edit_button_clicked).getAttribute("data-port_id")
    global_port_id_being_edited = port_id // used to determine which port_id is being edited whilst in the edit menu
    port_load_info()
    port_load_risks()

    // port_risk_reload(port_id)
}


function port_manager_delete_clicked(port_delete_button_clicked) {

  let text = "Do you really want to delete this Port? Press OK to confirm.";

  if (confirm(text) == true) {

    var port_id = document.getElementById(port_delete_button_clicked).getAttribute("data-port_id")

    // console.log(port_id);

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'port_id=' + port_id
    ajax_request.open('POST', '' + app_root + '/ports/port_manager_delete.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            port_manager_retrieve_data()
            alert("Port Deleted")

        }
    
    }
    ajax_request.send(data_to_send);

  } 

  else {
    // do nothing else if cancelled
  }

}


function port_edit_save() {

    var port_id = global_port_id_being_edited
    var port_name = document.getElementById("port_edit_name_input").value
    var country = document.getElementById("port_edit_country_input").value
    var latitude = document.getElementById("port_edit_latitude_input").value
    var longitude = document.getElementById("port_edit_longitude_input").value

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'port_id=' + port_id
    + '&port_name=' + port_name
    + '&country=' + country
    + '&latitude=' + latitude
    + '&longitude=' + longitude
    ajax_request.open('POST', '' + app_root + '/ports/port_edit_save.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            alert("Port Saved")
            close_edit_port()
            close_port_risk_analysis_box()
            fullMenuBox.style.left = "10px";
            port_manager_retrieve_data()
            openPorts()
        }
    
    }
    ajax_request.send(data_to_send);

}


function port_edit_preview() {

    var port_id = global_port_id_being_edited

    var port_name = document.getElementById("port_edit_name_input").value
    var latitude_decimal = document.getElementById("port_edit_latitude_input").value
    var longitude_decimal = document.getElementById("port_edit_longitude_input").value
    var latitude_dms = lat_to_dms(latitude_decimal)
    var longitude_dms = long_to_dms(longitude_decimal)

    if (latitude_decimal > -90 && latitude_decimal < 90 && longitude_decimal > -180 && longitude_decimal < 180) {
        display_port_anchor(port_id, port_name, latitude_dms, longitude_dms, latitude_decimal, longitude_decimal)
        map.flyTo({center: [longitude_decimal, latitude_decimal], zoom:5});
    }

    else {
        alert("There is an error with one or more of the coordinates, please check they are correct and in decimal format")
    }
}









// Admin menu by Chris
var adminMenuElements = {
    // "adminCompanyButton": "#companyMenu",
    // "adminQuestionnaireButton": "#questionnaireMenu",
    // "adminSystemButton": "#systemMenu",
    //"adminIncidentGuidanceButton": "#incidentGuidanceMenu",
    //"adminSystemButton": "#systemMenu"
}

// User menu permission
if (Number(window.privilege) < 2 || Number("0x" + window.permissions[4]) > 0) {
    adminMenuElements["adminUserButton"] = "#userMenu";
}

// Questionnaire menu permission
if (Number(window.privilege) < 2 || Number("0x" + window.permissions[0]) > 0 || Number("0x" + window.permissions[1]) > 0) {
    adminMenuElements["adminQuestionnaireButton"] = "#questionnaireMenu";
}

// Incident Guidance menu permission
if (Number(window.privilege) < 2 || Number("0x" + window.permissions[3]) > 0) {
    adminMenuElements["adminIncidentGuidanceButton"] = "#incidentGuidanceMenu";
}

if (window.privilege === 0) {
    adminMenuElements["adminSystemButton"] = "#systemMenu";
}

var currentAdminMenuEntry = Object.keys(adminMenuElements)[0];

function openAdmin() {
    optionsClose();
    greyOut.style.display = "block";
    if (userReturnButton != null) {
        userReturnButton.style.display = 'none';
    }
    console.log(`Active menu entry: ${currentAdminMenuEntry}`);
    document.getElementById(currentAdminMenuEntry).click();
    // document.getElementById(currentAdminMenuEntry).classList.add("activeMenuButton");
    // document.querySelector(adminMenuElements[currentAdminMenuEntry]).style.display = 'flex';
    // companyReturnButton.style.display = 'none';
}

function closeAdmin() {
    closeAdminMenus();
    greyOut.style.display = "";
}

function closeAdminMenus() {
    // Read company menu permission
    // if (document.getElementById("companyMenu")) {
    //     closeAddCompany();
    //     closeEditCompany();
    // }
    // Read user menu permission
    // if (document.getElementById("userMenu")) {
    //     closeAddUser();
    //     closeEditUser();
    // }

    // const adminMainMenuChildren = document.getElementById("adminMainMenu").children;
    //
    // for (let i = 0; i < adminMainMenuChildren.length; i++) {
    //     adminMainMenuChildren[i].style.display = 'none';
    // }

    for (item in adminMenuElements) {
        const element = document.querySelector(adminMenuElements[item]);
        
        if (element == null) continue;

        element.style.display = 'none';
    }
}

function switchMenuEntry(buttonId) {
    console.log(`Button ID: ${buttonId}, current admin button: ${currentAdminMenuEntry}`);
    closeAdminMenus();
    const currentAdminButton = document.querySelector("#" + currentAdminMenuEntry);
    const newAdminButton = document.querySelector("#" + buttonId);
    if (currentAdminButton) {
        currentAdminButton.classList.remove("activeMenuButton");
        // document.querySelector(adminMenuElements[currentAdminMenuEntry]).style.display = 'none';
    }
    if (newAdminButton) {
        newAdminButton.classList.add("activeMenuButton");
    }
    if (adminMenuElements[buttonId]) {
        document.querySelector(adminMenuElements[buttonId]).style.display = 'flex';
    }
    currentAdminMenuEntry = buttonId;
}

var table_total_lines = 0;

function submitNewUser(event) {
    event.preventDefault();
    var formData = {};
    var form = event.target;
    var outputElement = document.getElementById("newUserOutput");
    outputElement.innerText = "";

    // Stop if passwords don't match
    if (form.elements["password"].value !== form.elements["passwordRepeat"].value) {
        outputElement.innerText = "Error: Passwords don't match.";
        return 1;
    }

    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];

        if (element.tagName === "INPUT" || element.tagName === "SELECT") {
            if (element.type === "checkbox") {
                if (element.name.slice(-2) === "[]") {
                    var arrayName = element.name.replace(/\[\]$/, "");
                    if (!formData[arrayName]) {
                        formData[arrayName] = [];
                    }
                    formData[arrayName].push(element.checked);
                }
                else {
                    formData[element.name] = element.checked;
                }
            }
            else {
                formData[element.name] = element.value;
            }
        }
    }
    console.log(JSON.stringify(formData));

    // AJAX request
    var create_request = new XMLHttpRequest();
    create_request.open('POST', '' + app_root + '/admin_scripts/create_user.php', true);
    create_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    outputElement.innerText = "";
    create_request.onreadystatechange = function() {
        if (create_request.readyState === 4) {
            if (create_request.status === 200) {
                // Handle response
                var responseData = create_request.responseText;
                console.log(responseData);
                outputElement.innerText = responseData;
                refresh_users_table();
                closeAddUser();
                // location.reload();
            }
            else {
                outputElement.innerText = 'Error:', create_request.status;
            }
        }
    };

    create_request.send(JSON.stringify(formData));
}

function submitEditUser(event) {
    event.preventDefault();
    var formData = {};
    var form = event.target;

    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];

        if (element.tagName === "INPUT" || element.tagName === "SELECT") {
            if (element.type === "checkbox") {
                if (element.name.slice(-2) === "[]") {
                    var arrayName = element.name.replace(/\[\]$/, "");
                    if (!formData[arrayName]) {
                        formData[arrayName] = [];
                    }
                    formData[arrayName].push(element.checked);
                }
                else {
                    formData[element.name] = element.checked;
                }
            }
            else {
                formData[element.name] = element.value;
            }
        }
    }

    // AJAX request
    var create_request = new XMLHttpRequest();
    create_request.open('POST', '' + app_root + '/admin_scripts/edit_user_push.php', true);
    create_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    var outputElement = document.getElementById("editUserOutput");
    outputElement.innerText = "";
    create_request.onreadystatechange = function() {
        if (create_request.readyState === 4) {
            if (create_request.status === 200) {
                // Handle response
                var responseData = create_request.responseText;
                outputElement.innerText = responseData;
                refresh_users_table();
                toggleEditUser();
                // location.reload();
            }
            else {
                outputElement.innerText = 'Error:', create_request.status;
            }
        }
    };

    create_request.send(JSON.stringify(formData));
}

function submitChangeUserPassword(event) {
    event.preventDefault();
    var uid = editUserForm.elements["user_id"].value;
    var password = changeUserPasswordForm.elements["password"].value;
    var passwordRepeat = changeUserPasswordForm.elements["passwordRepeat"].value;
    changeUserPasswordOutput.innerText = "";
    
    if (password.length === 0 || passwordRepeat.length === 0) {
        changeUserPasswordOutput.innerText = "Error: Empty password field.";
        return 1;
    }
    else if (password !== passwordRepeat) {
        changeUserPasswordOutput.innerText = "Error: Passwords do not match.";
        return 1;
    }

    var data = {"uid": uid, "password": password};

    // AJAX request
    var change_request = new XMLHttpRequest();
    change_request.open('POST', '' + app_root + '/admin_scripts/change_user_password.php', true);
    change_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    change_request.onreadystatechange = function() {
        if (change_request.readyState === 4) {
            if (change_request.status === 200) {
                // Handle response
                var responseData = change_request.responseText;
                changeUserPasswordOutput.innerText = responseData;
        if (responseData === "Password updated successfully.") {
            toggleEditUser();
        }
            }
            else {
                changeUserPasswordOutput.innerText = 'Error:', change_request.status;
            }
        }
    };

    change_request.send(JSON.stringify(data));
}

/* Receives table element, list of fields */
function table_insert_line(tableDiv, columns) {
    table_total_lines++;

    var tableName = tableDiv.getAttribute("id");
    var tBody = tableDiv.getElementsByTagName('tbody')[0];

    var table_line = document.createElement("tr");
    table_line.setAttribute("class", "application_table_line");
    table_line.setAttribute("id", tableName + "_line_" + table_total_lines);
    tBody.appendChild(table_line);

    for (var i = 0; i < columns.length; i++) {
        var tableCell = document.createElement("td");
        // tableCell.classList.add("application_table_cell");
        tableCell.classList.add("adminTableCell");
        if (i == 0) tableCell.classList.add("hidden_cell");
        tableCell.setAttribute("id", tableName + "_cell_" + columns[i] + "_" + table_total_lines);
        var tableCellText = document.createElement("p");
        // tableCellText.classList.add("application_cell_text");
        tableCellText.setAttribute("id", tableName + "_cell_text_" + columns[i] + "_" + table_total_lines);
        tableCell.appendChild(tableCellText);
        table_line.appendChild(tableCell);

    }
    if (resource_permissions.canEditCompanies) {
        var edit_column = document.createElement("td");
        var edit_button = document.createElement("button");
        edit_button.setAttribute("id", "edit_" + tableName + "_line_" + table_total_lines);
        edit_button.setAttribute("data", table_total_lines);
        edit_button.setAttribute("onclick", "table_edit_line(this.id)");
        edit_button.classList.add("application_edit_button");
        edit_column.appendChild(edit_button);
        table_line.appendChild(edit_column);
    }
    
    /* Don't show delete button if using company table */
    if (resource_permissions.canDeleteCompanies) {
        if (tableDiv.getAttribute("id") !== "companiesTable") {
            var delete_column = document.createElement("td");
            var delete_button = document.createElement("button");
            delete_button.setAttribute("id", "delete_" + tableName + "_line_" + table_total_lines);
            delete_button.setAttribute("data", table_total_lines);
            delete_button.setAttribute("onclick", "table_delete_line(this.id)"); // 3rd oct TO CHANGE
            delete_button.classList.add("application_delete_button"); // 3rd oct TO CHANGE (CHANGED 4th Dec)
            delete_button.innertext = "delete_picture";
            delete_button.style.backgroundColor = ""; // 3rd oct TO CHANGE
            delete_column.appendChild(delete_button);
            table_line.appendChild(delete_column);
        }
    }
}

function openAddUser() {
    // Clear form values for new user
    for (var i = 0; i < newUserForm.elements.length; i++) {
        var formElement = newUserForm.elements[i];
        if (formElement.tagName === "INPUT") {
            if (formElement.type === "checkbox") {
                formElement.checked = false;
            }
            else {
                formElement.value = "";
            }
        }
        else if (formElement.tagName === "SELECT") {
            formElement.selectedIndex = 1;
        }
    }
    
    usersTable.style.display = 'none';
    newUserForm.style.display = 'block';
    addUserButton.style.display = 'none';
    // addUserButton.innerText = "Cancel";
    userHeaderContent.style.display = 'none';
    userReturnButton.style.display = 'inline-block';
    userReturnButton.setAttribute("onclick", "closeAddUser()");
    reset_user_selectors();
    document.getElementById("newUserOutput").innerHTML = "";
    // addUserButton.classList.remove("add_line_button");
    addingUser = true;
}

function closeAddUser() {
    usersTable.style.display = 'table';
    newUserForm.style.display = 'none';
    addUserButton.style.display = 'inline-block';
    // addUserButton.innerText = "Add User";
    userHeaderContent.style.display = 'inline-block';
    userReturnButton.style.display = 'none';
    userReturnButton.setAttribute("onclick", "");
    // addUserButton.classList.add("add_line_button");
    addingUser = false;
}

function toggleAddUser() {
    if (!addingUser) {
        openAddUser();
    } else {
        closeAddUser();
    }
    editUserDiv.style.display = 'none';
}

function openEditUser() {
    usersTable.style.display = 'none'
    editUserDiv.style.display = 'flex'

    if (addUserButton) addUserButton.style.display = 'none';
    userHeaderContent.style.display = 'none';
    userReturnButton.style.display = 'inline-block';
    userReturnButton.setAttribute("onclick", "closeEditUser()");

    editingUser = true;
}

function closeEditUser() {
    usersTable.style.display = 'table';
    editUserDiv.style.display = 'none'

    if (addUserButton) addUserButton.style.display = 'inline-block';
    userHeaderContent.style.display = 'inline-block';
    userReturnButton.style.display = 'none';
    userReturnButton.setAttribute("onclick", "");

    editingUser = false;
}

function toggleEditUser() {
    if (!editingUser) {
        openEditUser();
    }
    else {
        closeEditUser();
    }
    newUserForm.style.display = 'none';
}

function whichTable(row_id) {
    const companyPattern = /^companiesTable_line_\d+$/;
    const userPattern = /^usersTable_line_\d+$/;

    if (companyPattern.test(row_id)) {
        return "company";
    }
    else if (userPattern.test(row_id)) {
        return "user";
    }
    else {
        return false;
    }
}


function table_delete_line(passed_id) {
    var delete_button = document.getElementById(passed_id);
    var row = delete_button.parentElement.parentElement;
    var id = parseInt(row.children[0].children[0].innerText);
    var username = row.children[1].children[0].innerText;

    var category = whichTable(row.getAttribute("id"));
    if (!category) { return 1; }

    if (!confirm("Really delete " + category + " user " + username + "?")) {
        return 1;
    }
    var tableName = delete_button.parentElement.parentElement.parentElement.parentElement.getAttribute("id");
    var delete_button_data = delete_button.getAttribute("data");

    var outputElement = document.getElementById(category + "_table_output");
    outputElement.innerText = "";
    var delete_request = new XMLHttpRequest();
    delete_request.open('POST', '' + app_root + '/admin_scripts/delete_' + category + '.php', true);
    delete_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    delete_request.onload = function() {
        if (delete_request.status === 200) {
            // Handle response from server
            outputElement.innerText = delete_request.responseText;

            var table_line_to_delete = document.getElementById(tableName + "_line_" + delete_button_data);
            table_line_to_delete.remove();
            if (category == "company") {
                refresh_users_table();
                vessel_manager_retrieve_lines();
                route_manager_retrieve_lines();
            }
        }
    };
    delete_request.onerror = function() {
        outputElement.innerText = "Request failed.";
    }
    delete_request.send("id=" + id);
}

function table_retrieve_lines(tableDiv, columns, scriptName) {
    // table_total_lines = 0;
    var get_request_data = new XMLHttpRequest();
    var imo_data_send = ''
    get_request_data.open('POST', '' + app_root + '/admin_scripts/' + scriptName, true);
    get_request_data.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    get_request_data.onreadystatechange = function() {
        if (get_request_data.readyState == 4 && this.status == 200) {
            // if (scriptName = "companies_request.php") alert(this.responseText);

            var table_manager_data = this.responseText;
            table_load_lines(tableDiv, table_manager_data, columns);
        }
    }
    get_request_data.send(imo_data_send);    
}

function table_load_lines(tableDiv, table_manager_data, columns) {
    table_total_lines = 0;
    var tableName = tableDiv.getAttribute("id");
    var table_array = table_manager_data.split(',');

    var lines_to_load = table_array.length / columns.length;

    for (let x = 0; x < lines_to_load; x++) {
        table_insert_line(tableDiv, columns);
        var table_field = [];

        for (let i = 0; i < columns.length; i++) {
            table_field[i] = document.getElementById(tableName + "_cell_text_" + columns[i] + "_" + (x + 1));
            table_field[i].innerText = unescape(table_array[columns.length * x + i]);
        }
    }

}





// End of admin menu by Chris












function change_low_executive() {
    risk_rating_executive.style.backgroundColor = '#38cccc';
    risk_text_executive.innerText = "LOW"
}
function change_moderate_executive() {
    risk_rating_executive.style.backgroundColor = '#a0cc04';
    risk_text_executive.innerText = "MODERATE"
}
function change_substantial_executive() {
    risk_rating_executive.style.backgroundColor = '#ffc404';
    risk_text_executive.innerText = "SUBSTANTIAL"
}
function change_high_executive() {
    risk_rating_executive.style.backgroundColor = '#ff6404';
    risk_text_executive.innerText = "HIGH"
}
function change_extreme_executive() {
    risk_rating_executive.style.backgroundColor = '#e81c24';
    risk_text_executive.innerText = "EXTREME"
}
change_low_executive()
document.getElementById("radio_1_executive").checked = true;



function change_low_approaches() {
    risk_rating_approaches.style.backgroundColor = '#38cccc';
    risk_text_approaches.innerText = "LOW"
}
function change_moderate_approaches() {
    risk_rating_approaches.style.backgroundColor = '#a0cc04';
    risk_text_approaches.innerText = "MODERATE"
}
function change_substantial_approaches() {
    risk_rating_approaches.style.backgroundColor = '#ffc404';
    risk_text_approaches.innerText = "SUBSTANTIAL"
}
function change_high_approaches() {
    risk_rating_approaches.style.backgroundColor = '#ff6404';
    risk_text_approaches.innerText = "HIGH"
}
function change_extreme_approaches() {
    risk_rating_approaches.style.backgroundColor = '#e81c24';
    risk_text_approaches.innerText = "EXTREME"
}
change_low_approaches()
document.getElementById("radio_1_approaches").checked = true;



function change_low_terrorism() {
    risk_rating_terrorism.style.backgroundColor = '#38cccc';
    risk_text_terrorism.innerText = "LOW"
}
function change_moderate_terrorism() {
    risk_rating_terrorism.style.backgroundColor = '#a0cc04';
    risk_text_terrorism.innerText = "MODERATE"
}
function change_substantial_terrorism() {
    risk_rating_terrorism.style.backgroundColor = '#ffc404';
    risk_text_terrorism.innerText = "SUBSTANTIAL"
}
function change_high_terrorism() {
    risk_rating_terrorism.style.backgroundColor = '#ff6404';
    risk_text_terrorism.innerText = "HIGH"
}
function change_extreme_terrorism() {
    risk_rating_terrorism.style.backgroundColor = '#e81c24';
    risk_text_terrorism.innerText = "EXTREME"
}
change_low_terrorism()
document.getElementById("radio_1_terrorism").checked = true;



function change_low_piracy() {
    risk_rating_piracy.style.backgroundColor = '#38cccc';
    risk_text_piracy.innerText = "LOW"
}
function change_moderate_piracy() {
    risk_rating_piracy.style.backgroundColor = '#a0cc04';
    risk_text_piracy.innerText = "MODERATE"
}
function change_substantial_piracy() {
    risk_rating_piracy.style.backgroundColor = '#ffc404';
    risk_text_piracy.innerText = "SUBSTANTIAL"
}
function change_high_piracy() {
    risk_rating_piracy.style.backgroundColor = '#ff6404';
    risk_text_piracy.innerText = "HIGH"
}
function change_extreme_piracy() {
    risk_rating_piracy.style.backgroundColor = '#e81c24';
    risk_text_piracy.innerText = "EXTREME"
}
change_low_piracy()
document.getElementById("radio_1_piracy").checked = true;



function change_low_insurgency() {
    risk_rating_insurgency.style.backgroundColor = '#38cccc';
    risk_text_insurgency.innerText = "LOW"
}
function change_moderate_insurgency() {
    risk_rating_insurgency.style.backgroundColor = '#a0cc04';
    risk_text_insurgency.innerText = "MODERATE"
}
function change_substantial_insurgency() {
    risk_rating_insurgency.style.backgroundColor = '#ffc404';
    risk_text_insurgency.innerText = "SUBSTANTIAL"
}
function change_high_insurgency() {
    risk_rating_insurgency.style.backgroundColor = '#ff6404';
    risk_text_insurgency.innerText = "HIGH"
}
function change_extreme_insurgency() {
    risk_rating_insurgency.style.backgroundColor = '#e81c24';
    risk_text_insurgency.innerText = "EXTREME"
}
change_low_insurgency()
document.getElementById("radio_1_insurgency").checked = true;



function change_low_activism() {
    risk_rating_activism.style.backgroundColor = '#38cccc';
    risk_text_activism.innerText = "LOW"
}
function change_moderate_activism() {
    risk_rating_activism.style.backgroundColor = '#a0cc04';
    risk_text_activism.innerText = "MODERATE"
}
function change_substantial_activism() {
    risk_rating_activism.style.backgroundColor = '#ffc404';
    risk_text_activism.innerText = "SUBSTANTIAL"
}
function change_high_activism() {
    risk_rating_activism.style.backgroundColor = '#ff6404';
    risk_text_activism.innerText = "HIGH"
}
function change_extreme_activism() {
    risk_rating_activism.style.backgroundColor = '#e81c24';
    risk_text_activism.innerText = "EXTREME"
}
change_low_activism()
document.getElementById("radio_1_activism").checked = true;



function change_low_smuggling() {
    risk_rating_smuggling.style.backgroundColor = '#38cccc';
    risk_text_smuggling.innerText = "LOW"
}
function change_moderate_smuggling() {
    risk_rating_smuggling.style.backgroundColor = '#a0cc04';
    risk_text_smuggling.innerText = "MODERATE"
}
function change_substantial_smuggling() {
    risk_rating_smuggling.style.backgroundColor = '#ffc404';
    risk_text_smuggling.innerText = "SUBSTANTIAL"
}
function change_high_smuggling() {
    risk_rating_smuggling.style.backgroundColor = '#ff6404';
    risk_text_smuggling.innerText = "HIGH"
}
function change_extreme_smuggling() {
    risk_rating_smuggling.style.backgroundColor = '#e81c24';
    risk_text_smuggling.innerText = "EXTREME"
}
change_low_smuggling()
document.getElementById("radio_1_smuggling").checked = true;



function change_low_stowaways() {
    risk_rating_stowaways.style.backgroundColor = '#38cccc';
    risk_text_stowaways.innerText = "LOW"
}
function change_moderate_stowaways() {
    risk_rating_stowaways.style.backgroundColor = '#a0cc04';
    risk_text_stowaways.innerText = "MODERATE"
}
function change_substantial_stowaways() {
    risk_rating_stowaways.style.backgroundColor = '#ffc404';
    risk_text_stowaways.innerText = "SUBSTANTIAL"
}
function change_high_stowaways() {
    risk_rating_stowaways.style.backgroundColor = '#ff6404';
    risk_text_stowaways.innerText = "HIGH"
}
function change_extreme_stowaways() {
    risk_rating_stowaways.style.backgroundColor = '#e81c24';
    risk_text_stowaways.innerText = "EXTREME"
}
change_low_stowaways()
document.getElementById("radio_1_stowaways").checked = true;



function change_low_fraud() {
    risk_rating_fraud.style.backgroundColor = '#38cccc';
    risk_text_fraud.innerText = "LOW"
}
function change_moderate_fraud() {
    risk_rating_fraud.style.backgroundColor = '#a0cc04';
    risk_text_fraud.innerText = "MODERATE"
}
function change_substantial_fraud() {
    risk_rating_fraud.style.backgroundColor = '#ffc404';
    risk_text_fraud.innerText = "SUBSTANTIAL"
}
function change_high_fraud() {
    risk_rating_fraud.style.backgroundColor = '#ff6404';
    risk_text_fraud.innerText = "HIGH"
}
function change_extreme_fraud() {
    risk_rating_fraud.style.backgroundColor = '#e81c24';
    risk_text_fraud.innerText = "EXTREME"
}
change_low_fraud()
document.getElementById("radio_1_fraud").checked = true;



function route_open_button(imo_number) {

    console.log(imo_number)

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + '&imo_number=' + imo_number
    ajax_request.open('POST', '' + app_root + '/routes/route_open_button.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
            var retrieved_coords_edit = this.responseText;
            
            if (retrieved_coords_edit.length == 0) {
                alert("No route associated with this vessel");
            }
            else {
                route_edit_loadRouteByCoords(retrieved_coords_edit);
            }     
             
        }
    }
    ajax_request.send(data_to_send);

}



function searchPorts(e) {
    var query = e.target.value;
    var id = e.target.id;

    var startOrDestination, suggestions;

    switch (id) {
        case "route_add_start_input":
            // startOrDestination = "start";
            suggestions = document.getElementById("suggestions-start-new");
            break;
        case "route_add_destination_input":
            // startOrDestination = "destination";
            suggestions = document.getElementById("suggestions-destination-new");
            break;
        case "route_edit_start_input":
            // startOrDestination = "start";
            suggestions = document.getElementById("suggestions-start-edit");
            break;
        case "route_edit_destination_input":
            // startOrDestination = "destination";
            suggestions = document.getElementById("suggestions-destination-edit");
            break;
        default:
            console.error("Invalid ID for searchPorts function");
            return 1;
    }
    // console.log(`searchPorts called - query: ${query}, startOrDestination: ${startOrDestination}`);
    if (query.length > 1) {
        var request = new XMLHttpRequest();
        request.open('POST', app_root + '/routes/search_ports.php', true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        request.onload = function() {
            if (this.status === 200) {
                suggestions.style.display = "block";
                console.log(`Response: ${this.responseText}`);
                suggestions.innerHTML = this.responseText;
                suggestions.style.position = "fixed";
                // document.getElementById("suggestions-" + startOrDestination).innerHTML = this.responseText;
                // document.getElementById("suggestions-" + startOrDestination).style.position = "relative";
            }
        };

        request.send('query=' + encodeURIComponent(query));
    } else {
        suggestions.innerHTML = '';
        // document.getElementById('suggestions-' + startOrDestination).innerHTML = '';
        suggestions.style.display = "none";
    }
}

document.getElementById("route_add_start_input").addEventListener("input", searchPorts);
document.getElementById("route_add_destination_input").addEventListener("input", searchPorts);
document.getElementById("route_edit_start_input").addEventListener("input", searchPorts);
document.getElementById("route_edit_destination_input").addEventListener("input", searchPorts);

// Port selection
document.addEventListener("click", function(e) {
    if (e.target.classList.contains("suggestion")) {
        // Clear hra selection
        document.getElementById("route_create_risk_area_sel").selectedIndex = 0;

        var portName = e.target.textContent;
        var portId = e.target.dataset.id;

        var searchBox, portId, crossBtn, suggestions, chkCreateBtn;
        switch (e.target.parentElement.id) {
            case "suggestions-start-new":
                searchBox = document.getElementById("route_add_start_input");
                portId = document.getElementById("route_add_port_id_start");
                crossBtn = document.getElementById("cross-btn-start-new");
                suggestions = document.getElementById("suggestions-start-new");
                chkCreateBtn = true;
                break;
            case "suggestions-destination-new":
                searchBox = document.getElementById("route_add_destination_input");
                portId = document.getElementById("route_add_port_id_destination");
                crossBtn = document.getElementById("cross-btn-destination-new");
                suggestions = document.getElementById("suggestions-destination-new");
                chkCreateBtn = true;
                break;
            case "suggestions-start-edit":
                searchBox = document.getElementById("route_edit_start_input");
                portId = document.getElementById("route_edit_port_id_start");
                crossBtn = document.getElementById("cross-btn-start-edit");
                suggestions = document.getElementById("suggestions-start-edit");
                chkCreateBtn = false;
                break;
            case "suggestions-destination-edit":
                searchBox = document.getElementById("route_edit_destination_input");
                portId = document.getElementById("route_edit_port_id_destination");
                crossBtn = document.getElementById("cross-btn-destination-edit");
                suggestions = document.getElementById("suggestions-destination-edit");
                chkCreateBtn = false;
                break;
            default:
                console.error(`Parent element of ${e.target} not found.`);
                return 1;
        }

        searchBox.value = portName;
        searchBox.readOnly = true;
        searchBox.disabled = true;
        searchBox.style.borderColor = "black";

        portId.value = e.target.dataset.id;

        crossBtn.style.display = "inline";

        suggestions.innerHTML = "";
        suggestions.style.display = "none";

        if (chkCreateBtn) {
            verify_create_route_has_correct_data();
        }
    } else {
        document.querySelectorAll(".suggestions-dropdown").forEach(e => {
            e.style.display = "none";
        });
    }
});

// Set correct polygons when new hra is selected
document.getElementById("route_create_risk_area_sel").addEventListener("input", e => {
    if (e.target.selectedIndex == 0) {
        verify_create_route_has_correct_data();
        return;
    }

    const startSearchBox = document.getElementById("route_add_start_input");
    const destinationSearchBox = document.getElementById("route_add_destination_input");

    startSearchBox.value = "ENTER HRA";
    startSearchBox.readOnly = true;
    startSearchBox.disabled = true;
    startSearchBox.style.borderColor = "black";

    destinationSearchBox.value = "EXIT HRA";
    destinationSearchBox.readOnly = true;
    destinationSearchBox.disabled = true;
    destinationSearchBox.style.borderColor = "black";

    document.getElementById("route_add_port_id_start").value = "7602";
    document.getElementById("route_add_port_id_destination").value = "7603";

    document.getElementById("cross-btn-start-new").style.display = "inline";
    document.getElementById("cross-btn-destination-new").style.display = "inline";

    document.getElementById("suggestions-start-new").innerHTML = "";
    document.getElementById("suggestions-destination-new").innerHTML = "";
    document.getElementById("suggestions-start-new").style.display = "none";
    document.getElementById("suggestions-destination-new").style.display = "none";

    verify_create_route_has_correct_data();
});

// Set correct polygons when edit hra is selected
document.getElementById("route_edit_risk_area_sel").addEventListener("input", e => {
    if (e.target.selectedIndex == 0) {
        verify_create_route_has_correct_data();
        return;
    }

    const startSearchBox = document.getElementById("route_edit_start_input");
    const destinationSearchBox = document.getElementById("route_edit_destination_input");

    startSearchBox.value = "ENTER HRA";
    startSearchBox.readOnly = true;
    startSearchBox.disabled = true;
    startSearchBox.style.borderColor = "black";

    destinationSearchBox.value = "EXIT HRA";
    destinationSearchBox.readOnly = true;
    destinationSearchBox.disabled = true;
    destinationSearchBox.style.borderColor = "black";

    document.getElementById("route_edit_port_id_start").value = "7602";
    document.getElementById("route_edit_port_id_destination").value = "7603";

    document.getElementById("cross-btn-start-edit").style.display = "inline";
    document.getElementById("cross-btn-destination-edit").style.display = "inline";

    document.getElementById("suggestions-start-edit").innerHTML = "";
    document.getElementById("suggestions-destination-edit").innerHTML = "";
    document.getElementById("suggestions-start-edit").style.display = "none";
    document.getElementById("suggestions-destination-edit").style.display = "none";

    verify_create_route_has_correct_data();
});

document.querySelectorAll(".cross-button").forEach(e => {
    e.addEventListener("click", function(e) {
        var searchBox, portId, crossBtn;
        const routeAddStartPortId = document.getElementById("route_add_port_id_start");
        const routeAddStartPortSearchBox = document.getElementById("route_add_start_input");
        const routeAddStartPortCrossBtn = document.getElementById("cross-btn-start-new");
        const routeAddDestinationPortId = document.getElementById("route_add_port_id_destination");
        const routeAddDestinationPortSearchBox = document.getElementById("route_add_destination_input");
        const routeAddDestinationPortCrossBtn = document.getElementById("cross-btn-destination-new");
        const routeAddTRASelect = document.getElementById("route_create_risk_area_sel");
        const routeEditStartPortId = document.getElementById("route_edit_port_id_start");
        const routeEditStartPortSearchBox = document.getElementById("route_edit_start_input");
        const routeEditStartPortCrossBtn = document.getElementById("cross-btn-start-edit");
        const routeEditDestinationPortId = document.getElementById("route_edit_port_id_destination");
        const routeEditDestinationPortSearchBox = document.getElementById("route_edit_destination_input");
        const routeEditDestinationPortCrossBtn = document.getElementById("cross-btn-destination-edit");
        const routeEditTRASelect = document.getElementById("route_edit_risk_area_sel");

        // if (e.target.id === "cross-btn-start-new" || e.target.id === "cross-btn-destination-new") {
        //     document.getElementById("route_create_risk_area_sel").selectedIndex = 0;
        // } else if (e.target.id === "cross-btn-start-edit" || e.target.id === "cross-btn-destination-edit") {
        //     document.getElementById("route_edit_risk_area_sel").selectedIndex = 0;
        // }

        if (routeAddTRASelect.selectedIndex !== 0) {
            routeAddTRASelect.selectedIndex = 0;

            routeAddStartPortSearchBox.value = "";
            routeAddStartPortSearchBox.readOnly = false;
            routeAddStartPortSearchBox.disabled = false;

            routeAddDestinationPortSearchBox.value = "";
            routeAddDestinationPortSearchBox.readOnly = false;
            routeAddDestinationPortSearchBox.disabled = false;

            routeAddStartPortId.value = "";
            routeAddDestinationPortId.value = "";

            routeAddStartPortCrossBtn.style.display = "none";
            routeAddDestinationPortCrossBtn.style.display = "none";
        }

        if (routeEditTRASelect.selectedIndex !== 0) {
            routeEditTRASelect.selectedIndex = 0;

            routeEditStartPortSearchBox.value = "";
            routeEditStartPortSearchBox.readOnly = false;
            routeEditStartPortSearchBox.disabled = false;

            routeEditDestinationPortSearchBox.value = "";
            routeEditDestinationPortSearchBox.readOnly = false;
            routeEditDestinationPortSearchBox.disabled = false;

            routeEditStartPortId.value = "";
            routeEditDestinationPortId.value = "";

            routeEditStartPortCrossBtn.style.display = "none";
            routeEditDestinationPortCrossBtn.style.display = "none";
        }

        switch (e.target.id) {
            case "cross-btn-start-new":
                searchBox = document.getElementById("route_add_start_input");
                portId = document.getElementById("route_add_port_id_start");
                crossBtn = document.getElementById("cross-btn-start-new");
                break;
            case "cross-btn-destination-new":
                searchBox = document.getElementById("route_add_destination_input");
                portId = document.getElementById("route_add_port_id_destination");
                crossBtn = document.getElementById("cross-btn-destination-new");
                break;
            case "cross-btn-start-edit":
                searchBox = document.getElementById("route_edit_start_input");
                portId = document.getElementById("route_edit_port_id_start");
                crossBtn = document.getElementById("cross-btn-start-edit");
                break;
            case "cross-btn-destination-edit":
                searchBox = document.getElementById("route_edit_destination_input");
                portId = document.getElementById("route_edit_port_id_destination");
                crossBtn = document.getElementById("cross-btn-destination-edit");
                break;
            default:
                console.error(`Invalid target for cross button function`);
                return 1;
        }

        searchBox.value = "";
        searchBox.readOnly = false;
        searchBox.disabled = false;

        portId.value = "";

        crossBtn.style.display = "none";

        if (e.target.id === "cross-btn-start-new" || e.target.id === "cross-btn-destination-new") {
            verify_create_route_has_correct_data();
        }
    });
});



var global_section_being_edited = "";
function port_edit_risk(passed_id) {

    var port_id = global_port_id_being_edited
    var section = document.getElementById(passed_id).getAttribute("data-section")
    global_section_being_edited = section;

    var start_date = document.getElementById("port_risk_start_date_input_" + section).value
    var end_date = document.getElementById("port_risk_end_date_input_" + section).value

    if (start_date == "" || end_date == "") {
        alert("Please enter Start and End dates")
    }

    else {

        tinymce_open()

        document.getElementById("tinymce_save_button").setAttribute("onclick", "port_create_risk(event)");

        var ajax_request = new XMLHttpRequest();
        var data_to_send = '' 
        + 'port_id=' + port_id
        + '&section=' + section
        ajax_request.open('POST', '' + app_root + '/ports/port_edit_risk.php', true);
        ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

        ajax_request.onreadystatechange = function() {
            if(ajax_request.readyState == 4 && this.status == 200) {
                // console.log(this.responseText);

                tinymce_setContent(this.responseText);

            }
        
        }
        ajax_request.send(data_to_send);

    }

}



function port_load_info() {

    var port_id = global_port_id_being_edited

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'port_id=' + port_id
    ajax_request.open('POST', '' + app_root + '/ports/port_load_info.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var port_info_array = this.responseText.split(",;")

            document.getElementById("port_edit_name_input").value = port_info_array[0];
            document.getElementById("port_edit_country_input").value = port_info_array[1];
            document.getElementById("port_edit_latitude_input").value = port_info_array[2];
            document.getElementById("port_edit_longitude_input").value = port_info_array[3];

        }
    
    }
    ajax_request.send(data_to_send);

}



function port_create_risk() {
    event.stopPropagation(); // prevents parent div element "tinymce_background_close" onclick event from firing, include this with every function bound to "tinymce_save_button"

    alert("Description Saved");

    var port_id = global_port_id_being_edited
    var section = global_section_being_edited

    get_radio_value_port_risk(section) // defines radio_value_port_risk

    var start_date = document.getElementById("port_risk_start_date_input_" + section).value
    var end_date = document.getElementById("port_risk_end_date_input_" + section).value

    var description = tinymce.get("tinymce_editor_instance").getContent()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'port_id=' + port_id
    + '&section=' + section
    + '&start_date=' + start_date
    + '&end_date=' + end_date
    + '&port_risk_rating=' + radio_value_port_risk
    + '&description=' + encodeURIComponent(description)
    ajax_request.open('POST', '' + app_root + '/ports/port_add_risk.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            tinymce_close();
            
            port_load_risks();

        }
    
    }
    ajax_request.send(data_to_send);


}


function port_load_risks() {

    var port_id = global_port_id_being_edited

    set_port_risk_values("executive", "", "", 1, "")
    set_port_risk_values("approaches", "", "", 1, "")
    set_port_risk_values("terrorism", "", "", 1, "")
    set_port_risk_values("piracy", "", "", 1, "")
    set_port_risk_values("insurgency", "", "", 1, "")
    set_port_risk_values("activism", "", "", 1, "")
    set_port_risk_values("smuggling", "", "", 1, "")
    set_port_risk_values("stowaways", "", "", 1, "")
    set_port_risk_values("fraud", "", "", 1, "")

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'port_id=' + port_id
    ajax_request.open('POST', '' + app_root + '/ports/port_load_risks.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var port_risk_array = this.responseText.split(',;');

            var section_amount = 9
            for (let x = 0; x < section_amount; x++) {
            
                var section = port_risk_array[5*x + 0]
                var start_date = port_risk_array[5*x + 1]
                var end_date = port_risk_array[5*x + 2]
                var port_risk_rating = port_risk_array[5*x + 3]
                var description = port_risk_array[5*x + 4]

                set_port_risk_values(section, start_date, end_date, port_risk_rating, description)
            }

            
        }
    
    }
    ajax_request.send(data_to_send);

}


var radio_value_port_risk = "";
function get_radio_value_port_risk(section) {

    if (document.getElementById("radio_1_" + section).checked == true) {
        radio_value_port_risk = 1;
    }

    else if (document.getElementById("radio_2_" + section).checked == true) {
        radio_value_port_risk = 2;
    }

    else if (document.getElementById("radio_3_" + section).checked == true) {
        radio_value_port_risk = 3;
    }

    else if (document.getElementById("radio_4_" + section).checked == true) {
        radio_value_port_risk = 4;
    }

    else if (document.getElementById("radio_5_" + section).checked == true) {
        radio_value_port_risk = 5;
    }

}

function set_port_risk_values(section, start_date, end_date, port_risk_rating, description) {

    if (section) {

        // console.log(section)
        // console.log(start_date)
        // console.log(end_date)
        // console.log(port_risk_rating)
        // console.log(description)

        document.getElementById("port_risk_start_date_input_" + section).value = start_date
        document.getElementById("port_risk_end_date_input_" + section).value = end_date
        document.getElementById("port_risk_uneditable_box_" + section).innerHTML = description

        if (port_risk_rating == 1) {
            document.getElementById("risk_rating_" + section).style.backgroundColor = '#38cccc';
            document.getElementById("risk_text_" + section).innerText = "LOW"
            document.getElementById("radio_1_" + section).checked = true
            document.getElementById("radio_2_" + section).checked = false
            document.getElementById("radio_3_" + section).checked = false
            document.getElementById("radio_4_" + section).checked = false
            document.getElementById("radio_5_" + section).checked = false
        }

        else if (port_risk_rating == 2) {
            document.getElementById("risk_rating_" + section).style.backgroundColor = '#a0cc04';
            document.getElementById("risk_text_" + section).innerText = "MODERATE"
            document.getElementById("radio_1_" + section).checked = false
            document.getElementById("radio_2_" + section).checked = true
            document.getElementById("radio_3_" + section).checked = false
            document.getElementById("radio_4_" + section).checked = false
            document.getElementById("radio_5_" + section).checked = false
        }

        else if (port_risk_rating == 3) {
            document.getElementById("risk_rating_" + section).style.backgroundColor = '#ffc404';
            document.getElementById("risk_text_" + section).innerText = "SUBSTANTIAL"
            document.getElementById("radio_1_" + section).checked = false
            document.getElementById("radio_2_" + section).checked = false
            document.getElementById("radio_3_" + section).checked = true
            document.getElementById("radio_4_" + section).checked = false
            document.getElementById("radio_5_" + section).checked = false
        }

        else if (port_risk_rating == 4) {
            document.getElementById("risk_rating_" + section).style.backgroundColor = '#ff6404';
            document.getElementById("risk_text_" + section).innerText = "HIGH"
            document.getElementById("radio_1_" + section).checked = false
            document.getElementById("radio_2_" + section).checked = false
            document.getElementById("radio_3_" + section).checked = false
            document.getElementById("radio_4_" + section).checked = true
            document.getElementById("radio_5_" + section).checked = false
        }

        else if (port_risk_rating == 5) {
            document.getElementById("risk_rating_" + section).style.backgroundColor = '#e81c24';
            document.getElementById("risk_text_" + section).innerText = "EXTREME"
            document.getElementById("radio_1_" + section).checked = false
            document.getElementById("radio_2_" + section).checked = false
            document.getElementById("radio_3_" + section).checked = false
            document.getElementById("radio_4_" + section).checked = false
            document.getElementById("radio_5_" + section).checked = true
        }

        else {
            // do nothing if risk value isnt set
        }

    }

    else {
        // do nothing if no section value is set
    }


}




var long_pass_route_edit = "";
var lat_pass_route_edit = "";
function route_edit_getCoordData() {

    long_pass_route_edit = ""; // resets incase something is being edited more than once
    lat_pass_route_edit = "";

    route_convert_coordinates("route_edit_textbox");
    // global_route_coordinates now defined

    for (let x = 0; x < global_route_coordinates.length; x++) {
        lat_pass_route_edit = lat_pass_route_edit + global_route_coordinates[x][0] + ","
        long_pass_route_edit = long_pass_route_edit + global_route_coordinates[x][1] + ","

    }

    long_pass_route_edit = long_pass_route_edit.slice(0,-1);
    lat_pass_route_edit = lat_pass_route_edit.slice(0,-1);
    
}








function polygon_risk_change_low() {
    polygon_risk_radio_1.checked = true;
    polygon_risk_input_box.style.backgroundColor = '#38cccc';
    polygon_risk_text.innerText = "LOW"
}

function polygon_risk_change_moderate() {
    polygon_risk_radio_2.checked = true;
    polygon_risk_input_box.style.backgroundColor = '#a0cc04';
    polygon_risk_text.innerText = "MODERATE"
}

function polygon_risk_change_substantial() {
    polygon_risk_radio_3.checked = true;
    polygon_risk_input_box.style.backgroundColor = '#ffc404';
    polygon_risk_text.innerText = "SUBSTANTIAL"
}

function polygon_risk_change_high() {
    polygon_risk_radio_4.checked = true;
    polygon_risk_input_box.style.backgroundColor = '#ff6404';
    polygon_risk_text.innerText = "HIGH"
}

function polygon_risk_change_extreme() {
    polygon_risk_radio_5.checked = true;
    polygon_risk_input_box.style.backgroundColor = '#e81c24';
    polygon_risk_text.innerText = "EXTREME"
}


function set_polygon_risk_rating(polygon_risk_rating) {

    if (polygon_risk_rating == 1) {
        polygon_risk_change_low();
    }
    else if (polygon_risk_rating == 2) {
        polygon_risk_change_moderate();
    }
    else if (polygon_risk_rating == 3) {
        polygon_risk_change_substantial();
    }
    else if (polygon_risk_rating == 4) {
        polygon_risk_change_high();
    }
    else if (polygon_risk_rating == 5) {
        polygon_risk_change_extreme();
    }
    else {
        console.log("Transit Risk Value Invalid");
    }

}
set_polygon_risk_rating(1);







function region_min_risk_change_low() {
    region_min_risk_radio_1.checked = true;
    region_min_risk_input_box.style.backgroundColor = '#38cccc';
    region_min_risk_text.innerText = "LOW"
}

function region_min_risk_change_moderate() {
    region_min_risk_radio_2.checked = true;
    region_min_risk_input_box.style.backgroundColor = '#a0cc04';
    region_min_risk_text.innerText = "MODERATE"
}

function region_min_risk_change_substantial() {
    region_min_risk_radio_3.checked = true;
    region_min_risk_input_box.style.backgroundColor = '#ffc404';
    region_min_risk_text.innerText = "SUBSTANTIAL"
}

function region_min_risk_change_high() {
    region_min_risk_radio_4.checked = true;
    region_min_risk_input_box.style.backgroundColor = '#ff6404';
    region_min_risk_text.innerText = "HIGH"
}

function region_min_risk_change_extreme() {
    region_min_risk_radio_5.checked = true;
    region_min_risk_input_box.style.backgroundColor = '#e81c24';
    region_min_risk_text.innerText = "EXTREME"
}


function set_region_min_risk_rating(region_min_risk_rating) {

    if (region_min_risk_rating == 1) {
        region_min_risk_change_low();
    }
    else if (region_min_risk_rating == 2) {
        region_min_risk_change_moderate();
    }
    else if (region_min_risk_rating == 3) {
        region_min_risk_change_substantial();
    }
    else if (region_min_risk_rating == 4) {
        region_min_risk_change_high();
    }
    else if (region_min_risk_rating == 5) {
        region_min_risk_change_extreme();
    }
    else {
        console.log("Transit Risk Value Invalid");
    }

}
set_region_min_risk_rating(1);





function region_max_risk_change_low() {
    region_max_risk_radio_1.checked = true;
    region_max_risk_input_box.style.backgroundColor = '#38cccc';
    region_max_risk_text.innerText = "LOW"
}

function region_max_risk_change_moderate() {
    region_max_risk_radio_2.checked = true;
    region_max_risk_input_box.style.backgroundColor = '#a0cc04';
    region_max_risk_text.innerText = "MODERATE"
}

function region_max_risk_change_substantial() {
    region_max_risk_radio_3.checked = true;
    region_max_risk_input_box.style.backgroundColor = '#ffc404';
    region_max_risk_text.innerText = "SUBSTANTIAL"
}

function region_max_risk_change_high() {
    region_max_risk_radio_4.checked = true;
    region_max_risk_input_box.style.backgroundColor = '#ff6404';
    region_max_risk_text.innerText = "HIGH"
}

function region_max_risk_change_extreme() {
    region_max_risk_radio_5.checked = true;
    region_max_risk_input_box.style.backgroundColor = '#e81c24';
    region_max_risk_text.innerText = "EXTREME"
}


function set_region_max_risk_rating(region_max_risk_rating) {

    if (region_max_risk_rating == 1) {
        region_max_risk_change_low();
    }
    else if (region_max_risk_rating == 2) {
        region_max_risk_change_moderate();
    }
    else if (region_max_risk_rating == 3) {
        region_max_risk_change_substantial();
    }
    else if (region_max_risk_rating == 4) {
        region_max_risk_change_high();
    }
    else if (region_max_risk_rating == 5) {
        region_max_risk_change_extreme();
    }
    else {
        console.log("Transit Risk Value Invalid");
    }

}
set_region_max_risk_rating(1);


function display_polygon_risk_rating() {
    document.getElementById("polygon_risk_rating_box").style.display = "block";
    document.getElementById("region_min_risk_rating_box").style.display = "none";
    document.getElementById("region_max_risk_rating_box").style.display = "none";
}

function display_region_risk_rating() {
    document.getElementById("polygon_risk_rating_box").style.display = "none";
    document.getElementById("region_min_risk_rating_box").style.display = "block";
    document.getElementById("region_max_risk_rating_box").style.display = "block";
}







function toggleNa(e) {
    console.log("toggling na");
    e.target.nextSibling.disabled = e.target.checked ? false : true;
}

document.querySelectorAll(".na_chk").forEach(e => {
    e.addEventListener("change", toggleNa)
});

document.querySelectorAll(".questionnaire_form").forEach(e => {
    e.addEventListener("submit", async function(e) {
        e.preventDefault();
        let formId, qData;
        try {
            let pattern = /^questionnaire_form_([0-9]+)$/;
            formId = e.target.id.match(pattern)[1];
            qData = window.questionnaires.find(questionnaire => questionnaire["questionnaire_id"] === formId);
        } catch (error) {
            console.error("Error:", error);
            alert("Problem with form.");
            return;
        }
        let parsedQuestionnaire = JSON.parse(qData["questions"]);
        // parsedQuestionnaire["questions"] = JSON.parse(qData["questions"]);
        // alert(typeof(parsedQuestionnaire["questions"][0]["questions"]));
        parsedQuestionnaire.forEach(section => {
            section["questions"].forEach(question => {
                // console.log(`Question ${question["number"]}: ${question["text"]}`);
                if (typeof question["scores"] === "undefined") {
                    question["scores"] = {};
                }
                let scoreYes = parseInt(e.target.elements[`score_yes_${question["number"]}`].value);
                if (typeof question["scores"]["yes"] === "undefined" || question["scores"]["yes"] !== scoreYes) {
                    question["scores"]["yes"] = scoreYes;
                }
                let scoreNo = parseInt(e.target.elements[`score_no_${question["number"]}`].value);
                if (typeof question["scores"]["no"] === "undefined" || question["scores"]["no"] !== scoreNo) {
                    question["scores"]["no"] = scoreNo;
                }
                let scoreNa = parseInt(e.target.elements[`score_na_${question["number"]}`].value);
                if (typeof question["scores"]["na"] === "undefined" || question["scores"]["na"] !== scoreNa) {
                    question["scores"]["na"] = scoreNa;
                }
                let naEnabled = e.target.elements[`toggle_na_${question["number"]}`].checked;
                question["input_type"] = naEnabled ? "bool+" : "bool";
            });
        });
        // alert(JSON.stringify(JSON.parse(JSON.stringify(parsedQuestionnaire))));

        // AJAX request
        let save_request = new XMLHttpRequest();
        save_request.open('POST', '' + app_root + '/admin_scripts/questionnaire_score_save.php', true);
        save_request.setRequestHeader('Content-Type', 'application/json');

        var outputElement = document.getElementById("newCompanyOutput");
        outputElement.innerText = "";
        save_request.onreadystatechange = function() {
            if (save_request.readyState === 4) {
                if (save_request.status === 200) {
                    // Handle response
                    alert(save_request.responseText);
                }
            
            } else {
                console.error(`Error saving questionnaire: ${save_request.statusText}`);
            }
            //ajax_request.send(data_to_send);

        }
        save_request.send(JSON.stringify({questionnaire_id: formId, data: JSON.stringify(parsedQuestionnaire)}));
    });
});




var global_current_incident_guidance_id = "";
function editIncidentGuidance(passed_id) {
    const button = document.getElementById(passed_id);
    const incident_id = button.value;
    global_current_incident_guidance_id = incident_id;

    const initialData = document.getElementById(`incident_guidance_uneditable_box_${incident_id}`).innerHTML;

    tinymce_open();

    tinymce_setContent(initialData);

    document.getElementById("tinymce_save_button").setAttribute("onclick", "createIncidentGuidance(event)");
}

function createIncidentGuidance() {
    event.stopPropagation(); // prevents parent div element "tinymce_background_close" onclick event from firing, include this with every function bound to "tinymce_save_button"

    alert("Description Saved");

    var incident_id = global_current_incident_guidance_id;
    const uneditable_box = document.getElementById(`incident_guidance_uneditable_box_${incident_id}`);
    
    const guidance = tinymce.get("tinymce_editor_instance").getContent();


    const data = {
        incident_id: incident_id,
        incident_guidance: guidance
    };

    let ajax = new XMLHttpRequest();
    ajax.open('POST', app_root + '/admin_scripts/edit_incident_guidance.php', true);
    ajax.setRequestHeader('Content-type', 'application/json');

    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            uneditable_box.innerHTML = tinymce.get("tinymce_editor_instance").getContent();

            tinymce_close();

            openAdmin();
        }
    }
    ajax.send(JSON.stringify(data));
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



function polygon_manager_load_all_lines() {

    polygon_manager_clear_lines()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '';
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_manager_load_all_lines.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);

            var polygon_manager_data = this.responseText;

            if (polygon_manager_data === "") {
                // do nothing if data returned is <empty string>
            }

            else {
                polygon_manager_load_each_line(polygon_manager_data);
            }
        
        }
    
    }
    ajax_request.send(data_to_send);
}



function polygon_manager_clear_lines() {

    for (let x = 0; x <= polygon_manager_linecount; x++) {

        if (document.getElementById("polygon_line_" + x) !== null) {
                
            var line_to_delete = document.getElementById("polygon_line_" + x)
            line_to_delete.remove()

        }

    }

    polygon_manager_linecount = 0;

}



function polygon_manager_load_each_line(polygon_manager_data) {


    var polygon_manager_array = polygon_manager_data.split(',;')
    var polygon_manager_lines_to_load = polygon_manager_array.length / 7;

    for (let x = 0; x < polygon_manager_lines_to_load; x++) {

        var polygon_number = polygon_manager_array[7*x + 0];

        var area_type = polygon_manager_array[7*x + 1];

        var polygon_name = polygon_manager_array[7*x + 2];

        var polygon_date_raw = polygon_manager_array[7*x + 3].split("-");
        var polygon_date = polygon_date_raw[2] + "/" + polygon_date_raw[1] + "/" + polygon_date_raw[0];


        if (area_type == "Incident") {

            var impact_radius = polygon_manager_array[7*x + 4];

            var incident_start_date_raw = polygon_manager_array[7*x + 5].split("-");
            var incident_start_date = incident_start_date_raw[2] + "/" + incident_start_date_raw[1] + "/" + incident_start_date_raw[0];

            var incident_end_date_raw = polygon_manager_array[7*x + 6].split("-");
            var incident_end_date = incident_end_date_raw[2] + "/" + incident_end_date_raw[1] + "/" + incident_end_date_raw[0];

            polygon_manager_insert_line(polygon_number, area_type, incident_start_date, incident_end_date, polygon_name, impact_radius);
        }


        else {
            polygon_manager_insert_line(polygon_number, area_type, polygon_date, "", polygon_name, "");
        }


    }

}



var polygon_manager_linecount = 0;
function polygon_manager_insert_line(polygon_number, area_type, start_date, end_date, polygon_name, impact_radius) {

    polygon_manager_linecount++


    var polygon_line = document.createElement("div");
        polygon_line.setAttribute("class", "application_table_line");
        polygon_line.setAttribute("id", "polygon_line_" + polygon_manager_linecount);
        document.getElementById("polygon_table_body_id").appendChild(polygon_line);



    var polygon_cell_areatype = document.createElement("div");
        polygon_cell_areatype.setAttribute("class", "polygon_table_cell");
        polygon_cell_areatype.setAttribute("id", "polygon_cell_areatype_" + polygon_manager_linecount);
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_areatype)

    var polygon_text_areatype = document.createElement("p");
        polygon_text_areatype.setAttribute("class", "application_cell_text");
        polygon_text_areatype.setAttribute("id", "polygon_text_areatype_" + polygon_manager_linecount);
        polygon_text_areatype.innerText = area_type;
        document.getElementById("polygon_cell_areatype_" + polygon_manager_linecount).appendChild(polygon_text_areatype)   



    var polygon_cell_first_date = document.createElement("div");
        polygon_cell_first_date.setAttribute("class", "polygon_table_cell");
        polygon_cell_first_date.setAttribute("id", "polygon_cell_first_date_" + polygon_manager_linecount);
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_first_date)

    var polygon_text_first_date = document.createElement("p");
        polygon_text_first_date.setAttribute("class", "application_cell_text");
        polygon_text_first_date.setAttribute("id", "polygon_text_first_date_" + polygon_manager_linecount);
        polygon_text_first_date.innerText = start_date;
        document.getElementById("polygon_cell_first_date_" + polygon_manager_linecount).appendChild(polygon_text_first_date)



    var polygon_cell_second_date = document.createElement("div");
        polygon_cell_second_date.setAttribute("class", "polygon_table_cell");
        polygon_cell_second_date.setAttribute("id", "polygon_cell_second_date_" + polygon_manager_linecount);
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_second_date)

    var polygon_text_second_date = document.createElement("p");
        polygon_text_second_date.setAttribute("class", "application_cell_text");
        polygon_text_second_date.setAttribute("id", "polygon_text_second_date_" + polygon_manager_linecount);
        polygon_text_second_date.innerText = end_date;
        document.getElementById("polygon_cell_second_date_" + polygon_manager_linecount).appendChild(polygon_text_second_date)     



    var polygon_cell_name = document.createElement("div");
        polygon_cell_name.setAttribute("class", "polygon_table_cell");
        polygon_cell_name.setAttribute("id", "polygon_cell_name_" + polygon_manager_linecount);
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_name)

    var polygon_text_name = document.createElement("p");
        polygon_text_name.setAttribute("class", "application_cell_text");
        polygon_text_name.setAttribute("id", "polygon_text_name_" + polygon_manager_linecount);
        polygon_text_name.innerText = polygon_name;
        document.getElementById("polygon_cell_name_" + polygon_manager_linecount).appendChild(polygon_text_name)  



    var polygon_cell_radius = document.createElement("div");
        polygon_cell_radius.setAttribute("class", "polygon_table_cell");
        polygon_cell_radius.setAttribute("id", "polygon_cell_radius_" + polygon_manager_linecount);
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_radius)

    var polygon_text_radius = document.createElement("p");
        polygon_text_radius.setAttribute("class", "application_cell_text");
        polygon_text_radius.setAttribute("id", "polygon_text_radius_" + polygon_manager_linecount);
        polygon_text_radius.innerText = impact_radius;
        document.getElementById("polygon_cell_radius_" + polygon_manager_linecount).appendChild(polygon_text_radius) 



    var polygon_cell_view = document.createElement("div");
        polygon_cell_view.setAttribute("class", "polygon_table_cell_button");
        polygon_cell_view.setAttribute("id", "polygon_cell_view_" + polygon_manager_linecount);
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_view)

    var polygon_picture_view = document.createElement("div");
        polygon_picture_view.setAttribute("class", "application_view_button");
        polygon_picture_view.setAttribute("id", "polygon_picture_view_" + polygon_manager_linecount);
        polygon_picture_view.setAttribute("data-polygon_number", polygon_number);
        polygon_picture_view.setAttribute("onclick", "polygon_manager_view_clicked(this.id)");
        document.getElementById("polygon_cell_view_" + polygon_manager_linecount).appendChild(polygon_picture_view) 
    
    // Remove view incidents if user does not have permission to view
    if (area_type == "Incident" && !resource_permissions.canReadIncidents) {
        document.getElementById("polygon_line_" + polygon_manager_linecount).remove();
    }
    
    var polygon_cell_edit = document.createElement("div");
        polygon_cell_edit.setAttribute("class", "polygon_table_cell_button");
        polygon_cell_edit.setAttribute("id", "polygon_cell_edit_" + polygon_manager_linecount);
        

    var polygon_picture_edit = document.createElement("div");
        polygon_picture_edit.setAttribute("class", "application_edit_button");
        polygon_picture_edit.setAttribute("id", "polygon_picture_edit_" + polygon_manager_linecount);
        polygon_picture_edit.setAttribute("data-polygon_number", polygon_number);
        polygon_picture_edit.setAttribute("onclick", "polygon_manager_edit_clicked(this.id)");
        
    
    if (area_type != "Incident" && resource_permissions.canEditDangerzones) {
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_edit);
        document.getElementById("polygon_cell_edit_" + polygon_manager_linecount).appendChild(polygon_picture_edit);
    }

    if (area_type == "Incident" && resource_permissions.canEditIncidents) {
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_edit);
        document.getElementById("polygon_cell_edit_" + polygon_manager_linecount).appendChild(polygon_picture_edit);
    }


    var polygon_cell_delete = document.createElement("div");
        polygon_cell_delete.setAttribute("class", "polygon_table_cell_button");
        polygon_cell_delete.setAttribute("id", "polygon_cell_delete_" + polygon_manager_linecount);
        
    var polygon_picture_delete = document.createElement("div");
        polygon_picture_delete.setAttribute("class", "application_delete_button");
        polygon_picture_delete.setAttribute("id", "polygon_picture_delete_" + polygon_manager_linecount);
        polygon_picture_delete.setAttribute("data-polygon_number", polygon_number);
        polygon_picture_delete.setAttribute("data-line_number", polygon_manager_linecount);
        polygon_picture_delete.setAttribute("onclick", "polygon_manager_delete_clicked(this.id)");
        

    if (area_type != "Incident" && resource_permissions.canDeleteDangerzones) {
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_delete);
        document.getElementById("polygon_cell_delete_" + polygon_manager_linecount).appendChild(polygon_picture_delete);
    }

    if (area_type == "Incident" && resource_permissions.canDeleteIncidents) {
        document.getElementById("polygon_line_" + polygon_manager_linecount).appendChild(polygon_cell_delete);
        document.getElementById("polygon_cell_delete_" + polygon_manager_linecount).appendChild(polygon_picture_delete);
    }


}














function polygon_load_visual_zone(polygon_number) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_load_visual_zone.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText)

            var polygon_coords_data = this.responseText.split(",;")
            var polygon_coords_amount = polygon_coords_data.length / 2;

            var polygon_coordinates = [];
            for (var x = 0; x < polygon_coords_amount; x++) {

                var longitude = polygon_coords_data[2*x + 1];
                var latitude = polygon_coords_data[2*x + 0];

                polygon_coordinates[x] = [longitude, latitude];

            }
            

            var map_polygon_line = map.getSource('polygon_line');

            map_polygon_line.setData({
                'type': 'Feature',
                'properties': {},
                'geometry': {
                'type': 'Polygon',
                'coordinates': [polygon_coordinates]
                }
            });
            
        }
    }
    ajax_request.send(data_to_send);

}


var global_incident_single_marker = null;
function polygon_load_visual_details(polygon_number) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_load_visual_details.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            //console.log(this.responseText);

            var polygon_info_data = this.responseText.split(",;");
            var polygon_colour = polygon_info_data[0];
            var polygon_type = polygon_info_data[1];
            var incident_longitude = polygon_info_data[2];
            var incident_latitude = polygon_info_data[3];
            var incident_radius = polygon_info_data[4]; // not needed for this script
            var longitude = polygon_info_data[5];
            var latitude = polygon_info_data[6];

            incident_remove_single_marker();

            if (polygon_colour) {
                map.setPaintProperty('polygon_middle', 'fill-color', polygon_colour);
            }

            if (polygon_type == "Incident") {

                const incident_marker = document.createElement('div');
                incident_marker.style.backgroundImage = 'url(' + document_root + '/assets/incident_marker.png)';
                incident_marker.style.backgroundSize = 'cover';
                incident_marker.style.backgroundPosition = 'center';
                incident_marker.setAttribute('class','single_incident_marker');
                incident_marker.style.width = '25px';
                incident_marker.style.height = '25px';

                global_incident_single_marker = new mapboxgl.Marker({
                    anchor: 'bottom',
                    element: incident_marker,
                    rotation: 0
                  })
                .setLngLat([incident_longitude, incident_latitude])
                .addTo(map);

                map.flyTo({center: [incident_longitude, incident_latitude], zoom:4.0});

            }

            else if (longitude && latitude) {
                map.flyTo({center: [longitude, latitude], zoom:4.0});
            }

        }
    }
    ajax_request.send(data_to_send);

}


function incident_remove_single_marker() {

    var single_incident_marker_class = document.getElementsByClassName('single_incident_marker');

    while(single_incident_marker_class[0]) {
        single_incident_marker_class[0].parentNode.removeChild(single_incident_marker_class[0]);
        global_incident_single_marker = null;
    }

}



function polygon_manager_view_clicked(passed_id) {

    var polygon_number = document.getElementById(passed_id).getAttribute("data-polygon_number");

    optionsClose();

    polygon_load_visual_zone(polygon_number);
    polygon_load_visual_details(polygon_number); // polygon_number, close_menu, open_polygon

}



var global_polygon_being_edited = false; // global variable, is true when polygon is being edited, helps with loading correct elements

function polygon_manager_edit_clicked(passed_id) {

    global_polygon_being_edited = true; // set true when polygon is being edited

    var polygon_number = document.getElementById(passed_id).getAttribute("data-polygon_number");

    polygon_show_description();

    optionsClose(1); // keep close button

    polygon_edit_load_coordinates(polygon_number);
    polygon_edit_load_details(polygon_number); // have to load in details beforehand, so the visible DMZ isnt cleared by the area_type change to "Incident"

    polygon_load_visual_zone(polygon_number);
    polygon_load_visual_details(polygon_number); // polygon_number, close_menu, open_polygon

    document.getElementById("polygon_edit_box").style.left = "10px"; 


}


function polygon_edit_load_coordinates(polygon_number) {

    document.getElementById("polygon_coordinate_box").innerHTML = "";

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_edit_load_coordinates.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var polygon_coords_data = this.responseText.split(",;");
            var polygon_type = polygon_coords_data[0];

            if (polygon_type == "JWC") { // locks JWC area type/coordinates if user attempts to edit one

                document.getElementById("polygon_coordinate_box").innerHTML = "For JWC changes contact Sensor Magic";

                document.getElementById("polygon_area_type_select").disabled = true; 
                document.getElementById("polygon_area_type_select").style.cursor = "not-allowed";

                document.getElementById("polygon_coordinate_box").setAttribute("contenteditable", false);
                document.getElementById("polygon_coordinate_box").style.cursor = "not-allowed";

            }

            else if (polygon_type == "Incident") {

                var incident_latitude = Number(polygon_coords_data[1]).toFixed(5);
                var incident_longitude = Number(polygon_coords_data[2]).toFixed(5);

                document.getElementById("polygon_coordinate_box").innerHTML = incident_latitude + "  " + incident_longitude + "<br>"

            }

            else {

                var polygon_coords_amount = (polygon_coords_data.length / 2) - 1
                for (let x = 0; x < polygon_coords_amount; x++) {

                    var latitude = Number(polygon_coords_data[2*x + 0]).toFixed(5);
                    var longitude = Number(polygon_coords_data[2*x + 1]).toFixed(5);

                    document.getElementById("polygon_coordinate_box").innerHTML += latitude + "  " + longitude + "<br>"

                }
            }

        }
    }
    ajax_request.send(data_to_send);

}



function polygon_edit_load_details(polygon_number) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_edit_load_details.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var polygon_details_data = this.responseText.split(",;");

            var polygon_number = Number(polygon_details_data[0]);
            var polygon_name = polygon_details_data[1];
            var area_type = polygon_details_data[2];
            var polygon_radius = polygon_details_data[3];
            var polygon_colour = polygon_details_data[4];
            var incident_type = polygon_details_data[5];
            var incident_start_date = polygon_details_data[6];
            var incident_end_date = polygon_details_data[7];
            var polygon_risk_rating = Number(polygon_details_data[8]);
            var region_min_risk_rating = Number(polygon_details_data[9]);
            var region_max_risk_rating = Number(polygon_details_data[10]);
            var incident_start_time = polygon_details_data[11].slice(0,5); // .slice(0,5) ensures only the hours/minutes are taken, and seconds are excluded from being shown
            var incident_end_time = polygon_details_data[12].slice(0,5); // .slice(0,5) ensures only the hours/minutes are taken, and seconds are excluded from being shown
            var incident_region = polygon_details_data[13];
            var incident_source_confidence = Number(polygon_details_data[14]);

            document.getElementById("polygon_description_button").setAttribute("data-polygon_number", polygon_number) // sets polygon_number as the data value on the description button (for use in description functions)
            document.getElementById("polygon_save_button").setAttribute("data-polygon_number", polygon_number); // sets polygon_number as the data value on the save button (for use in edit/add functions)

            document.getElementById("polygon_name_input").value = polygon_name;
            document.getElementById("polygon_area_type_select").value = area_type;
            document.getElementById("polygon_colour_input").value = polygon_colour;

            polygon_area_type_selected(true); // first_load variable, if true dont remove existing incident/polygon data from box

            if (area_type == "JWC" || area_type == "EOS" || area_type == "Other") {

                set_polygon_risk_rating(polygon_risk_rating);

            }

            else if (area_type == "Incident") {

                document.getElementById("polygon_incident_input").value = incident_type;
                document.getElementById("polygon_impact_radius_input").value = polygon_radius;
                document.getElementById("incident_start_date_input").value = incident_start_date;
                document.getElementById("incident_end_date_input").value = incident_end_date;
                document.getElementById("incident_start_time_input").value = incident_start_time;
                document.getElementById("incident_end_time_input").value = incident_end_time;
                document.getElementById("incident_region_dropdown").value = incident_region;

                set_incident_source_confidence(incident_source_confidence)
                set_polygon_risk_rating(polygon_risk_rating);

            }

            else if (area_type == "Region") {

                set_region_min_risk_rating(region_min_risk_rating);
                set_region_max_risk_rating(region_max_risk_rating);

            }

            else {
                alert("area_type error")
            }

        }
    }
    ajax_request.send(data_to_send);

}


function polygon_area_type_selected(first_load) {

    var area_type = document.getElementById("polygon_area_type_select").value

    if (area_type == "JWC") {

        if (global_polygon_description_hidden == true) { // if description box is hidden, give more height to the coordinate box
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 100px)"
        }
        else if (global_polygon_description_hidden == false) {
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 150px)"
        }
        else {
            console.log("global_polygon_description_hidden error")
        }

        enable_grabber();

        polygon_disable_plotting();
        incident_disable_plotting();

        display_polygon_risk_rating();

        if (first_load != true) {
            remove_existing_incident_map();
        }

        polygon_hide_incident_elements()

        if (global_polygon_being_edited == true) {
            polygon_show_description()  
        }

        if (global_polygon_being_edited == false) {

            document.getElementById("polygon_colour_input").value = "#0064ff";
            polygon_change_colour()
            
        }

    }

    else if (area_type == "Incident") {

        if (global_polygon_description_hidden == true) { // if description box is hidden, give more height to the coordinate box
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 200px)"
        }
        else if (global_polygon_description_hidden == false) {
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 250px)"
        }
        else {
            console.log("global_polygon_description_hidden error")
        }

        enable_crosshair();

        display_polygon_risk_rating();

        polygon_disable_plotting();
        incident_enable_plotting();

        if (first_load != true) {
            remove_existing_polygon_map();
        }

        document.getElementById("polygon_incident_box").style.display = "block";
        document.getElementById("polygon_incident_para").style.display = "block";
        document.getElementById("polygon_incident_input").style.display = "inline";
        document.getElementById("polygon_incident_add_type_btn").style.display = "inline";

        document.getElementById("polygon_impact_radius_box").style.display = "block";
        document.getElementById("polygon_impact_radius_para").style.display = "block";
        document.getElementById("polygon_impact_radius_input").style.display = "block";

        document.getElementById("incident_start_date_box").style.display = "block";
        document.getElementById("incident_start_date_para").style.display = "block";
        document.getElementById("incident_start_date_input").style.display = "block";

        document.getElementById("incident_end_date_box").style.display = "block";
        document.getElementById("incident_end_date_para").style.display = "block";
        document.getElementById("incident_end_date_input").style.display = "block";

        document.getElementById("incident_start_time_box").style.display = "block";
        document.getElementById("incident_start_time_para").style.display = "block";
        document.getElementById("incident_start_time_input").style.display = "block";
        document.getElementById("incident_end_time_box").style.display = "block";
        document.getElementById("incident_end_time_para").style.display = "block";
        document.getElementById("incident_end_time_input").style.display = "block";

        document.getElementById("polygon_disable_email_box").style.display = "block";
        document.getElementById("incident_region_box").style.display = "block";
        document.getElementById("incident_source_confidence_box").style.display = "block";
        document.getElementById("incident_preview_box").style.display = "block";
        document.getElementById("incident_description_box").style.display = "block";

        if (global_polygon_being_edited == true) {

            document.getElementById("incident_preview_box").style.display = "none";
            document.getElementById("incident_description_box").style.display = "none";

            polygon_show_description();
        }

        if (global_polygon_being_edited == false) {

            document.getElementById("incident_start_date_input").valueAsDate = new Date();
            document.getElementById("incident_end_date_input").valueAsDate = new Date();

            document.getElementById("polygon_colour_input").value = "#A020F0";
            polygon_change_colour()

        }

    }

    else if (area_type == "Region") {

        if (global_polygon_description_hidden == true) { // if description box is hidden, give more height to the coordinate box
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 100px)"
        }
        else if (global_polygon_description_hidden == false) {
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 150px)"
        }
        else {
            console.log("global_polygon_description_hidden error")
        }

        enable_crosshair();

        display_region_risk_rating();

        polygon_enable_plotting();
        incident_disable_plotting();

        if (first_load != true) {
            remove_existing_incident_map();
        }

        polygon_hide_incident_elements()

        document.getElementById("incident_description_box").style.display = "none";

        if (global_polygon_being_edited == true) {
            polygon_show_description()  
        }

        if (global_polygon_being_edited == false) {

            document.getElementById("polygon_colour_input").value = "#0064ff";
            polygon_change_colour()
            
        }

    }

    else if (area_type == "EOS" || area_type == "Other") { // covers "EOS" and "Other"

        if (global_polygon_description_hidden == true) { // if description box is hidden, give more height to the coordinate box
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 100px)"
        }
        else if (global_polygon_description_hidden == false) {
            document.getElementById("polygon_coordinate_box").style.height = "calc(100% - 150px)"
        }
        else {
            console.log("global_polygon_description_hidden error")
        }

        enable_crosshair();

        display_polygon_risk_rating();

        polygon_enable_plotting();
        incident_disable_plotting();

        if (first_load != true) {
            remove_existing_incident_map();
        }

        polygon_hide_incident_elements()

        if (global_polygon_being_edited == true) {
            polygon_show_description()  
        }

        if (global_polygon_being_edited == false) {

            document.getElementById("polygon_colour_input").value = "#0064ff";
            polygon_change_colour()
            
        }

    }

    else {
        console.log("area_type error");
    }


}


function load_incident_types() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/load_incident_types.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);
            const incidentInput = document.getElementById("polygon_incident_input");
            
            // Clear the select box
            [].forEach.call([].slice.call(incidentInput.children), e => { e.remove(); });

            var incident_category_split = this.responseText.split("___")

            for (let x = 0; x < (incident_category_split.length / 2); x++) {

                var incident_optgroup = incident_category_split[(2*x + 0)]

                var new_optgroup = document.createElement('optgroup');
                new_optgroup.label = incident_optgroup;
                incidentInput.appendChild(new_optgroup)


                var incident_option_array = incident_category_split[(2*x + 1)].split(",;")

                for (let x = 0; x < incident_option_array.length; x++) {

                    var new_option = document.createElement('option');
                    new_option.value = incident_option_array[x];
                    new_option.innerHTML = incident_option_array[x];
                    incidentInput.appendChild(new_option)

                }

            }

        }
    }
    ajax_request.send(data_to_send);

}
load_incident_types()

function load_incident_type_categories() {
    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/load_incident_type_categories.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            const responseData = JSON.parse(this.responseText);
            const categorySelect = document.getElementById("new_incident_type_category");

            if (Array.isArray(responseData)) {
                categorySelect.options.length = 0;
                for (let i = 0; i < responseData.length; i++) {
                    const incident_category = responseData[i];
                    var new_optgroup = document.createElement('option');
                    new_optgroup.label = incident_category;
                    new_optgroup.value = incident_category;
                    categorySelect.appendChild(new_optgroup)
                }
            } else {
                alert("Error loading incident categories");
                console.log(this.responseText);
            }
        }
    }
    ajax_request.send(data_to_send);
}

function hasOptGroup(select, value) {
    for (let i = 0; i < select.children.length; i++) {
        if (select.children[i].tagName == "OPTGROUP" && select.children[i].label === value) {
            return true;
        }
    }
    return false;
}

function incident_type_create_save(event) {
    event.preventDefault();
    var incident_category = document.getElementById("new_incident_type_category").value;
    var new_incident_type = document.getElementById("new_incident_type_name").value;
    var ajax_request = new XMLHttpRequest();
    var data_to_send = JSON.stringify({"incident_category": incident_category, "incident_type": new_incident_type});

    ajax_request.open('POST', '' + app_root + '/polygons/add_incident_type.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/json');
    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
            try {
                const responseData = JSON.parse(this.responseText);
                const incident_select = document.getElementById("polygon_incident_input");
                if (responseData.hasOwnProperty("new_category") && responseData.hasOwnProperty("incident_type")) {
                    if (!hasOptGroup(incident_select, responseData.new_category)) {
                        var optGroup = document.createElement('optgroup');
                        optGroup.label = responseData.new_category;
                        incident_select.appendChild(optGroup)
                    } else {
                        // Get the existing optgroup
                        var optGroup = incident_select.querySelector("optgroup[label='" + responseData.new_category + "']");
                    }
                    //optGroup.insertAdjacentText("afterend", `<option value="${responseData.incident_type}">${responseData.incident_type}</option>`);
                    var new_option = document.createElement('option');
                    new_option.value = responseData.incident_type;
                    new_option.innerText = responseData.incident_type;
                    optGroup.after(new_option);
                    incident_select.value = responseData.incident_type;
                }
                polygon_add_incident_type_close();
            } catch (error) {
                alert("Error loading incident categories");
                console.log(error);
            }
            //incident_select.options.length = 0;
            //load_incident_types();

        }
    };
    ajax_request.send(data_to_send);
}

// Add new incident type of existing category
function polygon_add_incident_type() {
    const add_incident_type_form = document.getElementById("add_incident_type_form");
    add_incident_type_form.style.display = "block";
    load_incident_type_categories();
}

function polygon_add_incident_type_submit() {
    add_incident_type_form.addEventListener("submit", function(event) {
        event.preventDefault();
        var incident_category = document.getElementById("incident_category_input").value;
        var new_incident_type = document.getElementById("incident_type_input").value;
        var ajax_request = new XMLHttpRequest();
        var data_to_send = ''
        ajax_request.open('POST', '' + app_root + '/load_data/add_incident_type.php', true);
        ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete
        ajax_request.onreadystatechange = function() {
            if(ajax_request.readyState == 4 && this.status == 200) {
                const incident_select = document.getElementById("polygon_incident_input");
                incident_select.options.length = 0;
            }
        };
        ajax_request.send(new FormData(add_incident_type_form));
    });
}

function polygon_add_incident_type_close() {
    const add_incident_type_form = document.getElementById("add_incident_type_form");
    add_incident_type_form.style.display = "none";
    add_incident_type_form.reset();
}

var incident_plotting_enabled = false;
function incident_enable_plotting() {
    incident_plotting_enabled = true;
}

function incident_disable_plotting() {
    incident_plotting_enabled = false;
}


polygon_plotting_enabled = false;
function polygon_enable_plotting() {
    polygon_plotting_enabled = true;
}

function polygon_disable_plotting() {
    polygon_plotting_enabled = false;
}


function polygon_plot_point(latitude_clicked, longitude_clicked) {
    
    var latitude = Number(latitude_clicked).toFixed(5);
    var longitude = Number(longitude_clicked).toFixed(5);
    var text_to_convert = document.getElementById("polygon_coordinate_box").innerText; // gets the text the user has entered in the coordinate box

    if (text_to_convert.includes("Â°") == false) { // if no Â° symbol, the text must be in DD format

        document.getElementById("polygon_coordinate_box").innerHTML += latitude + "  " + longitude + "<br>";

    }
    else if (text_to_convert.includes("Â°") == true && text_to_convert.includes(".") == true && text_to_convert.includes("\"") == false) { // if Â° and . but no " the text must be in DMS format

        document.getElementById("polygon_coordinate_box").innerHTML += lat_to_dm(latitude) + "  " + long_to_dm(longitude) + "<br>";

    }   
    else if (text_to_convert.includes("Â°") == true && text_to_convert.includes("\"") == true) { // if Â° and " the text must be in DMS format

        document.getElementById("polygon_coordinate_box").innerHTML += lat_to_dms(latitude) + "  " + long_to_dms(longitude) + "<br>";

    }

    document.getElementById("polygon_coordinate_box").scrollTop = document.getElementById("polygon_coordinate_box").scrollHeight; // scrolls to the bottom of "polygon_coordinate_box" every time a new point is plotted

}

var global_incident_single_marker = null;
function incident_plot_point(latitude_clicked, longitude_clicked, keep_box) {

    var incident_latitude = Number(latitude_clicked).toFixed(5);
    var incident_longitude = Number(longitude_clicked).toFixed(5);

    if (keep_box != true) {
        document.getElementById("polygon_coordinate_box").innerHTML = incident_latitude + "  " + incident_longitude + "<br>";
    }


// Setting Incident Marker /////////////////////////////////////////////////////////////////////////////////////////////////////////

    incident_remove_single_marker();

    const incident_marker = document.createElement('div');
    incident_marker.style.backgroundImage = 'url(' + document_root + '/assets/incident_marker.png)';
    incident_marker.style.backgroundSize = 'cover';
    incident_marker.style.backgroundPosition = 'center';
    incident_marker.setAttribute('class','single_incident_marker');
    incident_marker.style.width = '25px';
    incident_marker.style.height = '25px';

    global_incident_single_marker = new mapboxgl.Marker({
        anchor: 'bottom',
        element: incident_marker,
        rotation: 0
      })
    .setLngLat([incident_longitude, incident_latitude])
    .addTo(map);


// Setting Incident Polygon /////////////////////////////////////////////////////////////////////////////////////////////////////////

    var incident_radius = document.getElementById("polygon_impact_radius_input").value * 1.15078 // adds polygon_radius (multiply by 1.15078 to convert nautical miles to miles)

    if (incident_radius > 0) {

        var point = turf.point([Number(incident_longitude), Number(incident_latitude)]);
        var incident_polygon_buffer = turf.buffer(point, incident_radius, {units: 'miles'});
        var incident_polygon_coordinates = incident_polygon_buffer.geometry.coordinates


        var map_polygon_line = map.getSource('polygon_line');

        map_polygon_line.setData({
            'type': 'Feature',
            'properties': {},
            'geometry': {
            'type': 'Polygon',
            'coordinates': incident_polygon_coordinates
            }
        });

    }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}


document.getElementById("polygon_impact_radius_input").addEventListener("input", incident_radius_updated);
function incident_radius_updated() {

    var incident_radius = document.getElementById("polygon_impact_radius_input").value * 1.15078 // adds polygon_radius (multiply by 1.15078 to convert nautical miles to miles)

    if (global_incident_single_marker && incident_radius > 0) {

        var incident_latitude = global_incident_single_marker._lngLat.lat
        var incident_longitude = global_incident_single_marker._lngLat.lng

        var point = turf.point([Number(incident_longitude), Number(incident_latitude)]);
        var incident_polygon_buffer = turf.buffer(point, incident_radius, {units: 'miles'});
        var incident_polygon_coordinates = incident_polygon_buffer.geometry.coordinates


        var map_polygon_line = map.getSource('polygon_line');

        map_polygon_line.setData({
            'type': 'Feature',
            'properties': {},
            'geometry': {
            'type': 'Polygon',
            'coordinates': incident_polygon_coordinates
            }
        });


    }

}


function remove_existing_incident_map(keep_box) {

    if (global_incident_single_marker) {

        if (keep_box != true) {
            document.getElementById("polygon_coordinate_box").innerHTML = "";
        }


        var map_polygon_line = map.getSource('polygon_line');

        map_polygon_line.setData({
            'type': 'Feature',
            'properties': {},
            'geometry': {
            'type': 'Polygon',
            'coordinates': []
            }
        });

        incident_remove_single_marker()
    }

}


function remove_existing_polygon_map() {

    document.getElementById("polygon_coordinate_box").innerHTML = "";


    var map_polygon_line = map.getSource('polygon_line');

    map_polygon_line.setData({
        'type': 'Feature',
        'properties': {},
        'geometry': {
        'type': 'Polygon',
        'coordinates': []
        }
    });

}


function polygon_description_clicked() {
    
    var polygon_number = document.getElementById("polygon_description_button").getAttribute("data-polygon_number")

    polygon_description_load(polygon_number)

}

function polygon_description_load(polygon_number) {

    tinymce_open()

    document.getElementById("tinymce_save_button").setAttribute("onclick", "polygon_description_save(event)");
    document.getElementById("tinymce_save_button").setAttribute("data-polygon_number", polygon_number);

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_description_load.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);
            
            tinymce_setContent(this.responseText)


        }
    
    }
    ajax_request.send(data_to_send);

}


function polygon_description_save() {
    event.stopPropagation(); // prevents parent div element "tinymce_background_close" onclick event from firing, include this with every function bound to "tinymce_save_button"

    alert("Description Saved")

    var polygon_number = document.getElementById("tinymce_save_button").getAttribute("data-polygon_number")
    var polygon_description = tinymce.get("tinymce_editor_instance").getContent()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'polygon_number=' + polygon_number
    + '&polygon_description=' + encodeURIComponent(polygon_description)
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_description_save.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            tinymce_close();

        }
    
    }
    ajax_request.send(data_to_send);

}



function polygon_change_colour() {

    var polygon_colour = document.getElementById("polygon_colour_input").value

    map.setPaintProperty('polygon_middle', 'fill-color', polygon_colour);

}




function polygon_update_visual_from_box() {

    var area_type = document.getElementById("polygon_area_type_select").value

    if (area_type == "JWC") { // handles updating JWCs on map
        // do nothing
    }

    else if (area_type == "Incident") { // handles updating Incidents on map
            
        // get coordinates from textbox, plot incident marker using these

        polygon_convert_coordinates();
        
        var polygon_coord_box_html = document.getElementById("polygon_coordinate_box").innerHTML; // gets the html inside the coordinate box

        if (global_polygon_coordinates.length == 1 && polygon_coord_box_html.includes("<span id=\"bold_test\">") == false) { // checks there are no error messages in the single Incident Coordinate

            var latitude = global_polygon_coordinates[0][1];
            var longitude = global_polygon_coordinates[0][0];

            incident_plot_point(latitude, longitude, true) // keep_box variable retains the data in the box

        }

        else {
            alert("There is a problem with the Incident Coordinates, please check them");
            remove_existing_incident_map(true) // keep_box variable retains the data in the box
        }

    }

    else { // handles updating Eos/Region/Other DMZs on map

        polygon_convert_coordinates() // global_polygon_coordinates now defined
            
        var polygon_coord_box_html = document.getElementById("polygon_coordinate_box").innerHTML; // gets the html inside the coordinate box

        if (polygon_coord_box_html.includes("<span id=\"bold_test\">") == true) {
            alert("There is a problem with the DMZ Coordinates, please check them");
        }

        var map_polygon_line = map.getSource('polygon_line');

        map_polygon_line.setData({
            'type': 'Feature',
            'properties': {},
            'geometry': {
            'type': 'Polygon',
            'coordinates': [global_polygon_coordinates]
            }
        });

    }
}


function polygon_view_visual_from_box() {

    var area_type = document.getElementById("polygon_area_type_select").value

    if (area_type == "Incident") {

        if (global_incident_single_marker) { // if incident marker exists on map

            var incident_latitude = global_incident_single_marker._lngLat.lat
            var incident_longitude = global_incident_single_marker._lngLat.lng

            map.flyTo({center: [incident_longitude, incident_latitude], zoom:4});

        }
        else {
            // do nothing
        }

    }

    else {

        var polygon_coordinates = map.getSource('polygon_line')._data.geometry.coordinates[0]

        if (polygon_coordinates.length > 0) { // if polygon exists on map

            map.flyTo({center: polygon_coordinates[0], zoom:4});

        }
        else {
            // do nothing        
        }

    }
}








var global_polygon_coordinates = []; // this array will hold the raw decimal converted values
function polygon_convert_coordinates() {

    global_polygon_coordinates = []; // resets array incase it has already been defined

    var text_to_convert = document.getElementById("polygon_coordinate_box").innerText; // gets the text the user has entered in the coordinate box
    var text_string = "";



    // Decimal Conversion
    if (text_to_convert.includes("Â°") == false) { // if no Â° symbol, the text must be in DD format

        // alert("text is DD");

        text_to_convert = text_to_convert.replace(/\s+/g, ":"); // replaces any length of \s whitespace with a single :
        text_to_convert = text_to_convert.replace(/^:*/, ""); // replaces all : at start of string with ""
        text_to_convert = text_to_convert.replace(/:*$/, ""); // replaces all : at end of string with ""

        var single_coordinate_array = text_to_convert.split(":"); // splits the newly segmented string into an array, between every :

        for (let x = 0; x < single_coordinate_array.length; x+=2) { // increments by 2 each time

            if (x+1 == single_coordinate_array.length) {
                text_string = text_string + '<span id="bold_test">' + single_coordinate_array[x] + '</span>' + '  '
            }

            else {

                var latitude_raw = single_coordinate_array[x]
                var longitude_raw = single_coordinate_array[x+1]

                var latitude_decimal = Number(single_coordinate_array[x]).toFixed(5); // conversion equation removes front 0s and limits decimal length to 5 decimal places
                var longitude_decimal = Number(single_coordinate_array[x+1]).toFixed(5);

                if (latitude_decimal > -90 && latitude_decimal < 90) { // if lat is correct, add it without error marker
                    text_string = text_string + latitude_decimal + '  '
                }
                else { // if lat is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + latitude_raw + '</span>' + '  '
                }


                if (longitude_decimal > -180 && longitude_decimal < 180) { // if long is correct, add it without error marker
                    text_string = text_string + longitude_decimal + '<br>'
                }
                else { // if long is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + longitude_raw + '</span>' + '<br>'
                }


                if (latitude_decimal > -90 && latitude_decimal < 90 && longitude_decimal > -180 && longitude_decimal < 180) { // if both coordinates are correct, add them to creation array to be displayed on map
                    global_polygon_coordinates.push([longitude_decimal, latitude_decimal])
                }
                else {
                    // do nothing, dont try to display the coordinates on map
                }

            }

        }

    }












    // Degrees Minutes Conversion
    else if (text_to_convert.includes("Â°") == true && text_to_convert.includes(".") == true && text_to_convert.includes("\"") == false) { // if Â° and . but no " the text must be in DMS format
        
        // alert("text is DM");
        
        text_to_convert = text_to_convert.replace(/\s/g, ""); // replaces all \s whitespace with ""

        text_to_convert = text_to_convert.replace(/N/g, "N:"); // replaces all N with N:
        text_to_convert = text_to_convert.replace(/E/g, "E:"); // replaces all E with E:
        text_to_convert = text_to_convert.replace(/S/g, "S:"); // replaces all S with S:
        text_to_convert = text_to_convert.replace(/W/g, "W:"); // replaces all W with W:

        text_to_convert = text_to_convert.replace(/:*$/, ""); // replaces all : at end of string with ""

        var single_coordinate_array = text_to_convert.split(":"); // splits the newly segmented string into an array, between every :
        var amount_of_coordinates = single_coordinate_array.length;

        var evaluated_coordinate_array = [];
        for (let x = 0; x < amount_of_coordinates; x++) { // converts single_coordinate_array to evaluated_coordinate_array

            var coordinate_dm = single_coordinate_array[x];
            var coordinate_dm_array = coordinate_dm.replace(/Â°/g, ":").replace(/\'/g, ":").split(":"); // replaces the Â° ' " symbols with : breaks to split to array, and calculate the raw value of the DM coordinate
            var coordinate_correct = "";
            var coordinate_type = "";

            // DM Latitude Check
            if (coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "N" || coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "S") { // validates the coordinate is Latitude and contains 5 segments

                coordinate_type = "latitude";

                var latitude_degrees = Number(coordinate_dm_array[0]); // splits latitude into sections, for use in conversion equation
                var latitude_minutes = Number(coordinate_dm_array[1]/60);
                var latitude_direction = Number(coordinate_dm_array[2].replace(/N/g, "1").replace(/S/g, "-1")); // replaces N with 1 and S with -1, for use in conversion equation
                
                var coordinate_raw = Number((latitude_degrees + latitude_minutes) * latitude_direction).toFixed(5); // conversion equation

                if (coordinate_raw >= -90 && coordinate_raw <= 90 && coordinate_dm_array[1] >= 0 && coordinate_dm_array[1] <= 60) { // validates all the lat are within the 180 bounds, and the minutes are within [0,60] bounds
                     coordinate_correct = true // latitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // dm Longitude Check
            else if (coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "E" || coordinate_dm_array.length == 3 && coordinate_dm_array[2] == "W") {

                coordinate_type = "longitude";

                var longitude_degrees = Number(coordinate_dm_array[0]);
                var longitude_minutes = Number(coordinate_dm_array[1]/60);
                var longitude_direction = Number(coordinate_dm_array[2].replace(/E/g, "1").replace(/W/g, "-1"));

                var coordinate_raw = Number((longitude_degrees + longitude_minutes) * longitude_direction).toFixed(5);

                if (coordinate_raw >= -180 && coordinate_raw <= 180 && coordinate_dm_array[1] >= 0 && coordinate_dm_array[1] <= 60) { // validates all the long are within 360 bounds, and the minutes are within [0,60] bounds
                    coordinate_correct = true // longitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // Only occurs if coordinate isnt in Latitude or Longitude format
            else {
                coordinate_type = "undefined"; // only sets these parameters to these values if an error occurs
                coordinate_correct = false;
                var coordinate_raw = "0";
            }

            evaluated_coordinate_array.push([coordinate_dm, coordinate_type, coordinate_correct, coordinate_raw]);

        }

        var text_output_array = [];
        for (let x = 0; x < evaluated_coordinate_array.length; x++) { // converts evaluated_coordinate_array to text_output_array

            if (x+1 == evaluated_coordinate_array.length) { // if x is at the final item in array, add it and dont look at x+1 to prevent errors
                text_output_array.push([evaluated_coordinate_array[x][0]])
            }

            else { // otherwise look normally at x and x+1 pairs

                if (evaluated_coordinate_array[x][1] == "latitude" && evaluated_coordinate_array[x+1][1] == "longitude") { // if lat long pair add them to the array and increment one extra to skip x+1
                    // console.log(evaluated_coordinate_array[x][0] + ", " + evaluated_coordinate_array[x+1][0])
                    text_output_array.push([evaluated_coordinate_array[x][0], evaluated_coordinate_array[x][2], evaluated_coordinate_array[x][3], evaluated_coordinate_array[x+1][0], evaluated_coordinate_array[x+1][2], evaluated_coordinate_array[x+1][3]])
                    x++ // increment one extra x to skip x+1
                }

                else { // else just add the single coordinate
                    text_output_array.push([evaluated_coordinate_array[x][0]])
                }

            }
            
        }

        for (let x = 0; x < text_output_array.length; x++) { // converts text_output_array to text_string

            if (text_output_array[x].length == 6) {

                var lat_dm = text_output_array[x][0]
                var lat_correct = text_output_array[x][1]
                var lat_decimal = text_output_array[x][2]
                var long_dm = text_output_array[x][3]
                var long_correct = text_output_array[x][4]
                var long_decimal = text_output_array[x][5]

                if (lat_correct == true) { // if lat is correct, add it without error marker
                    text_string = text_string + lat_dm + '  '
                }
                else { // if lat is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + lat_dm + '</span>' + '  '
                }


                if (long_correct == true) { // if long is correct, add it without error marker
                    text_string = text_string + long_dm + '<br>'
                }
                else { // if long is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + long_dm + '</span>' + '<br>'
                }


                if (lat_correct == true && long_correct == true) { // if both coordinates are correct, add them to creation array to be displayed on map
                    global_polygon_coordinates.push([long_decimal, lat_decimal])
                }
                else {
                    // do nothing, dont try to display the coordinates on map
                }

            }

            else { // coordinate is by itself on a line, add it with an error marker
                text_string = text_string + '<span id="bold_test">' + text_output_array[x] + '</span>' + '<br>'
            }

        }

    }















    // Degrees Minutes Seconds Conversion
    else if (text_to_convert.includes("Â°") == true && text_to_convert.includes("\"") == true) { // if Â° and " the text must be in DMS format
        
        // alert("text is DMS");
        
        text_to_convert = text_to_convert.replace(/\s/g, ""); // replaces all \s whitespace with ""

        text_to_convert = text_to_convert.replace(/N/g, "N:"); // replaces all N with N:
        text_to_convert = text_to_convert.replace(/E/g, "E:"); // replaces all E with E:
        text_to_convert = text_to_convert.replace(/S/g, "S:"); // replaces all S with S:
        text_to_convert = text_to_convert.replace(/W/g, "W:"); // replaces all W with W:

        text_to_convert = text_to_convert.replace(/:*$/, ""); // replaces all : at end of string with ""

        var single_coordinate_array = text_to_convert.split(":"); // splits the newly segmented string into an array, between every :
        var amount_of_coordinates = single_coordinate_array.length;

        var evaluated_coordinate_array = [];
        for (let x = 0; x < amount_of_coordinates; x++) { // converts single_coordinate_array to evaluated_coordinate_array

            var coordinate_dms = single_coordinate_array[x];
            var coordinate_dms_array = coordinate_dms.replace(/Â°/g, ":").replace(/\'/g, ":").replace(/\"/g, ":").split(":"); // replaces the Â° ' " symbols with : breaks to split to array, and calculate the raw value of the DMS coordinate
            var coordinate_correct = "";
            var coordinate_type = "";

            // DMS Latitude Check
            if (coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "N" || coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "S") { // validates the coordinate is Latitude and contains 5 segments

                coordinate_type = "latitude";

                var latitude_degrees = Number(coordinate_dms_array[0]); // splits latitude into sections, for use in conversion equation
                var latitude_minutes = Number(coordinate_dms_array[1]/60);
                var latitude_seconds = Number(coordinate_dms_array[2]/3600);
                var latitude_direction = Number(coordinate_dms_array[3].replace(/N/g, "1").replace(/S/g, "-1")); // replaces N with 1 and S with -1, for use in conversion equation
                
                var coordinate_raw = Number((latitude_degrees + latitude_minutes + latitude_seconds) * latitude_direction).toFixed(5); // conversion equation

                if (coordinate_raw >= -90 && coordinate_raw <= 90 && coordinate_dms_array[1] >= 0 && coordinate_dms_array[1] <= 60 && coordinate_dms_array[2] >= 0 && coordinate_dms_array[2] <= 60) { // validates all the lat are within the 180 bounds, and the minutes seconds are within [0,60] bounds
                    coordinate_correct = true // latitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // DMS Longitude Check
            else if (coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "E" || coordinate_dms_array.length == 4 && coordinate_dms_array[3] == "W") {

                coordinate_type = "longitude";

                var longitude_degrees = Number(coordinate_dms_array[0]);
                var longitude_minutes = Number(coordinate_dms_array[1]/60);
                var longitude_seconds = Number(coordinate_dms_array[2]/3600);
                var longitude_direction = Number(coordinate_dms_array[3].replace(/E/g, "1").replace(/W/g, "-1"));

                var coordinate_raw = Number((longitude_degrees + longitude_minutes + longitude_seconds) * longitude_direction).toFixed(5);

                if (coordinate_raw >= -180 && coordinate_raw <= 180 && coordinate_dms_array[1] >= 0 && coordinate_dms_array[1] <= 60 && coordinate_dms_array[2] >= 0 && coordinate_dms_array[2] <= 60) { // validates all the long are within 360 bounds, and the minutes seconds are within [0,60] bounds
                    coordinate_correct = true // longitude is of correct format
                }
                else {
                    coordinate_correct = false // coordinate has an error
                }

            }

            // Only occurs if coordinate isnt in Latitude or Longitude format
            else {
                coordinate_type = "undefined"; // only sets these parameters to these values if an error occurs
                coordinate_correct = false;
                var coordinate_raw = "0";
            }

            evaluated_coordinate_array.push([coordinate_dms, coordinate_type, coordinate_correct, coordinate_raw]);

        }

        var text_output_array = [];
        for (let x = 0; x < evaluated_coordinate_array.length; x++) { // converts evaluated_coordinate_array to text_output_array

            if (x+1 == evaluated_coordinate_array.length) { // if x is at the final item in array, add it and dont look at x+1 to prevent errors
                text_output_array.push([evaluated_coordinate_array[x][0]])
            }

            else { // otherwise look normally at x and x+1 pairs

                if (evaluated_coordinate_array[x][1] == "latitude" && evaluated_coordinate_array[x+1][1] == "longitude") { // if lat long pair add them to the array and increment one extra to skip x+1
                    // console.log(evaluated_coordinate_array[x][0] + ", " + evaluated_coordinate_array[x+1][0])
                    text_output_array.push([evaluated_coordinate_array[x][0], evaluated_coordinate_array[x][2], evaluated_coordinate_array[x][3], evaluated_coordinate_array[x+1][0], evaluated_coordinate_array[x+1][2], evaluated_coordinate_array[x+1][3]])
                    x++
                }

                else { // else just add the single coordinate
                    text_output_array.push([evaluated_coordinate_array[x][0]])
                }

            }
            
        }

        for (let x = 0; x < text_output_array.length; x++) { // converts text_output_array to text_string

            if (text_output_array[x].length == 6) {

                var lat_dms = text_output_array[x][0]
                var lat_correct = text_output_array[x][1]
                var lat_decimal = text_output_array[x][2]
                var long_dms = text_output_array[x][3]
                var long_correct = text_output_array[x][4]
                var long_decimal = text_output_array[x][5]

                if (lat_correct == true) { // if lat is correct, add it without error marker
                    text_string = text_string + lat_dms + '  '
                }
                else { // if lat is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + lat_dms + '</span>' + '  '
                }


                if (long_correct == true) { // if long is correct, add it without error marker
                    text_string = text_string + long_dms + '<br>'
                }
                else { // if long is incorrect, add it with error marker
                    text_string = text_string + '<span id="bold_test">' + long_dms + '</span>' + '<br>'
                }


                if (lat_correct == true && long_correct == true) { // if both coordinates are correct, add them to creation array to be displayed on map
                    global_polygon_coordinates.push([long_decimal, lat_decimal])
                }
                else {
                    // do nothing, dont try to display the coordinates on map
                }

            }

            else { // coordinate is by itself on a line, add it with an error marker
                text_string = text_string + '<span id="bold_test">' + text_output_array[x] + '</span>' + '<br>'
            }

        }

    }







    else {
        alert("The coordinates do not belong to any of the shown formats, please check them and try again");

    }


    document.getElementById("polygon_coordinate_box").innerHTML = text_string; // puts appended (bold/wavy underline) text back into contenteditable div



}




function polygon_save(passed_id) {

    var polygon_number = document.getElementById(passed_id).getAttribute("data-polygon_number");
    var polygon_coordinates = map.getSource('polygon_line')._data.geometry.coordinates[0]; // define polygon_coordinates before creation/save to prevent polygon being removed after save is clicked

    if (polygon_coordinates && polygon_coordinates.length >= 3) { // validate polygon_coordinates has atleast 4 coordinates on map

        if (polygon_number) { // edit procedure
            polygon_edit_update_details(polygon_number);
            polygon_edit_update_coordinates(polygon_number, polygon_coordinates);
        }

        else { // add procedure
            polygon_create_details(polygon_coordinates);
        }

    }

    else {
        alert("Please define a zone on the map with 4 or more coordinates");
    }

}

function polygon_edit_update_details(polygon_number) {

    var area_type = document.getElementById("polygon_area_type_select").value;
    var current_date = new Date().toLocaleDateString('en-CA');

    if (area_type == "JWC" || area_type == "EOS" || area_type == "Other") {

        var polygon_number = polygon_number;
        var polygon_date = current_date;
        var polygon_colour = document.getElementById("polygon_colour_input").value;
        var polygon_type = document.getElementById("polygon_area_type_select").value;
        var incident_type = "";
        var incident_longitude = "";
        var incident_latitude = "";
        var incident_start_date = "";
        var incident_end_date = "";
        var incident_start_time = "";
        var incident_end_time = "";
        var incident_region = "";
        var incident_source_confidence = "";
        var polygon_name = document.getElementById("polygon_name_input").value;
        var polygon_radius = "";
        var polygon_risk_rating = document.querySelector('input[name="polygon_risk_rating_radio"]:checked').value;
        var region_min_risk_rating = "";
        var region_max_risk_rating = "";

        // validate all data has been entered
        if (!polygon_date == true || !polygon_colour == true || !polygon_type == true || !polygon_name == true || !polygon_risk_rating == true) {
            
            alert ("Please check all DMZ fields are filled in");

            console.log("polygon_date: " + !polygon_date)
            console.log("polygon_colour: " + !polygon_colour)
            console.log("polygon_type: " + !polygon_type)
            console.log("polygon_name: " + !polygon_name)
            console.log("polygon_risk_rating: " + !polygon_risk_rating)

            return; // exit save function
        }
        else {
            // do nothing, polygon data has been validated
        }

    }

    else if (area_type == "Incident") {

        if (global_incident_single_marker) { // if incident marker exists on map
            var incident_longitude = global_incident_single_marker._lngLat.lng
            var incident_latitude = global_incident_single_marker._lngLat.lat
        }
        else {
            incident_longitude = "";
            incident_latitude = "";
        }

        var polygon_number = polygon_number;
        var polygon_date = current_date;
        var polygon_colour = document.getElementById("polygon_colour_input").value;
        var polygon_type = document.getElementById("polygon_area_type_select").value;
        var incident_type = document.getElementById("polygon_incident_input").value;
        var incident_longitude = incident_longitude;
        var incident_latitude = incident_latitude;
        var incident_start_date = document.getElementById("incident_start_date_input").value;
        var incident_end_date = document.getElementById("incident_end_date_input").value;
        var incident_start_time = document.getElementById("incident_start_time_input").value;
        var incident_end_time = document.getElementById("incident_end_time_input").value;
        var incident_region = document.getElementById("incident_region_dropdown").value;
        var incident_source_confidence = document.querySelector('input[name="incident_source_confidence_radio"]:checked').value;
        var polygon_name = document.getElementById("polygon_name_input").value;
        var polygon_radius = document.getElementById("polygon_impact_radius_input").value;
        var polygon_risk_rating = document.querySelector('input[name="polygon_risk_rating_radio"]:checked').value;
        var region_min_risk_rating = "";
        var region_max_risk_rating = "";

        // validate all data has been entered
        if (!polygon_date == true || !polygon_colour == true || !polygon_type == true || !incident_type == true || !incident_longitude == true || !incident_latitude == true || !incident_start_date == true || !incident_end_date == true || !incident_start_time == true || !incident_end_time == true || incident_region == true || !incident_source_confidence == true || !polygon_name == true || !polygon_radius == true || !polygon_risk_rating == true) {
            
            alert ("Please check all Incident fields are filled in, and that an incident is plotted on the map");

            console.log("polygon_date: " + !polygon_date)
            console.log("polygon_colour: " + !polygon_colour)
            console.log("polygon_type: " + !polygon_type)
            console.log("incident_type: " + !incident_type)
            console.log("incident_longitude: " + !incident_longitude)
            console.log("incident_latitude: " + !incident_latitude)
            console.log("incident_start_date: " + !incident_start_date)
            console.log("incident_end_date: " + !incident_end_date)
            console.log("incident_start_time: " + !incident_start_time)
            console.log("incident_end_time: " + !incident_end_time)
            console.log("incident_region: " + !incident_region)
            console.log("polygon_name: " + !polygon_name)
            console.log("polygon_radius: " + !polygon_radius)
            console.log("polygon_risk_rating: " + !polygon_risk_rating)

            return; // exit save function
        }
        else {
            // do nothing, incident data has been validated
        }

    }

    else if (area_type == "Region") {

        var polygon_number = polygon_number;
        var polygon_date = current_date;
        var polygon_colour = document.getElementById("polygon_colour_input").value;
        var polygon_type = document.getElementById("polygon_area_type_select").value;
        var incident_type = "";
        var incident_longitude = "";
        var incident_latitude = "";
        var incident_start_date = "";
        var incident_end_date = "";
        var incident_start_time = "";
        var incident_end_time = "";
        var incident_region = "";
        var incident_source_confidence = "";
        var polygon_name = document.getElementById("polygon_name_input").value;
        var polygon_radius = "";
        var polygon_risk_rating = "";
        var region_min_risk_rating = document.querySelector('input[name="region_min_risk_rating_radio"]:checked').value;
        var region_max_risk_rating = document.querySelector('input[name="region_max_risk_rating_radio"]:checked').value;

        // validate all data has been entered
        if (!polygon_date == true || !polygon_colour == true || !polygon_type == true || !polygon_name == true || !region_min_risk_rating == true || !region_max_risk_rating == true) {
            
            alert ("Please check all Region fields are filled in");

            console.log("polygon_date: " + !polygon_date)
            console.log("polygon_colour: " + !polygon_colour)
            console.log("polygon_type: " + !polygon_type)
            console.log("polygon_name: " + !polygon_name)
            console.log("region_min_risk_rating: " + !region_min_risk_rating)
            console.log("region_max_risk_rating: " + !region_max_risk_rating)

            return; // exit save function
        }
        else {
            // do nothing, polygon data has been validated
        }
        
    }

    else {
        console.log("area_type error");
    }


    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    + '&polygon_colour=' + polygon_colour
    + '&polygon_type=' + polygon_type
    + '&incident_type=' + incident_type
    + '&incident_longitude=' + incident_longitude
    + '&incident_latitude=' + incident_latitude
    + '&incident_start_date=' + incident_start_date
    + '&incident_end_date=' + incident_end_date
    + '&incident_start_time=' + incident_start_time
    + '&incident_end_time=' + incident_end_time
    + '&incident_region=' + incident_region
    + '&incident_source_confidence=' + incident_source_confidence
    + '&polygon_date=' + polygon_date
    + '&polygon_name=' + polygon_name
    + '&polygon_radius=' + polygon_radius
    + '&polygon_risk_rating=' + polygon_risk_rating
    + '&region_min_risk_rating=' + region_min_risk_rating
    + '&region_max_risk_rating=' + region_max_risk_rating
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_edit_update_details.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

        }
    }
    ajax_request.send(data_to_send);

}


function polygon_edit_update_coordinates(polygon_number, polygon_coordinates) {
    // deletes existing coordinates for polygon_number, and inserts new ones to update polygon coordinates for a polygon_number
    
    var area_type = document.getElementById("polygon_area_type_select").value

    if (area_type == "JWC") { // do nothing as JWC data should not be edited

        alert("DMZ Saved")
        optionsClose();
        optionsOpen();
        openDangerZones();

    }

    else { // update polygon coordinates for the
        
        var ajax_request = new XMLHttpRequest();
        var data_to_send = ''
        + 'polygon_number=' + polygon_number
        + '&coordinates=' + polygon_coordinates;
        ajax_request.open('POST', '' + app_root + '/polygons/polygon_edit_update_coordinates.php', true);
        ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

        ajax_request.onreadystatechange = function() {
            if(ajax_request.readyState == 4 && this.status == 200) {
                console.log(this.responseText);

                alert("DMZ Saved")
                optionsClose();
                optionsOpen();
                openDangerZones();

            }
        }
        ajax_request.send(data_to_send);

    }

}



function remove_incidents() {

    for (let x = 1; x <= global_incidents_loaded; x++) {

        map.removeLayer("incident_loaded_middle_" + x);
        map.removeLayer("incident_loaded_outline_" + x);
        map.removeSource("incident_loaded_" + x);

    } 

    remove_incident_markers()

    global_incidents_loaded = 0;
}



function remove_incident_markers() {

    var incident_markers_class = document.getElementsByClassName('incident_markers');

    while(incident_markers_class[0]) {
        incident_markers_class[0].parentNode.removeChild(incident_markers_class[0]);
    }
}


function close_polygon_menu() {

    remove_existing_incident_map();
    remove_existing_polygon_map();

    document.getElementById("polygon_name_input").value = "";
    document.getElementById("polygon_area_type_select").selectedIndex = 0;
    document.getElementById("polygon_colour_input").value = "#0064ff";

    map.setPaintProperty('polygon_middle', 'fill-color', '#0064ff');


    document.getElementById("polygon_incident_input").selectedIndex = 0;
    document.getElementById("polygon_impact_radius_input").value = "";
    document.getElementById("incident_start_date_input").value = "";
    document.getElementById("incident_end_date_input").value = "";
    document.getElementById("incident_start_time_input").value = "";
    document.getElementById("incident_end_time_input").value = "";

    document.getElementById("incident_description_preview").innerHTML = "";

    document.getElementById("polygon_area_type_select").disabled = false; 

    document.getElementById("polygon_coordinate_box").setAttribute("contenteditable", true);
    document.getElementById("polygon_coordinate_box").style.cursor = "text";

    set_polygon_risk_rating(1);
    set_region_min_risk_rating(1);
    set_region_max_risk_rating(1);
    incident_source_change_high(); // reset to default value of HIGH on polygon menu close

    polygon_area_type_selected();

    document.getElementById("polygon_description_button").removeAttribute("data-polygon_number");
    document.getElementById("polygon_save_button").removeAttribute("data-polygon_number");

    document.getElementById("polygon_edit_box").style.left = "-1000px"; 

}


function polygon_add_clicked() {

    global_polygon_being_edited = false; // set false when new polygon is being added

    polygon_hide_description();

    optionsClose(1);

    document.getElementById("polygon_edit_box").style.left = "10px";

}
    
var global_polygon_description_hidden = false;
function polygon_hide_description() {

    global_polygon_description_hidden = true;
    document.getElementById("polygon_description_para").style.display = "none";
    document.getElementById("polygon_description_button").style.display = "none";

}

function polygon_show_description() {

    global_polygon_description_hidden = false;
    document.getElementById("polygon_description_para").style.display = "block";
    document.getElementById("polygon_description_button").style.display = "block";

}

function polygon_create_details(polygon_coordinates) {

    var area_type = document.getElementById("polygon_area_type_select").value;
    var current_date = new Date().toLocaleDateString('en-CA');

    if (area_type == "JWC" || area_type == "EOS" || area_type == "Other") {

        var polygon_date = current_date;
        var polygon_colour = document.getElementById("polygon_colour_input").value;
        var polygon_type = document.getElementById("polygon_area_type_select").value;
        var incident_type = "";
        var incident_longitude = "";
        var incident_latitude = "";
        var incident_start_date = "";
        var incident_end_date = "";
        var incident_start_time = "";
        var incident_end_time = "";
        var incident_region = "";
        var incident_source_confidence = "";
        var incident_description = "";
        var polygon_name = document.getElementById("polygon_name_input").value;
        var polygon_radius = "";
        var polygon_risk_rating = document.querySelector('input[name="polygon_risk_rating_radio"]:checked').value;
        var region_min_risk_rating = "";
        var region_max_risk_rating = "";

        // validate all data has been entered
        if (!polygon_date == true || !polygon_colour == true || !polygon_type == true || !polygon_name == true || !polygon_risk_rating == true) {
            
            alert ("Please check all DMZ fields are filled in");

            console.log("polygon_date: " + !polygon_date)
            console.log("polygon_colour: " + !polygon_colour)
            console.log("polygon_type: " + !polygon_type)
            console.log("polygon_name: " + !polygon_name)
            console.log("polygon_risk_rating: " + !polygon_risk_rating)

            return; // exit save function
        }
        else {
            // do nothing, polygon data has been validated
        }

    }

    else if (area_type == "Incident") {

        if (global_incident_single_marker) { // if incident marker exists on map
            var incident_longitude = global_incident_single_marker._lngLat.lng
            var incident_latitude = global_incident_single_marker._lngLat.lat
        }
        else {
            incident_longitude = 0;
            incident_latitude = 0;
        }

        var polygon_date = current_date;
        var polygon_colour = document.getElementById("polygon_colour_input").value;
        var polygon_type = document.getElementById("polygon_area_type_select").value;
        var incident_type = document.getElementById("polygon_incident_input").value;
        var incident_longitude = incident_longitude;
        var incident_latitude = incident_latitude;
        var incident_start_date = document.getElementById("incident_start_date_input").value;
        var incident_end_date = document.getElementById("incident_end_date_input").value;
        var incident_start_time = document.getElementById("incident_start_time_input").value;
        var incident_end_time = document.getElementById("incident_end_time_input").value;
        var incident_region = document.getElementById("incident_region_dropdown").value;
        var incident_source_confidence = document.querySelector('input[name="incident_source_confidence_radio"]:checked').value;
        var incident_description = encodeURIComponent(global_incident_add_description_to_save); // assigned as global variable by tinymce editor, encode to prevent whitespace issue
        var polygon_name = document.getElementById("polygon_name_input").value;
        var polygon_radius = document.getElementById("polygon_impact_radius_input").value;
        var polygon_risk_rating = document.querySelector('input[name="polygon_risk_rating_radio"]:checked').value;
        var region_min_risk_rating = "";
        var region_max_risk_rating = "";

        // validate all data has been entered
        if (!polygon_date == true || !polygon_colour == true || !polygon_type == true || !incident_type == true || !incident_longitude == true || !incident_latitude == true || !incident_start_date == true || !incident_end_date == true || !incident_start_time == true || !incident_end_time == true || incident_region == true || !incident_source_confidence == true || !polygon_name == true || !polygon_radius == true || !polygon_risk_rating == true) {
            
            alert ("Please check all Incident fields are filled in, and that an incident is plotted on the map");

            console.log("polygon_date: " + !polygon_date)
            console.log("polygon_colour: " + !polygon_colour)
            console.log("polygon_type: " + !polygon_type)
            console.log("incident_type: " + !incident_type)
            console.log("incident_longitude: " + !incident_longitude)
            console.log("incident_latitude: " + !incident_latitude)
            console.log("incident_start_date: " + !incident_start_date)
            console.log("incident_end_date: " + !incident_end_date)
            console.log("incident_start_time: " + !incident_start_time)
            console.log("incident_end_time: " + !incident_end_time)
            console.log("incident_region: " + !incident_region)
            console.log("polygon_name: " + !polygon_name)
            console.log("polygon_radius: " + !polygon_radius)
            console.log("polygon_risk_rating: " + !polygon_risk_rating)

            return; // exit save function
        }
        else {
            // do nothing, incident data has been validated
        }

    }

    else if (area_type == "Region") {

        var polygon_date = current_date;
        var polygon_colour = document.getElementById("polygon_colour_input").value;
        var polygon_type = document.getElementById("polygon_area_type_select").value;
        var incident_type = "";
        var incident_longitude = "";
        var incident_latitude = "";
        var incident_start_date = "";
        var incident_end_date = "";
        var incident_start_time = "";
        var incident_end_time = "";
        var incident_region = "";
        var incident_source_confidence = "";
        var incident_description = "";
        var polygon_name = document.getElementById("polygon_name_input").value;
        var polygon_radius = "";
        var polygon_risk_rating = "";
        var region_min_risk_rating = document.querySelector('input[name="region_min_risk_rating_radio"]:checked').value;
        var region_max_risk_rating = document.querySelector('input[name="region_max_risk_rating_radio"]:checked').value;

        // validate all data has been entered
        if (!polygon_date == true || !polygon_colour == true || !polygon_type == true || !polygon_name == true || !region_min_risk_rating == true || !region_max_risk_rating == true) {
            
            alert ("Please check all Region fields are filled in");

            console.log("polygon_date: " + !polygon_date)
            console.log("polygon_colour: " + !polygon_colour)
            console.log("polygon_type: " + !polygon_type)
            console.log("polygon_name: " + !polygon_name)
            console.log("region_min_risk_rating: " + !region_min_risk_rating)
            console.log("region_max_risk_rating: " + !region_max_risk_rating)

            return; // exit save function
        }
        else {
            // do nothing, polygon data has been validated
        }

    }

    else {
        console.log("area_type error");
    }


    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_colour=' + polygon_colour
    + '&polygon_type=' + polygon_type
    + '&incident_type=' + incident_type
    + '&incident_longitude=' + incident_longitude
    + '&incident_latitude=' + incident_latitude
    + '&incident_start_date=' + incident_start_date
    + '&incident_end_date=' + incident_end_date
    + '&incident_start_time=' + incident_start_time
    + '&incident_end_time=' + incident_end_time
    + '&incident_region=' + incident_region
    + '&incident_source_confidence=' + incident_source_confidence
    + '&incident_description=' + incident_description
    + '&polygon_date=' + polygon_date
    + '&polygon_name=' + polygon_name
    + '&polygon_radius=' + polygon_radius
    + '&polygon_risk_rating=' + polygon_risk_rating
    + '&region_min_risk_rating=' + region_min_risk_rating
    + '&region_max_risk_rating=' + region_max_risk_rating
    ajax_request.open('POST', '' + app_root + '/polygons/polygon_create_details.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

            var polygon_number = this.responseText;

            polygon_edit_update_coordinates(polygon_number, polygon_coordinates); // deletes existing coordinates (none) and inserts updated coordinates to database

            if (polygon_type == 'Incident' && document.getElementById("incident_silence_creation_email").checked == false) { // if incident is being created, send incident creation email
                send_incident_creation_email(polygon_number);
            }
            else {
                // dont send email if wrong polygon_type or if silenced
            }

        }
    }
    ajax_request.send(data_to_send);

}



function send_incident_creation_email(polygon_number) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/polygons/send_incident_creation_email.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

        }
    }
    ajax_request.send(data_to_send);

}



function polygon_manager_delete_clicked(passed_id) {

    var polygon_number = document.getElementById(passed_id).getAttribute("data-polygon_number");
    let text = "Do you really want to delete this DMZ?";

    // console.log(polygon_number);

    if (confirm(text) == true) {

        var ajax_request = new XMLHttpRequest();
        var data_to_send = ''
        + 'polygon_number=' + polygon_number
        ajax_request.open('POST', '' + app_root + '/polygons/polygon_manager_delete.php', true);
        ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

        ajax_request.onreadystatechange = function() {
            if(ajax_request.readyState == 4 && this.status == 200) {
                console.log(this.responseText);

                var delete_button_data = document.getElementById(passed_id).getAttribute("data-line_number"); // visually removes the line in polygon_manager that the user deleted 
                var line_to_delete = document.getElementById("polygon_line_" + delete_button_data);
                line_to_delete.remove();

            }
        }
        ajax_request.send(data_to_send);

    } 

    else {
        // do nothing else if cancelled
    }

}




all_incidents_shown = false
function toggle_incidents() {

    optionsClose();

    if (all_incidents_shown == false) {
        load_all_incidents();
        all_incidents_shown = true;
    }

    else if (all_incidents_shown == true) {
        remove_all_incidents();
        all_incidents_shown = false;
    }

}


function load_all_incidents() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/load_all_incident_numbers.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var incident_number_list = this.responseText.split(",;");

            for (var x = 0; x < incident_number_list.length; x++) {

                var polygon_number = incident_number_list[x];

                load_all_incident_details(polygon_number);

            }


        }
    }
    ajax_request.send(data_to_send);

}


function remove_all_incidents() {

    var many_incident_markers_class = document.getElementsByClassName('many_incident_markers');

    while(many_incident_markers_class[0]) {
        many_incident_markers_class[0].parentNode.removeChild(many_incident_markers_class[0]);
        global_incident_multiple_markers = null;
    }


    for (let x = 1; x <= global_incidents_loaded; x++) {

        map.removeLayer("incident_loaded_middle_" + x);
        map.removeLayer("incident_loaded_outline_" + x);
        map.removeSource("incident_loaded_" + x);

    }

    global_incidents_loaded = 0;

}


var global_incident_multiple_markers = null;
function load_all_incident_details(polygon_number) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/load_data/load_all_incident_details.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var polygon_info_data = this.responseText.split(",;");
            var polygon_colour = polygon_info_data[0];
            var incident_longitude = polygon_info_data[1];
            var incident_latitude = polygon_info_data[2];

            load_all_incident_zones(polygon_number, polygon_colour);
            
            const incident_marker = document.createElement('div');
            incident_marker.style.backgroundImage = 'url(' + document_root + '/assets/incident_marker.png)';
            incident_marker.style.backgroundSize = 'cover';
            incident_marker.style.backgroundPosition = 'center';
            incident_marker.setAttribute('class','many_incident_markers');
            incident_marker.style.width = '25px';
            incident_marker.style.height = '25px';

            global_incident_multiple_markers = new mapboxgl.Marker({
                anchor: 'bottom',
                element: incident_marker,
                rotation: 0
              })
            .setLngLat([incident_longitude, incident_latitude])
            .addTo(map);

        }
    }
    ajax_request.send(data_to_send);

}


var global_incidents_loaded = 0;
function load_all_incident_zones(polygon_number, polygon_colour) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'polygon_number=' + polygon_number
    ajax_request.open('POST', '' + app_root + '/load_data/load_all_incident_zones.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText)

            var incident_coords_data = this.responseText.split(",;")
            var incident_coords_amount = incident_coords_data.length / 2;

            var incident_coordinates = [];
            for (var x = 0; x < incident_coords_amount; x++) {

                var longitude = incident_coords_data[2*x + 1];
                var latitude = incident_coords_data[2*x + 0];

                incident_coordinates[x] = [longitude, latitude];

            }

            global_incidents_loaded++ 


            map.addSource('incident_loaded_' + global_incidents_loaded, {
                'type': 'geojson',
                'data': {
                    'type': 'Feature',
                    'geometry': {
                        'type': 'Polygon',
                        'coordinates': [incident_coordinates]
                    }
                }
            });
             
            // Add a new layer to visualize the incident.
            map.addLayer({
                'id': 'incident_loaded_middle_' + global_incidents_loaded,
                'type': 'fill',
                'source': 'incident_loaded_' + global_incidents_loaded, // reference the data source
                'layout': {},
                'paint': {
                    'fill-color': polygon_colour, // colour fill
                    'fill-opacity': 0.5
                }
            });

            // Add a black outline around the incident.
            map.addLayer({
                'id': 'incident_loaded_outline_' + global_incidents_loaded,
                'type': 'line',
                'source': 'incident_loaded_' + global_incidents_loaded,
                'layout': {},
                'paint': {
                    'line-color': '#000',
                    'line-width': 1
                }
            });
            
        }
    }
    ajax_request.send(data_to_send);

}







const base64_img_handler = (blobInfo) => new Promise((resolve) => {
    resolve("data:image/png;base64," + blobInfo.base64());
});


var tinymce_first_load_pdf = true;
function tinymce_open_pdf() {

    if (tinymce_first_load_pdf == true) { // on first load, initialise "tinymce_editor_instance"

        tinymce_first_load_pdf = false;

        tinymce.init({
            selector: 'tinymce_editor_pdf',
            plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
            toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | addcomment showcomments | spellcheckdialog a11ycheck typography | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat',
            tinycomments_mode: 'embedded',
            tinycomments_author: 'Author name',
            mergetags_list: [
              { value: 'First.Name', title: 'First Name' },
              { value: 'Email', title: 'Email' },
            ],
            ai_request: (request, respondWith) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")),
            height: "85vh",
            resize: false,
            elementpath: false,
            editable_root: false,
            editable_class: 'editable',
            images_upload_handler: base64_img_handler,
        });

    }

    else {
        // do nothing if editor is already loaded
    }

    document.getElementById("tinymce_background_close_pdf").style.top = "0px";
    document.getElementById("tinymce_container_pdf").style.top = "0px";

}


function tinymce_close_pdf() {

    document.getElementById("tinymce_background_close_pdf").style.top = "-300vh";
    document.getElementById("tinymce_container_pdf").style.top = "-300vh";

    document.getElementById("tinymce_save_button_pdf").removeAttribute("onclick");
    tinymce.get("tinymce_editor_instance_pdf").setContent("");


}


async function tinymce_setContent_pdf(content) { // call this function instead of the .setContent() method

    if (tinymce.get('tinymce_editor_instance_pdf') && tinymce.get('tinymce_editor_instance_pdf').initialized == true) {

        tinymce.get('tinymce_editor_instance_pdf').setContent(content);

        loading_bar_pdf_finished()

    }

    else {

        await new Promise(r => setTimeout(r, 100)); // wait 100ms

        tinymce_setContent_pdf(content); // try setting content again

    }

}



function generate_vra() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'route_number=' + global_route_number_clicked // set when route edit was opened
    ajax_request.open('POST', '' + app_root + '/pdf/pdf_check_route_valid.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            if (this.responseText == 'incorrect_route_coordinates') { // if error message, give error alert instead of loading bar / vra generation

                alert("Invalid route coordinates, please check");

            }

            else {
                pdf_load_route_data() // continue generating VRA if no error message
            }

        }
    }
    ajax_request.send(data_to_send);

}


function pdf_load_route_data() {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'route_number=' + global_route_number_clicked
    ajax_request.open('POST', '' + app_root + '/pdf/pdf_load_route_data.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            loading_bar_pdf_running()

            var route_data = this.responseText.split(',;');

            var vessel_name = route_data[0];
            var vessel_imo = route_data[1];
            var route_name = route_data[2];
            
            var date_day = new Date(route_data[3]).toLocaleString('default', { day: 'numeric' });
            var date_month = new Date(route_data[3]).toLocaleString('default', { month: 'long' });
            var date_year = new Date(route_data[3]).toLocaleString('default', { year: 'numeric' });
            var route_start_datetime = date_day + " " + date_month + " " + date_year; // date_received

            pdf_get_image_data(vessel_name, vessel_imo, route_name, route_start_datetime)

        }
    }
    ajax_request.send(data_to_send);

}



function pdf_get_image_data(vessel_name, vessel_imo, route_name, route_start_datetime) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'route_number=' + global_route_number_clicked // set when route edit was opened
    ajax_request.open('POST', '' + app_root + '/pdf/pdf_get_image_data.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var image_base64_data = this.responseText;

            pdf_get_analysis_data(image_base64_data, vessel_name, vessel_imo, route_name, route_start_datetime);

        }
    }
    ajax_request.send(data_to_send);

}


function pdf_get_analysis_data(image_base64_data, vessel_name, vessel_imo, route_name, route_start_datetime) {

    var page_1_content = "";
    var page_2_content = "";


    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'route_number=' + global_route_number_clicked
    ajax_request.open('POST', '' + app_root + '/pdf/pdf_get_analysis_data.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            page_1_content = this.responseText


            pdf_load_landscape_data(image_base64_data, vessel_name, vessel_imo, route_name, route_start_datetime, page_1_content, page_2_content);

        }
    }
    ajax_request.send(data_to_send);


}


function pdf_load_landscape_data(image_base64_data, vessel_name, vessel_imo, route_name, route_start_datetime, page_1_content, page_2_content) {

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_imo=' + vessel_imo
    ajax_request.open('POST', '' + app_root + '/pdf/pdf_load_landscape_data.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var landscape_data_list = this.responseText.split(",;");

            var vessel_flag = landscape_data_list[0];
            var freeboard = landscape_data_list[1];
            var speed_over_ground = landscape_data_list[2] + "Kts";
            var armed_security_team = "";
            var eos_assure_coverage = "YES";


            load_pdf_template(image_base64_data, vessel_name, vessel_imo, route_name, route_start_datetime, page_1_content, page_2_content, vessel_flag, freeboard, speed_over_ground, armed_security_team, eos_assure_coverage);

        }
    }
    ajax_request.send(data_to_send);


}


function load_pdf_template(image_base64_data, vessel_name, vessel_imo, route_name, route_start_datetime, page_1_content, page_2_content, vessel_flag, freeboard, speed_over_ground, armed_security_team, eos_assure_coverage) {

    if (!page_1_content) {
        var page_1_content = "";
    }
    if (!page_2_content) {
        var page_2_content = "";
    }

    tinymce_open_pdf();

    var content = 
    `


    <div style="aspect-ratio: 210 / 297; height: 1122.89px; margin-left: 50%; transform: translate(-50%, 0); margin-top: 20px; margin-bottom: 40px; box-shadow: 0px 3px 12px 3px rgba(0,0,0,0.24);">
        
        <div style="height: 240px; width: 100%; background-color: #303c44; position: absolute; top: 0px;">
            <img style="position: absolute;top: 100px;right: 30px;" height="60px" width="368px" src="`+document_root+`/assets/eosrisk_logo.jpg">
        </div>

        <div style="height: 5px; width: 100%; background-color: #303c44; position: absolute; top: 305px;">
        </div>


        <div style="position: absolute; top: 338px; left: 10%;">
            <span style="font-weight: bold; font-size: 33px; color: #303c44; font-family: arial, sans-serif;">VOYAGE RISK ASSESSMENT</span>
        </div>

        <div style="position: absolute; top: 395px; left: 10%;">
            <span style="font-size: 14px; color: #303c44; font-family: arial, sans-serif;">Vessel name:</span>
            <span style="font-size: 14px; font-weight: bold; color: #303c44; font-family: arial, sans-serif;">`+vessel_name+`</span>
        </div>

        <div style="position: absolute; top: 425px; left: 10%;">
            <span style="font-size: 14px; color: #303c44; font-family: arial, sans-serif;">IMO:</span>
            <span style="font-size: 14px; font-weight: bold; color: #303c44; font-family: arial, sans-serif;">`+vessel_imo+`</span>
        </div>

        <div style="position: absolute; top: 455px; left: 10%;">
            <span style="font-size: 14px; color: #303c44; font-family: arial, sans-serif;">Route:</span>
            <span style="font-size: 14px; font-weight: bold; color: #303c44; font-family: arial, sans-serif;">`+route_name+`</span>
        </div>

        <div style="position: absolute; top: 485px; left: 10%;">
            <span style="font-size: 14px; color: #303c44; font-family: arial, sans-serif;">Date:</span>
            <span style="font-size: 14px; font-weight: bold; color: #303c44; font-family: arial, sans-serif;">`+route_start_datetime+`</span>
        </div>


        <div style="height: 5px; width: 100%; background-color: #303c44; position: absolute; bottom: 585px;">
        </div>

        <div style="height: 395px; width: 100%; position: absolute; bottom: 190px;">
            <img style="position: absolute; top: 0px; left: 0px;" height="100%" width="100%" src="`+document_root+`/assets/world_map.png">
        </div>

        <div style="height: 190px; width: 100%; background-color: #303c44; position: absolute; bottom: 0px;">
            <span style="position: absolute;bottom: 80px;left: calc(50% - 120px);font-weight: bold;font-size: 20px;color:white;font-family: arial,sans-serif;">STRICTLY CONFIDENTIAL</span>
        </div>

    </div>


    <div style="aspect-ratio: 297 / 210; width: 1122.89px; margin-left: 50%; transform: translate(-50%, 0); margin-top: 10px; margin-bottom: 40px; box-shadow: 0px 3px 12px 3px rgba(0,0,0,0.24);">
        
        <div style="height: 80px; width: 100%; background-color: #303c44; position: absolute; top: 0px;">
            <span style="position: absolute; width: 700px; height: 60px; top: 12px; left: 12px; color: white; font-size: 36px; font-weight: bold; font-family: arial, sans-serif;">Vessel Vulnerability Assessment</span>
            <img style="position: absolute; top: 15px; right: 20px;" height="60px" width="368px" src="`+document_root+`/assets/eosrisk_logo.jpg">
        </div>

        <div id="landscape_content" style="height: calc(100% - 120px); width: 100%; position: absolute; top: 80px; outline: none; overflow: hidden;">
            <div style="position: absolute; height: 100%; width: 100%; margin: 0px; padding: 0px; background-color: white;">


                <div style="position: absolute; height: 99%; top: 1%; width: 52%; left: 0px; background-color: white; border: solid; border-color: black; border-width: 1px; box-sizing: border-box;">
                    

                    <div style="position: absolute; width: 100%; height: 25px; line-height: 25px; top: 0px; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">VESSEL DETAILS</span>
                    </div>


                    <div style="position: absolute; width: calc(100% / 3); left: 0px; border-top: solid; border-bottom: solid; border-color: white; border-width: 1px; box-sizing: border-box; height: 25px; line-height: 25px; top: 25px; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">NAME</span>
                    </div>
                    <div style="position: absolute; width: calc(100% / 3); left: calc(100% / 3); border: solid; border-color: white; border-width: 1px; box-sizing: border-box; height: 25px; line-height: 25px; top: 25px; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">IMO</span>
                    </div>
                    <div style="position: absolute; width: calc(100% / 3); left: calc(200% / 3); border-top: solid; border-bottom: solid; border-color: white; border-width: 1px; box-sizing: border-box; height: 25px; line-height: 25px; top: 25px; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">FLAG</span>
                    </div>


                    <div style="position: absolute; width: calc(100% / 3); left: 0px; line-height: 25px; border-bottom: solid; border-color: black; border-width: 1px; box-sizing: border-box; height: 25px; top: 50px; outline: none; background-color: #e0dcdc;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">`+vessel_name+`</span>
                    </div>
                    <div style="position: absolute; width: calc(100% / 3); left: calc(100% / 3); line-height: 25px; border-bottom: solid; border-left: solid; border-right: solid; border-color: black; border-width: 1px; box-sizing: border-box; height: 25px; top: 50px; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">`+vessel_imo+`</span>
                    </div>
                    <div style="position: absolute; width: calc(100% / 3); left: calc(200% / 3); line-height: 25px; border-bottom: solid; border-color: black; border-width: 1px; box-sizing: border-box; height: 25px; top: 50px; outline: none; background-color: #e0dcdc;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">`+vessel_flag+`</span>
                    </div>


                    <div style="position: absolute; width: 100%; height: 25px; top: 75px; background-color: white;"></div>


                    <div style="position: absolute; width: 100%; left: 0px; height: 25px; line-height: 25px; top: 100px; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">VESSEL VULNERABILITY</span>
                    </div>


                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: 0px; height: 25px; line-height: 25px; top: 125px; border-top: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">SPEED</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.4); left: calc((100% / 3) * 0.6); height: 25px; line-height: 25px; top: 125px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">FREEBOARD</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 1.4); left: calc((100% / 3) * 1); height: 25px; line-height: 25px; top: 125px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">ARMED SECURITY TEAM</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: calc((100% / 3) * 2.4); height: 25px; line-height: 25px; top: 125px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">EOS ASSURE</span>
                    </div>


                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: 0px; height: 25px; line-height: 25px; top: 150px; border-top: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">`+speed_over_ground+`</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.4); left: calc((100% / 3) * 0.6); height: 25px; line-height: 25px; top: 150px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">`+freeboard+`</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 1.4); left: calc((100% / 3) * 1); height: 25px; line-height: 25px; top: 150px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">`+armed_security_team+`</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: calc((100% / 3) * 2.4); height: 25px; line-height: 25px; top: 150px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">`+eos_assure_coverage+`</span>
                    </div>


                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: 0px; height: 45px; line-height: 45px; top: 175px; border-top: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">IDENTIFIER</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.4); left: calc((100% / 3) * 0.6); height: 45px; line-height: 45px; top: 175px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">RISK LEVEL</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 2); left: calc((100% / 3) * 1); height: 45px; line-height: 45px; top: 175px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">COMMENT</span>
                    </div>


                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: 0px; height: 55px; line-height: 55px; top: 220px; border-top: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">FLAG</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.4); left: calc((100% / 3) * 0.6); height: 55px; line-height: 55px; top: 220px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #10b4ec; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">LOW</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 2); left: calc((100% / 3) * 1); height: 55px; line-height: 55px; top: 220px; border-top: solid; border-left: solid; border-color: white; border-left-color: black; border-width: 1px; box-sizing: border-box; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;"></span>
                    </div>


                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: 0px; height: 55px; line-height: 55px; top: 275px; border-top: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">MANAGEMENT</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.4); left: calc((100% / 3) * 0.6); height: 55px; line-height: 55px; top: 275px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #10b4ec; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">LOW</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 2); left: calc((100% / 3) * 1); height: 55px; line-height: 55px; top: 275px; border-top: solid; border-left: solid; border-color: white; border-left-color: black; border-width: 1px; box-sizing: border-box; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;"></span>
                    </div>


                    <div style="position: absolute; width: calc((100% / 3) * 0.6); left: 0px; height: 55px; line-height: 55px; top: 330px; border-top: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">PTRA SCORE</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 0.4); left: calc((100% / 3) * 0.6); height: 55px; line-height: 55px; top: 330px; border-top: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #10b4ec; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">LOW</span>
                    </div>

                    <div style="position: absolute; width: calc((100% / 3) * 2); left: calc((100% / 3) * 1); height: 55px; line-height: 55px; top: 330px; border-top: solid; border-left: solid; border-color: white; border-left-color: black; border-width: 1px; box-sizing: border-box; background-color: #e0dcdc; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: black; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;"></span>
                    </div>


                    <div style="position: absolute; width: 100%; height: 30px; line-height: 30px; top: 385px; border-top: solid; border-color: grey; border-width: 0.5px; box-sizing: border-box; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: left; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">BESPOKE THREAT SUMMARY</span>
                    </div>

                    <div style="position: absolute; width: calc(100% - 12px); left: 12px; height: calc(100% - 415px); top: 415px; overflow: hidden; font-size: 11px; outline: none; font-family: arial, sans-serif;" class="editable"></div>

                </div>


                <div style="position: absolute; height: 125px; top: 1%; width: 46.8%; right: 0.5%; background-color: white; border: solid; border-color: black; border-width: 1px;">


                    <div style="position: absolute; width: 100%; height: 30px; line-height: 30px; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">SUMMARY</span>
                    </div>


                    <div style="position: absolute; width: 100%; top: 30px; height: 5px; background-color: white;"></div>


                    <div style="position: absolute; width: 40%; top: 35px; height: 30px; line-height: 30px; background-color: #303c44; border-bottom: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <span style="position: absolute; width: calc(100% - 8px); padding-left: 8px; height: 100%; text-align: left; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">ROUTING</span>
                    </div>

                    <div style="position: absolute; width: 60%; left: 40%; top: 35px; height: 30px; line-height: 30px; background-color: white; border-left: solid; border-bottom: solid; border-color: white; border-width: 1px; box-sizing: border-box; outline: none;" class="editable">
                        <span style="position: absolute; width: calc(100% - 8px); padding-left: 8px; height: 100%; text-align: left; color: black; font-size: 13px; font-family: arial, sans-serif;"></span>
                    </div>

                    <div style="position: absolute; width: 40%; top: 65px; height: 30px; line-height: 30px; background-color: #303c44; border-bottom: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <span style="position: absolute; width: calc(100% - 8px); padding-left: 8px; height: 100%; text-align: left; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">INTERMEDIARY PORT CALLS</span>
                    </div>

                    <div style="position: absolute; width: 60%; left: 40%; top: 65px; height: 30px; line-height: 30px; background-color: white; border-left: solid; border-bottom: solid; border-color: white; border-width: 1px; box-sizing: border-box; outline: none;" class="editable">
                        <span style="position: absolute; width: calc(100% - 8px); padding-left: 8px; height: 100%; text-align: left; color: black; font-size: 13px; font-family: arial, sans-serif;"></span>
                    </div>

                    <div style="position: absolute; width: 40%; top: 95px; height: 30px; line-height: 30px; background-color: #303c44; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <span style="position: absolute; width: calc(100% - 8px); padding-left: 8px; height: 100%; text-align: left; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">OVERALL RISK RATING</span>
                    </div>

                    <div style="position: absolute; width: 60%; left: 40%; top: 95px; height: 30px; line-height: 30px; background-color: white; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box; outline: none;" class="editable">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; background-color: #609cd4; font-family: arial, sans-serif;">LOW</span>
                    </div>

                </div>


                <div style="position: absolute; height: 115px; top: calc(125px + 2%); width: 46.8%; right: 0.5%; background-color: white; border: solid; border-color: black; border-width: 1px;">

                    <div style="position: absolute; width: 100%; height: 30px; line-height: 30px; background-color: #303c44;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-weight: bold; font-family: arial, sans-serif;">EOS RISK RATING INDEX</span>
                    </div>

                    <div style="position: absolute; width: 100%; top: 30px; height: 5px; background-color: white;"></div>


                    <div style="position: absolute; width: 20%; left: 0%; top: 35px; height: 35px; line-height: 35px; border-bottom: solid; border-color: white; border-width: 1px; box-sizing: border-box; background-color: #609cd4;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-family: arial, sans-serif;">LOW</span>
                    </div>

                    <div style="position: absolute; width: 20%; left: 20%; top: 35px; height: 35px; line-height: 35px; background-color: #70ac4c; border-bottom: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-family: arial, sans-serif;">MODERATE</span>
                    </div>

                    <div style="position: absolute; width: 20%; left: 40%; top: 35px; height: 35px; line-height: 35px; background-color: #ffbc14; border-bottom: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-family: arial, sans-serif;">SUBSTANTIAL</span>
                    </div>

                    <div style="position: absolute; width: 20%; left: 60%; top: 35px; height: 35px; line-height: 35px; background-color: #c00404; border-bottom: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-family: arial, sans-serif;">HIGH</span>
                    </div>

                    <div style="position: absolute; width: 20%; left: 80%; top: 35px; height: 35px; line-height: 35px; background-color: #ff0404; border-bottom: solid; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <span style="position: absolute; width: 100%; height: 100%; text-align: center; color: white; font-size: 11px; font-family: arial, sans-serif;">EXTREME</span>
                    </div>


                    <div style="position: absolute; width: 20%; left: 0%; top: 70px; height: 45px; background-color: #f8f4f4;">
                        <p style="position: absolute; width: 90%; padding-left: 5px; padding-right: 5px; height: 100%; top: 10px; margin: 0; text-align: center; color: black; font-size: 9px; font-family: arial, sans-serif;">An incident is highly unlikely</p>
                    </div>

                    <div style="position: absolute; width: 20%; left: 20%; top: 70px; height: 45px; background-color: #f8f4f4; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <p style="position: absolute; width: 90%; padding-left: 5px; padding-right: 5px; height: 100%; top: 10px; margin: 0; text-align: center; color: black; font-size: 9px; font-family: arial, sans-serif;">An incident is possible but not likely</p>
                    </div>

                    <div style="position: absolute; width: 20%; left: 40%; top: 70px; height: 45px; background-color: #f8f4f4; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <p style="position: absolute; width: 90%; padding-left: 5px; padding-right: 5px; height: 100%; top: 10px; margin: 0; text-align: center; color: black; font-size: 9px; font-family: arial, sans-serif;">An incident is a credible possibility</p>
                    </div>

                    <div style="position: absolute; width: 20%; left: 60%; top: 70px; height: 45px; background-color: #f8f4f4; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <p style="position: absolute; width: 90%; padding-left: 5px; padding-right: 5px; height: 100%; top: 10px; margin: 0; text-align: center; color: black; font-size: 9px; font-family: arial, sans-serif;">An incident is likely</p>
                    </div>

                    <div style="position: absolute; width: 20%; left: 80%; top: 70px; height: 45px; background-color: #f8f4f4; border-left: solid; border-color: white; border-width: 1px; box-sizing: border-box;">
                        <p style="position: absolute; width: 90%; padding-left: 5px; padding-right: 5px; height: 100%; top: 10px; margin: 0; text-align: center; color: black; font-size: 9px; font-family: arial, sans-serif;">An incident is extremely likely</p>
                    </div>


                </div>


                <div style="position: absolute; height: calc(100% - 240px - 4% - 2px); bottom: 1%; width: 46.8%; right: 0.5%; background-color: white; border: solid; border-color: black; border-width: 1px; overflow: hidden;">
                    <img style="position: absolute; top: 50%; transform: translateY(-50%);" width="100%" height="auto" src="`+image_base64_data+`">
                </div>


            </div>
        </div>

        <div style="height: 40px; width: 100%; background-color: #303c44; position: absolute; bottom: 0px;">
        </div>

    </div>
    

    <div style="min-height: 1122.89px; width: 794px; height: auto; margin-left: 50%; transform: translate(-50%, 0); margin-top: 10px; margin-bottom: 40px; box-shadow: 0px 3px 12px 3px rgba(0,0,0,0.24);">
                    
        <div style="height: 130px; width: 100%; background-color: #303c44; position: relative; top: 0px;">
            
            <div style="position: absolute; top: 40px; left: 10%;">
                <span style="font-size: 13px; font-weight: bold; color: white; font-family: arial, sans-serif;">`+vessel_name+` | </span>
                <span style="font-size: 13px; font-weight: bold; color: red; font-family: arial, sans-serif;">CONFIDENTIAL</span>
            </div>

            <div style="position: absolute; top: 60px; left: 10%;">
                <span style="font-size: 13px; font-weight: bold; color: white; font-family: arial, sans-serif;">Voyage Risk Assessment</span>
            </div>
            
            <img style="position: absolute; top: 40px; right: 20px;" height="50px" width="306.5px" src="`+document_root+`/assets/eosrisk_logo.jpg">

        </div>
        
        <div id="main_content" style="min-height: 1040px; height: auto; width: 80%; max-width: 80%; background-color: white; position: relative; margin-top: 0px; left: 10%; outline: none; overflow-x: hidden;" class="editable">
        `+page_1_content+`
        </div>

        <div style="height: 130px; width: 100%; background-color: #303c44; position: relative; top: calc(100%); transform: translateY(calc(-100% + 130px));">
        </div>

    </div>


    <div style="min-height: 1122.89px; width: 794px; height: auto; margin-left: 50%; transform: translate(-50%, 0); margin-top: 10px; margin-bottom: 40px; box-shadow: 0px 3px 12px 3px rgba(0,0,0,0.24);">
            
        <div style="height: 130px; width: 100%; background-color: #303c44; position: relative; top: 0px;">
            
            <div style="position: absolute; top: 40px; left: 10%;">
                <span style="font-size: 13px; font-weight: bold; color: white; font-family: arial, sans-serif;">`+vessel_name+` | </span>
                <span style="font-size: 13px; font-weight: bold; color: red; font-family: arial, sans-serif;">CONFIDENTIAL</span>
            </div>

            <div style="position: absolute; top: 60px; left: 10%;">
                <span style="font-size: 13px; font-weight: bold; color: white; font-family: arial, sans-serif;">Voyage Risk Assessment</span>
            </div>
            
            <img style="position: absolute; top: 40px; right: 20px;" height="50px" width="306.5px" src="`+document_root+`/assets/eosrisk_logo.jpg">

        </div>
        
        <div id="conclusion_content" style="min-height: 1040px; height: auto; width: 80%; max-width: 80%; background-color: white; position: relative; margin-top: 0px; left: 10%; outline: none; overflow-x: hidden;" class="editable">
        `+page_2_content+`
        </div>

        <div style="height: 130px; width: 100%; background-color: #303c44; position: relative; top: calc(100%); transform: translateY(calc(-100% + 130px));">
        </div>

    </div>


    `

    tinymce_setContent_pdf(content)
}


function save_pdf() {

    alert("Emailing VRA, should arrive after 1 minute");

    var route_number = global_route_number_clicked;

    var main_content = document.getElementById('tinymce_editor_instance_pdf_ifr').contentWindow.document.getElementById("main_content").innerHTML;
    var landscape_content = document.getElementById('tinymce_editor_instance_pdf_ifr').contentWindow.document.getElementById("landscape_content").innerHTML;
    var conclusion_content = document.getElementById('tinymce_editor_instance_pdf_ifr').contentWindow.document.getElementById("conclusion_content").innerHTML;

    tinymce_close_pdf()

    var ajax_request = new XMLHttpRequest();
    var data_to_send = '' 
    + 'route_number=' + route_number
    + '&main_content=' + encodeURIComponent(main_content)
    + '&landscape_content=' + encodeURIComponent(landscape_content)
    + '&conclusion_content=' + encodeURIComponent(conclusion_content)
    ajax_request.open('POST', '' + app_root + '/pdf/pdf_email_vra.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            console.log(this.responseText);

        }
        
    }
    ajax_request.send(data_to_send);

}


all_polygons_shown = false
function toggle_dmz_areas() {

    optionsClose();

    if (all_polygons_shown == false) {
        load_all_polygons();
        all_polygons_shown = true;
    }

    else if (all_polygons_shown == true) {
        remove_all_polygons();
        all_polygons_shown = false;
    }

}

// Function the fetch all polygons' details from the database
let global_polygons_loaded = 0;
function load_all_polygons_numbers_and_colors() {
    fetch(app_root + '/load_data/load_all_polygon_numbers_and_colors.php', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        // Ensure data is an array before processing
        if (Array.isArray(data)) {
            data.forEach(polygon => {
                // Pass the full set of coordinates along with polygon colour
                load_all_polygon_zones_once(polygon.polygon_type, polygon.polygon_colour, polygon.latitude, polygon.longitude, polygon.incident_longitude, polygon.incident_latitude);  
            });
        } else {
            console.error("Invalid data format received:", data);
        }
    })
    .catch(error => {
        console.error("Error fetching polygons:", error);
    });
}

// Cache to store loaded polygons
let cachedPolygons = {};
let activeRequests = [];

function load_all_polygon_zones(polygon_number, polygon_colour, polygon_type, incident_longitude, incident_latitude) {
    // Check if the polygon data is already loaded
    if (cachedPolygons[polygon_number] && cachedPolygons[polygon_number].coordinates) {
        // Reuse cached data
        addPolygonToMap(polygon_number, cachedPolygons[polygon_number].coordinates, polygon_colour, polygon_type, incident_longitude, incident_latitude);
    } else {
        var ajax_request = new XMLHttpRequest();
        var data_to_send = 'polygon_number=' + polygon_number + '&polygon_type=' + polygon_type;  // Include polygon_type in the request
        var endpoint = app_root + '/load_data/load_all_polygon_zones.php'; // Only one endpoint

        ajax_request.open('POST', endpoint, true);  // Use the single endpoint
        ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        
        // Show spinner before sending request
        document.getElementById('overlay').style.display = 'flex';

        // Add the request to activeRequests array
        activeRequests.push(ajax_request);

        ajax_request.onreadystatechange = function() {
            if (ajax_request.readyState === 4 && ajax_request.status === 200) {
                if (ajax_request.responseText.trim()) {
                    var polygon_coords_data = ajax_request.responseText.trim().split(",;");
                    var polygon_coords_amount = polygon_coords_data.length / 2;
                    var polygon_coordinates = [];

                    for (var x = 0; x < polygon_coords_amount; x++) {
                        var longitude = parseFloat(polygon_coords_data[2 * x + 1]);
                        var latitude = parseFloat(polygon_coords_data[2 * x]);
                        if (!isNaN(longitude) && !isNaN(latitude)) {
                            polygon_coordinates[x] = [longitude, latitude];
                        }
                    }

                    // Cache the polygon data with both color and coordinates
                    cachedPolygons[polygon_number] = {
                        colour: polygon_colour,
                        coordinates: polygon_coordinates
                    };

                    addPolygonToMap(polygon_number, polygon_coordinates, polygon_colour, polygon_type, incident_longitude, incident_latitude);
                }
            }

            // Remove the request from activeRequests
            removeRequest(ajax_request);
        };

        ajax_request.send(data_to_send);
    }
}


function removeRequest(xhr) {
    activeRequests = activeRequests.filter(request => request !== xhr);

    // If no active requests remain, hide the overlay
    if (activeRequests.length === 0) {
        document.getElementById('overlay').style.display = 'none';
    }
}


function load_all_polygons(polygon_type) {
    var ajax_request = new XMLHttpRequest();
    var data_to_send = 'polygon_type=' + polygon_type;
    ajax_request.open('POST', app_root + '/load_data/load_all_polygon_numbers.php', true);    
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax_request.onreadystatechange = function() {
        if (ajax_request.readyState === 4 && ajax_request.status === 200) {
            if (ajax_request.responseText.trim()) {
                var polygon_number_list = ajax_request.responseText.trim().split(",;");
                polygon_number_list.forEach(function(polygon_number) {
                    if (cachedPolygons[polygon_number]) {
                        // Load from cache
                        load_all_polygon_zones(polygon_number, cachedPolygons[polygon_number].colour, polygon_type, cachedPolygons[polygon_number].incident_longitude, cachedPolygons[polygon_number].incident_latitude);
                    } else {
                        // Fetch polygon details
                        load_all_polygon_details(polygon_number, polygon_type);
                    }
                });
            }
        }
    };
    ajax_request.send(data_to_send);
}

function load_all_polygon_details(polygon_number, polygon_type) {

    // today237
    console.log("running load_all_polygon_details")
    console.log(polygon_number)
    console.log(polygon_type)
    
    var ajax_request = new XMLHttpRequest();
    var data_to_send = 'polygon_number=' + polygon_number;
    ajax_request.open('POST', app_root + '/load_data/load_all_polygon_details.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax_request.onreadystatechange = function() {
        if (ajax_request.readyState === 4 && ajax_request.status === 200) {
            if (this.responseText) {

                console.log(this.responseText)
                var response = JSON.parse(this.responseText);
                var polygon_colour = response["polygon_colour"];
                var incident_longitude = Number(response["incident_longitude"]);
                var incident_latitude = Number(response["incident_latitude"]);


                if (polygon_colour) {

                    // Properly cache the polygon colour
                    if (!cachedPolygons[polygon_number]) {
                        cachedPolygons[polygon_number] = {};
                    }
                    cachedPolygons[polygon_number].colour = polygon_colour;
                    cachedPolygons[polygon_number].incident_longitude = incident_longitude;
                    cachedPolygons[polygon_number].incident_latitude = incident_latitude;

                    // Now safely load polygon zones
                    load_all_polygon_zones(polygon_number, polygon_colour, polygon_type, incident_longitude, incident_latitude);
                }
            }
        }
    };
    ajax_request.send(data_to_send);
}

// Cache for incident markers
let incidentMarkers = {};

function addPolygonToMap(polygon_number, polygon_coordinates, polygon_colour, polygon_type, incident_longitude, incident_latitude) {
    // Generate unique IDs based on polygon number
    const sourceId = 'polygon_source_' + polygon_number;
    const middleLayerId = 'polygon_middle_' + polygon_number;
    const outlineLayerId = 'polygon_outline_' + polygon_number;

    remove_polygon_zones(polygon_number);

    // Create and add source to the map
    map.addSource(sourceId, {
        'type': 'geojson',
        'data': {
            'type': 'Feature',
            'geometry': {
                'type': 'Polygon',
                'coordinates': [polygon_coordinates]
            }
        }
    });

    // Add fill layer
    if (!map.getLayer(middleLayerId)) {
        map.addLayer({
            'id': middleLayerId,
            'type': 'fill',
            'source': sourceId,
            'layout': {},
            'paint': {
                'fill-color': polygon_colour,
                'fill-opacity': 0.5
            }
        });
    }

    // Add outline layer
    if (!map.getLayer(outlineLayerId)) {
        map.addLayer({
            'id': outlineLayerId,
            'type': 'line',
            'source': sourceId,
            'layout': {},
            'paint': {
                'line-color': '#000',
                'line-width': 1
            }
        });
    }

    // Create and add incident marker if polygon_type is "Incident"
    if (polygon_type === "Incident") {
            // Create the marker element
            const incident_marker = document.createElement('div');
            incident_marker.style.backgroundImage = `url(${document_root}/assets/incident_marker.png)`;
            incident_marker.style.backgroundSize = 'cover';
            incident_marker.style.backgroundPosition = 'center';
            incident_marker.style.width = '25px';
            incident_marker.style.height = '25px';

            // Create and store marker in cache
            const marker = new mapboxgl.Marker({
                anchor: 'bottom',
                element: incident_marker,
                rotation: 0
            })
            .setLngLat([incident_longitude, incident_latitude])
            .addTo(map);

            incidentMarkers[polygon_number] = marker;
        
    }
}

function remove_polygon_zones(polygon_number) {
    // Generate unique IDs based on polygon number
    const sourceId = 'polygon_source_' + polygon_number;
    const middleLayerId = 'polygon_middle_' + polygon_number;
    const outlineLayerId = 'polygon_outline_' + polygon_number;

    // Check and remove fill layer if it exists
    if (map.getLayer(middleLayerId)) {
        map.removeLayer(middleLayerId);
    }

    // Check and remove outline layer if it exists
    if (map.getLayer(outlineLayerId)) {
        map.removeLayer(outlineLayerId);
    }

    // Check and remove source if it exists
    if (map.getSource(sourceId)) {
        map.removeSource(sourceId);
    }

    // Remove the incident marker from the map without deleting it
    if (incidentMarkers[polygon_number]) {
        incidentMarkers[polygon_number].remove();
    }
}


function remove_all_polygons() {

    for (let x = 1; x <= global_polygons_loaded; x++) {

        map.removeLayer("polygon_loaded_middle_" + x);
        map.removeLayer("polygon_loaded_outline_" + x);
        map.removeSource("polygon_loaded_" + x);

    }

    global_polygons_loaded = 0;

}

var tinymce_first_load = true;
function tinymce_open() {

    if (tinymce_first_load == true) { // on first load, initialise "tinymce_editor_instance"

        tinymce_first_load = false;

        tinymce.init({
            selector: 'tinymce_editor',
            plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
            toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | addcomment showcomments | spellcheckdialog a11ycheck typography | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat',
            tinycomments_mode: 'embedded',
            tinycomments_author: 'Author name',
            mergetags_list: [
              { value: 'First.Name', title: 'First Name' },
              { value: 'Email', title: 'Email' },
            ],
            ai_request: (request, respondWith) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")),
            height: "75vh",
            resize: false,
            elementpath: false,
        });

    }

    else {
        // do nothing if editor is already loaded
    }

    document.getElementById("tinymce_background_close").style.top = "0px";
    document.getElementById("tinymce_container").style.top = "0px";

}


function tinymce_close() {

    document.getElementById("tinymce_background_close").style.top = "-300vh";
    document.getElementById("tinymce_container").style.top = "-300vh";

    document.getElementById("tinymce_save_button").removeAttribute("onclick");
    document.getElementById("tinymce_save_button").removeAttribute("data-polygon_number");
    tinymce.get("tinymce_editor_instance").setContent("");


}


async function tinymce_setContent(content) { // call this function instead of the .setContent() method

    if (tinymce.get('tinymce_editor_instance') && tinymce.get('tinymce_editor_instance').initialized == true) {

        tinymce.get("tinymce_editor_instance").setContent(content);

    }

    else {

        await new Promise(r => setTimeout(r, 100)); // wait 100ms

        tinymce_setContent(content); // try setting content again

    }

}


var pdf_loading = true;
async function loading_bar_pdf_running() {

    pdf_loading = true;

    document.getElementById("loading_bar_page").style.top = "0px";

    var max_time_seconds = 20;
    var updates_per_second = 100;
    var total_loads = max_time_seconds * updates_per_second;

    for (var x = 0; x < total_loads; x++) {

        if (pdf_loading == true) {
            document.getElementById("loading_bar").style.width = "calc("+(x/total_loads)+" * 100%)"
            document.getElementById("loading_text").innerText = "Loading - " + Number(x/total_loads * 100).toFixed(1) + "%";
            await new Promise(r => setTimeout(r, (1000 / updates_per_second))); // wait 1000ms
        }
        else {
            break; // exit the loop if loading is completed
        }

    }
    document.getElementById("loading_text").innerText = "Loading - 99.9% - Finishing VRA Generation"
}

async function loading_bar_pdf_finished() {

    pdf_loading = false;

    document.getElementById("loading_bar_page").style.top = "-300vh";
    document.getElementById("loading_bar").style.width = "0%"
    document.getElementById("loading_text").innerText = "";

}


function incident_source_change_high() {
    incident_source_radio_1.checked = true;
    incident_source_input_box.style.backgroundColor = '#A0CC04';
    incident_source_text.innerText = "HIGH"
}

function incident_source_change_moderate() {
    incident_source_radio_2.checked = true;
    incident_source_input_box.style.backgroundColor = '#FFC404';
    incident_source_text.innerText = "MODERATE"
}

function incident_source_change_low() {
    incident_source_radio_3.checked = true;
    incident_source_input_box.style.backgroundColor = '#E81C24';
    incident_source_text.innerText = "LOW"
}
incident_source_change_high(); // default to Source Control: HIGH



function set_incident_source_confidence(incident_source_confidence) {

    if (incident_source_confidence == 1) {
        incident_source_change_high();
    }
    else if (incident_source_confidence == 2) {
        incident_source_change_moderate();
    }
    else if (incident_source_confidence == 3) {
        incident_source_change_low();
    }
    else {
        console.log("Incident Source Confidence Value Invalid");
    }

}



function incident_add_description() {

    tinymce_open()

    document.getElementById("tinymce_save_button").setAttribute("onclick", "incident_add_save(event)");

}


var global_incident_add_description_to_save = ""; // define on a global scope so the save function can access this
function incident_add_save() {
    event.stopPropagation(); // prevents parent div element "tinymce_background_close" onclick event from firing, include this with every function bound to "tinymce_save_button"
 

    // retrieve content in tinymce editor
    global_incident_add_description_to_save = tinymce.get("tinymce_editor_instance").getContent();

    console.log(global_incident_add_description_to_save)

    // format content using REGEX to display preview in simple text format
    var incident_description_preview_trimmed = "<span style='font-weight:bold;'>Incident: </span>" + global_incident_add_description_to_save.replace(/\s*<[^>]*>\s*/g, " ").replace(/\s*&nbsp;\s*/g, ' ').replace(/\s+/g, " ").replace(/^[\s]+/g, ""); // remove <> bracketed styles and whitespace
    
    // set content of preview box to trimmed content user just entered
    document.getElementById("incident_description_preview").innerHTML = incident_description_preview_trimmed;

    console.log(global_incident_add_description_to_save)

    // close tinymce editor
    tinymce_close()


    // REGEX EXPLANATION //

    // .replace(/<[^>]*>/g, " ")
    // <[^>]*> replaces everything from < until > which is not >

    // replace(/\s*&nbsp;\s*/g, ' ')
    // replaces all instances of "&nbsp;" (with optional \s whitespace either side) with " " whitespace

    // .replace(/\s+/g, " ")
    // replaces all \s whitespace (one or more) with a single " " whitespace

    // .replace(/^[\s]+/g, "")
    // replaces any \s whitespace at the beginning of the string with ""

    //

}

function polygon_hide_incident_elements() { // call this function to hide the extra elements on the "Incident" screen


    document.getElementById("polygon_incident_box").style.display = "none";
    document.getElementById("polygon_incident_para").style.display = "none";
    document.getElementById("polygon_incident_input").style.display = "none";
    document.getElementById("polygon_incident_add_type_btn").style.display = "none";

    document.getElementById("polygon_impact_radius_box").style.display = "none";
    document.getElementById("polygon_impact_radius_para").style.display = "none";
    document.getElementById("polygon_impact_radius_input").style.display = "none";

    document.getElementById("incident_start_date_box").style.display = "none";
    document.getElementById("incident_start_date_para").style.display = "none";
    document.getElementById("incident_start_date_input").style.display = "none";

    document.getElementById("incident_end_date_box").style.display = "none";
    document.getElementById("incident_end_date_para").style.display = "none";
    document.getElementById("incident_end_date_input").style.display = "none";

    document.getElementById("incident_start_time_box").style.display = "none";
    document.getElementById("incident_start_time_para").style.display = "none";
    document.getElementById("incident_start_time_input").style.display = "none";
    document.getElementById("incident_end_time_box").style.display = "none";
    document.getElementById("incident_end_time_para").style.display = "none";
    document.getElementById("incident_end_time_input").style.display = "none";

    document.getElementById("polygon_disable_email_box").style.display = "none";
    document.getElementById("incident_region_box").style.display = "none";
    document.getElementById("incident_source_confidence_box").style.display = "none";
    document.getElementById("incident_preview_box").style.display = "none";
    document.getElementById("incident_description_box").style.display = "none";

}




function incident_select_new_region() {

    let prompt_text = "Custom Region Name:"; // ask user for custom region to include in selector
    var custom_region = prompt(prompt_text)

    if (custom_region) { // if user enters a custom region name, reload selector with it included
        incident_load_region_dropdown(custom_region); 
    }

}


function incident_load_region_dropdown(custom_option) {

    document.getElementById("incident_region_dropdown").length = 0; // reset selector whenever function is ran to "refresh" it 

    var region_option = document.createElement('option'); // sets first option to "All Vessels"
    region_option.value = "N/A";
    region_option.innerHTML = "N/A";
    document.getElementById("incident_region_dropdown").appendChild(region_option)

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    ajax_request.open('POST', '' + app_root + '/load_data/load_region_dropdown.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);

            var response = JSON.parse(this.responseText); // retrieve array of region names from php file

            for (var x = 0; x < response.length; x++) {

                if (x == 0 && custom_option) {

                    if (custom_option.length > 22) { // if incident_type is longer than 20 characters, cut it down to 20 characters
                        console.log("custom_option: " + custom_option + " is too long, taking only the first 22 characters");
                        custom_option = custom_option.slice(0,22) + "-"
                    }

                    var region_option = document.createElement('option'); // if custom_option is defined, set this one first in the list
                    region_option.value = custom_option;
                    region_option.innerHTML = custom_option;
                    document.getElementById("incident_region_dropdown").appendChild(region_option)

                    document.getElementById("incident_region_dropdown").selectedIndex = 1; // set selected index to new custom value if entered
                }

                var region_name = response[x]; // for each region name

                if (region_name.length > 22) { // if incident_type is longer than 20 characters, cut it down to 20 characters
                    console.log("region_name: " + region_name + " is too long, taking only the first 22 characters");
                    region_name = region_name.slice(0,22) + "-";
                }

                var region_option = document.createElement('option'); // add each region to dropdown list
                region_option.value = region_name;
                region_option.innerHTML = region_name;
                document.getElementById("incident_region_dropdown").appendChild(region_option)

            }

        }
    }
    ajax_request.send(data_to_send);



}
incident_load_region_dropdown()



var global_filtered_vessels_loaded_array = [];
function load_unfiltered_vessels() {

    var vessel_imo_list = global_filtered_vessels_loaded_array.toString();

    var ajax_request = new XMLHttpRequest();
    var data_to_send = ''
    + 'vessel_imo_list=' + vessel_imo_list
    ajax_request.open('POST', '' + app_root + '/load_data/load_unfiltered_vessels.php', true);
    ajax_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // cant delete

    ajax_request.onreadystatechange = function() {
        if(ajax_request.readyState == 4 && this.status == 200) {
            // console.log(this.responseText);
            var response = JSON.parse(this.responseText);

            for (var x = 0; x < response.length; x++) {

                var vessel_imo = response[x]["vessel_imo"];
                var latitude = Number(response[x]["latitude"]);
                var longitude = Number(response[x]["longitude"]);
                var heading = response[x]["heading"];
                var name = response[x]["name"];
                var callsign = response[x]["callsign"];
                var shipType = response[x]["shipType"];
                var is_vessel_inside_eos_dmz = response[x]["is_vessel_inside_eos_dmz"];
                var is_vessel_inside_route = response[x]["is_vessel_inside_route"];
                var navigationalStatus = response[x]["navigationalStatus"];
                var mmsi = response[x]["mmsi"];
                var speed = response[x]["speed"];
                var destination = response[x]["destination"];
                var date_received = response[x]["date_received"];

                var current_date_seconds = new Date().getTime()
                var date_received_seconds = new Date(date_received).getTime()
                var time_difference_milliseconds = current_date_seconds - date_received_seconds
                var time_difference_seconds = time_difference_milliseconds / 1000
                var time_difference_minutes = time_difference_seconds / 60
                var time_difference_hours = time_difference_minutes / 60

                if (!document.getElementById("marker_" + Number(vessel_imo))) {

                    create_vessel_marker(vessel_imo, latitude, longitude, heading, name, callsign, shipType, is_vessel_inside_eos_dmz, is_vessel_inside_route, navigationalStatus, mmsi, speed, destination, date_received, time_difference_hours);

                }

            }
        }
    
    }
    ajax_request.send(data_to_send);



}


  document.querySelectorAll(".accordion-toggle").forEach(button => {
    button.addEventListener("click", () => {
      const content = button.nextElementSibling;
      const allContents = document.querySelectorAll(".accordion-content");

      allContents.forEach(section => {
        if (section !== content) section.style.display = "none";
      });

      content.style.display = content.style.display === "block" ? "none" : "block";
    });
  });


  
//   const icon = document.querySelector('.icons_topbar_dark');

//   icon.addEventListener('mouseenter', () => {
//     icon.src = './assets/images/dark_hover.svg';
//   });

//   icon.addEventListener('mouseleave', () => {
//     icon.src = './assets/images/dark.svg';
//   });



//   function reset_mode() {
//     const icon = document.querySelector('.icons_topbar_dark');

//     if (icon.src.includes('dark.svg')) {
//       icon.src = './assets/images/light.svg';
//     } else {
//       icon.src = './assets/images/dark.svg';
//     }

//     icon.classList.toggle('icon-toggled');
//   }

function reset_play() {
  const icon = document.querySelector('.icons_topbar_dark_play');
  const logoImg = document.querySelector('.logo img');
  const sidebar = document.querySelector('.sidebar');

  // Toggle icon class for styling/rotation
  icon.classList.toggle('icon-play-toggled');

  // Toggle collapsed class on sidebar
  const isCollapsed = sidebar.classList.toggle('collapsed');

  // Update logo based on sidebar state
  if (logoImg) {
    logoImg.src = isCollapsed
      ? './assets/images/toggle_logo.svg'
      : './assets/images/logo_white.svg';
  }

  // Ensure sidebar expands when any menu item is clicked
    document.querySelectorAll('.menu-item').forEach(item => {
    item.addEventListener('click', () => {
        // Only expand if not on mobile (e.g., width > 992px)
        if (window.innerWidth > 992 && sidebar.classList.contains('collapsed')) {
        sidebar.classList.remove('collapsed');

        // Reset logo to expanded version
        if (logoImg) {
            logoImg.src = './assets/images/logo_white.svg';
        }

        // Reset icon class if needed
        icon.classList.remove('icon-play-toggled');
        }
    });
    });

}


function search_func() {
  const geocoder = document.getElementById('geocoder');
  const isHidden = geocoder.style.display === 'none' || geocoder.style.display === '';

  closeAllPanels();

  if (isHidden) {
    geocoder.style.display = 'block';

    // Trigger reflow before applying transition
    void geocoder.offsetHeight;

    geocoder.style.top = '20px';
  } else {
    // Slide it back up before hiding
    geocoder.style.top = '-40px';

    // After transition ends, hide it
    setTimeout(() => {
      geocoder.style.display = 'none';
    }, 400); // matches the CSS transition duration
  }
}


function map_func_panel() {
  const panel = document.querySelector('.map-options');
  const isHidden = !panel.classList.contains('visible');

  closeAllPanels();

  if (isHidden) {
    panel.classList.add('visible');
  }
}

function direction_option_panel() {
  const panel = document.querySelector('.direction_panels');
  const isHidden = !panel.classList.contains('visible');

  closeAllPanels();

  if (isHidden) {
    panel.classList.add('visible');
  }
}

const sidebar = document.querySelector('.sidebar');
const pageBox = document.getElementById('page_box');

function updatePageBoxWidth() {
  if (sidebar.classList.contains('collapsed')) {
    pageBox.style.width = 'calc(100vw - 65px)';
  } else {
    pageBox.style.width = ''; // Reset or set default width
  }
}

// Example: Run this on page load and when toggling sidebar
updatePageBoxWidth();
sidebar.addEventListener('transitionend', updatePageBoxWidth); // or use your sidebar toggle event

document.querySelectorAll('.application_text_title').forEach(el => {
  el.addEventListener('click', () => {
    el.classList.toggle('rotated');
  });
});




document.querySelectorAll(".menu-item").forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    // Hide all layout wrappers
    document.querySelectorAll(".form_wrapper").forEach(wrapper => {
      wrapper.style.display = "none";
    });

    // Show the add line button
    const addButton = document.querySelector(".add_line_button");
    if (addButton) {
      addButton.style.display = "block";
    }
  });

  item.dataset.bound = "true";
});



function add_company() {
  const companyWrapperId = "company_form_wrapper";
  const formWrapper = document.getElementById(companyWrapperId);

  console.log("add_company triggered");

  // 1. Show the company form
  if (formWrapper) {
    formWrapper.style.display = "flex";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the company menu tab
  const menuTab = document.getElementById("company_menu_tab");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("Company menu tab hidden");
  }

  // 5. Bind .menu-item click handlers only once
const menuItems = document.querySelectorAll(".menu-item");

menuItems.forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    const menuId = this.id;

    const layoutId = menuId
      .replace("Button", "")
      .replace("_menu", "")
      .toLowerCase() + "_form_wrapper";

    console.log("Clicked menu ID:", menuId);
    console.log("Computed layout ID to show:", layoutId);

    let found = false;

    document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
      if (wrapper.id === layoutId) {
        wrapper.style.display = "flex";
        found = true;
      } else {
        wrapper.style.display = "none";
      }
    });

    if (!found) {
      console.warn("No wrapper found with ID:", layoutId);
    }

    if (typeof addButton !== "undefined" && addButton) {
      addButton.style.display = "inline-block";
    }
  });

  item.dataset.bound = "true";
});


  // 6. Setup internal company-tab switching
  const companyTabs = document.querySelectorAll(".company-tab");
  const companySections = document.querySelectorAll(".company-section");

  companyTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      companyTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      companySections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

// 7. Add the back button (or re-bind if it already exists)
let backBtn = document.getElementById("back_button");

if (!backBtn) {
  backBtn = document.createElement("div");
  backBtn.id = "back_button";
  backBtn.className = "back-button";
  backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
  formWrapper.insertBefore(backBtn, formWrapper.firstChild);
  console.log("Back button created and inserted");
} else {
  console.log("Back button already exists – re-binding event");
}

// Re-bind click event every time to be safe
backBtn.onclick = () => {
  console.log("Back button clicked");
  formWrapper.style.display = "none";
  if (layoutWrapper) layoutWrapper.style.display = "none";
  if (addButton) addButton.style.display = "inline-block";
  if (menuTab) menuTab.style.display = "block";
  backBtn.remove();
};

}


function add_vessels() {
  document.getElementById("individual_vessel_wrapper").style.display = "none";
  const vesselsWrapperId = "vessels_form_wrapper";
  const formWrapper = document.getElementById(vesselsWrapperId);

  console.log("add_vessels triggered");

  // 1. Show the vessels form
  if (formWrapper) {
    formWrapper.style.display = "flex";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the vessels menu tab
  const menuTab = document.getElementById("tab_1");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("vessels menu tab hidden");
  }

  // 5. Bind .menu-item click handlers only once
  const menuItems = document.querySelectorAll(".menu-item");
  menuItems.forEach(item => {
    if (item.dataset.bound === "true") return;

    item.addEventListener("click", function () {
      const menuId = this.id;
      const layoutId = menuId.replace("Button", "").replace("_menu", "").toLowerCase() + "_form_wrapper";

      document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
        wrapper.style.display = (wrapper.id === layoutId) ? "flex" : "none";
      });

      if (addButton) addButton.style.display = "inline-block";
    });

    item.dataset.bound = "true";
  });

  // 6. Setup internal vessels-tab switching
  const vesselsTabs = document.querySelectorAll(".vessels-tab");
  const vesselsSections = document.querySelectorAll(".vessels-section");

  vesselsTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      vesselsTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      vesselsSections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

// 7. Add the back button (or re-bind if it already exists)
let backBtn = document.getElementById("back_button_vassel");

if (!backBtn) {
  backBtn = document.createElement("div");
  backBtn.id = "back_button_vassel";
  backBtn.className = "back-button";
  backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
  formWrapper.insertBefore(backBtn, formWrapper.firstChild);
  console.log("Back button created and inserted");
} else {
  console.log("Back button already exists – re-binding event");
}

// Re-bind click event every time to be safe
backBtn.onclick = () => {
  console.log("Back button clicked");
  formWrapper.style.display = "none";
  if (layoutWrapper) layoutWrapper.style.display = "none";
  if (addButton) addButton.style.display = "inline-block";
  if (menuTab) menuTab.style.display = "block";
  backBtn.remove();
};

}


function individual_vessel_edit() {
  const companyWrapperId = "individual_vessel_wrapper";
  const formWrapper = document.getElementById(companyWrapperId);

  console.log("individual_vessel_edit triggered");

  // 1. Show the company form
  if (formWrapper) {
    formWrapper.style.display = "flex";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the company menu tab
  const menuTab = document.getElementById("tab_1");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("Company menu tab hidden");
  }

  // 5. Bind .menu-item click handlers only once
  const menuItems = document.querySelectorAll(".menu-item");

  menuItems.forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    const menuId = this.id;

    const layoutId = menuId
      .replace("Button", "")
      .replace("_menu", "")
      .toLowerCase() + "_form_wrapper";

    console.log("Clicked menu ID:", menuId);
    console.log("Computed layout ID to show:", layoutId);

    let found = false;

    document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
      if (wrapper.id === layoutId) {
        wrapper.style.display = "flex";
        found = true;
      } else {
        wrapper.style.display = "none";
      }
    });

    if (!found) {
      console.warn("No wrapper found with ID:", layoutId);
    }

    if (typeof addButton !== "undefined" && addButton) {
      addButton.style.display = "inline-block";
    }
  });

  item.dataset.bound = "true";
  });


  // 6. Setup internal company-tab switching
  const companyTabs = document.querySelectorAll(".company-tab");
  const companySections = document.querySelectorAll(".company-section");

  companyTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      companyTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      companySections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

    // 7. Add the back button (or re-bind if it already exists)
    let backBtn = document.getElementById("back_button_vassel_ind");

    if (!backBtn) {
    backBtn = document.createElement("div");
    backBtn.id = "back_button_vassel_ind";
    backBtn.className = "back-button";
    backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
    formWrapper.insertBefore(backBtn, formWrapper.firstChild);
    console.log("Back button created and inserted");
    } else {
    console.log("Back button already exists – re-binding event");
    }

    // Re-bind click event every time to be safe
    backBtn.onclick = () => {
    console.log("Back button clicked");
    formWrapper.style.display = "none";
    if (layoutWrapper) layoutWrapper.style.display = "none";
    if (addButton) addButton.style.display = "inline-block";
    if (menuTab) menuTab.style.display = "block";
    backBtn.remove();
    };

 }





document.querySelectorAll(".menu-item").forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    // Hide all layout wrappers
    document.querySelectorAll(".form_wrapper").forEach(wrapper => {
      wrapper.style.display = "none";
    });

    // Show the add line button
    const addButton = document.querySelector(".add_line_button");
    if (addButton) {
      addButton.style.display = "block";
    }
  });

  item.dataset.bound = "true";
});


function add_danger_clicked() {
  const panel = document.getElementById("dangerPanel");
  panel.style.display = "flex";
  setTimeout(() => {
    panel.classList.add("open");
  }, 10); // allow layout to register before transition
  const tab3 = document.getElementById("tab_3");
  if (tab3) tab3.style.display = "none";
}

function close_danger_panel() {
  const panel = document.getElementById("dangerPanel");
  panel.classList.remove("open");
  setTimeout(() => {
    panel.style.display = "none";
  }, 300); // wait for transition to finish
  const tab3 = document.getElementById("tab_3");
  if (tab3) tab3.style.display = "";
}



function add_incident_clicked() {
    openRightBox();
    clear_pages();
    clear_colours();
  const panel = document.getElementById("incidentPanel");
  panel.style.display = "flex";
  setTimeout(() => {
    panel.classList.add("open");
  }, 10); // allow layout to register before transition
  const tab3 = document.getElementById("tab_7");
  if (tab3) tab3.style.display = "none";

    if (document.getElementById("tab_7_button")) {
        document.getElementById("tab_7_button").style.backgroundColor = "#223139";
        document.getElementById("tab_7_button").classList.remove('gray_colour_onhover');
    }

}

function close_incident_panel() {
  const panel = document.getElementById("incidentPanel");
  panel.classList.remove("open");
  setTimeout(() => {
    panel.style.display = "none";
  }, 300); // wait for transition to finish
  const tab3 = document.getElementById("tab_3");
  if (tab3) tab3.style.display = "";
}


  // Run after page load
//   document.addEventListener("DOMContentLoaded", function () {
//     const allMenuButtons = document.querySelectorAll('.menu-item');
    
//     allMenuButtons.forEach(button => {
//       button.addEventListener("click", function (e) {
//         // If the clicked button is not the Questionnaires tab, hide it
//         if (this.id !== "tab_7_button") {
//           hideQuestionnaire();
//         }
//       });
//     });
//   });



function openPopup(el) {
  document.getElementById('popup-imo').textContent = el.dataset.imo;
  document.getElementById('popup-name').textContent = el.dataset.name;
  document.getElementById('popup-callsign').textContent = el.dataset.callsign;
  document.getElementById('popup-type').textContent = el.dataset.type;
  document.getElementById('popup-status').textContent = el.dataset.status;
  document.getElementById('popup-mmsi').textContent = el.dataset.mmsi;
  document.getElementById('popup-speed').textContent = el.dataset.speed;
  document.getElementById('popup-destination').textContent = el.dataset.destination;
  document.getElementById('popup-lat').textContent = el.dataset.lat;
  document.getElementById('popup-lon').textContent = el.dataset.lon;
  document.getElementById('popup-date').textContent = el.dataset.date;

  document.getElementById('vesselPopup').style.display = 'block';
}

function closePopup() {
  document.getElementById('vesselPopup').style.display = 'none';
}


  function openPopup(marker) {
    const popup = document.getElementById('vesselPopup');

    // Get marker position (relative to viewport)
    const rect = marker.getBoundingClientRect();
    const popupWidth = 350;
    const popupHeight = 500;

    // Calculate available space
    const spaceTop = rect.top;
    const spaceBottom = window.innerHeight - rect.bottom;
    const spaceLeft = rect.left;
    const spaceRight = window.innerWidth - rect.right;

    // Clear all position classes first
    popup.classList.remove('popup-top', 'popup-bottom', 'popup-left', 'popup-right');

    // Choose best position
    let top = 0;
    let left = 0;
    if (spaceBottom > popupHeight + 20) {
      // Show popup above the marker
      popup.classList.add('popup-bottom');
      top = rect.bottom + window.scrollY + 10;
      left = rect.left + window.scrollX + rect.width / 2 - popupWidth / 2;
    } else if (spaceTop > popupHeight + 20) {
      // Show popup below the marker
      popup.classList.add('popup-top');
      top = rect.top + window.scrollY - popupHeight - 10;
      left = rect.left + window.scrollX + rect.width / 2 - popupWidth / 2;
    } else if (spaceRight > popupWidth + 20) {
      // Show popup to the left
      popup.classList.add('popup-right');
      top = rect.top + window.scrollY + rect.height / 2 - popupHeight / 2;
      left = rect.right + window.scrollX + 10;
    } else {
      // Default: Show popup to the right
      popup.classList.add('popup-left');
      top = rect.top + window.scrollY + rect.height / 2 - popupHeight / 2;
      left = rect.left + window.scrollX - popupWidth - 10;
    }

    popup.style.top = top + 'px';
    popup.style.left = left + 'px';
    popup.style.display = 'block';

    // Populate data
    document.getElementById('popup-name').innerText = marker.dataset.name;
    document.getElementById('popup-imo').innerText = marker.dataset.imo;
    document.getElementById('popup-callsign').innerText = marker.dataset.callsign;
    document.getElementById('popup-type').innerText = marker.dataset.type;
    document.getElementById('popup-status').innerText = marker.dataset.status;
    document.getElementById('popup-mmsi').innerText = marker.dataset.mmsi;
    document.getElementById('popup-speed').innerText = marker.dataset.speed;
    document.getElementById('popup-destination').innerText = marker.dataset.destination;
    document.getElementById('popup-lat').innerText = marker.dataset.lat;
    document.getElementById('popup-lon').innerText = marker.dataset.lon;
    document.getElementById('popup-date').innerText = marker.dataset.date;
  }

    function openPopupSpecified(imo) {
    // Find all elements with class 'marker'
    const markers = document.querySelectorAll('.marker');

    for (const marker of markers) {
        if (marker.dataset.imo === String(imo)) {
        openPopup(marker); // Call your existing popup function
        return;
        }
    }

    console.warn('No marker found with IMO:', imo);
    }

  function closePopup() {
    document.getElementById('vesselPopup').style.display = 'none';
  }


function route_edit() {
    document.getElementById("individual_vessel_wrapper").style.display = "none";
  const companyWrapperId = "route_form_wrapper";
  const formWrapper = document.getElementById(companyWrapperId);

  console.log("individual_vessel_edit triggered");

  // 1. Show the company form
  if (formWrapper) {
    formWrapper.style.display = "flex";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the company menu tab
  const menuTab = document.getElementById("tab_2");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("Company menu tab hidden");
  }
  const menuTabTwo = document.getElementById("tab_1");
  if (menuTabTwo) {
    menuTabTwo.style.display = "none";
    console.log("Company menu tab hidden");
  }
  // 5. Bind .menu-item click handlers only once
  const menuItems = document.querySelectorAll(".menu-item");

  menuItems.forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    const menuId = this.id;

    const layoutId = menuId
      .replace("Button", "")
      .replace("_menu", "")
      .toLowerCase() + "_form_wrapper";

    console.log("Clicked menu ID:", menuId);
    console.log("Computed layout ID to show:", layoutId);

    let found = false;

    document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
      if (wrapper.id === layoutId) {
        wrapper.style.display = "flex";
        found = true;
      } else {
        wrapper.style.display = "none";
      }
    });

    if (!found) {
      console.warn("No wrapper found with ID:", layoutId);
    }

    if (typeof addButton !== "undefined" && addButton) {
      addButton.style.display = "inline-block";
    }
  });

  item.dataset.bound = "true";
  });


  // 6. Setup internal company-tab switching
  const companyTabs = document.querySelectorAll(".route-tab");
  const companySections = document.querySelectorAll(".route-section");

  companyTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      companyTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      companySections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

    // 7. Add the back button (or re-bind if it already exists)
    let backBtn = document.getElementById("back_button_route");

    if (!backBtn) {
    backBtn = document.createElement("div");
    backBtn.id = "back_button_route";
    backBtn.className = "back-button";
    backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
    formWrapper.insertBefore(backBtn, formWrapper.firstChild);
    console.log("Back button created and inserted");
    } else {
    console.log("Back button already exists – re-binding event");
    }

    // Re-bind click event every time to be safe
    backBtn.onclick = () => {
    console.log("Back button clicked");
    formWrapper.style.display = "none";
    if (layoutWrapper) layoutWrapper.style.display = "none";
    if (addButton) addButton.style.display = "inline-block";
    if (menuTab) menuTab.style.display = "block";
    backBtn.remove();
    };

 }


 
function port_edit() {
  const companyWrapperId = "port_form_wrapper";
  const formWrapper = document.getElementById(companyWrapperId);

  console.log("individual_vessel_edit triggered");

  // 1. Show the company form
  if (formWrapper) {
    formWrapper.style.display = "flex";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the company menu tab
  const menuTab = document.getElementById("tab_4");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("Company menu tab hidden");
  }

  // 5. Bind .menu-item click handlers only once
  const menuItems = document.querySelectorAll(".menu-item");

  menuItems.forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    const menuId = this.id;

    const layoutId = menuId
      .replace("Button", "")
      .replace("_menu", "")
      .toLowerCase() + "_form_wrapper";

    console.log("Clicked menu ID:", menuId);
    console.log("Computed layout ID to show:", layoutId);

    let found = false;

    document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
      if (wrapper.id === layoutId) {
        wrapper.style.display = "flex";
        found = true;
      } else {
        wrapper.style.display = "none";
      }
    });

    if (!found) {
      console.warn("No wrapper found with ID:", layoutId);
    }

    if (typeof addButton !== "undefined" && addButton) {
      addButton.style.display = "inline-block";
    }
  });

  item.dataset.bound = "true";
  });


  // 6. Setup internal company-tab switching
  const companyTabs = document.querySelectorAll(".port-tab");
  const companySections = document.querySelectorAll(".port-section");

  companyTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      companyTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      companySections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

    // 7. Add the back button (or re-bind if it already exists)
    let backBtn = document.getElementById("back_button_port");

    if (!backBtn) {
    backBtn = document.createElement("div");
    backBtn.id = "back_button_port";
    backBtn.className = "back-button";
    backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
    formWrapper.insertBefore(backBtn, formWrapper.firstChild);
    console.log("Back button created and inserted");
    } else {
    console.log("Back button already exists – re-binding event");
    }

    // Re-bind click event every time to be safe
    backBtn.onclick = () => {
    console.log("Back button clicked");
    formWrapper.style.display = "none";
    if (layoutWrapper) layoutWrapper.style.display = "none";
    if (addButton) addButton.style.display = "inline-block";
    if (menuTab) menuTab.style.display = "block";
    backBtn.remove();
    };

 }


function add_users() {
  const companyWrapperId = "user_form_wrapper";
  const formWrapper = document.getElementById(companyWrapperId);

  console.log("user_form_wrapper triggered");

  // 1. Show the company form
  if (formWrapper) {
    formWrapper.style.display = "flex";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the company menu tab
  const menuTab = document.getElementById("tab_8");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("Company menu tab hidden");
  }

  // 5. Bind .menu-item click handlers only once
  const menuItems = document.querySelectorAll(".menu-item");

  menuItems.forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    const menuId = this.id;

    const layoutId = menuId
      .replace("Button", "")
      .replace("_menu", "")
      .toLowerCase() + "_form_wrapper";

    console.log("Clicked menu ID:", menuId);
    console.log("Computed layout ID to show:", layoutId);

    let found = false;

    document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
      if (wrapper.id === layoutId) {
        wrapper.style.display = "flex";
        found = true;
      } else {
        wrapper.style.display = "none";
      }
    });

    if (!found) {
      console.warn("No wrapper found with ID:", layoutId);
    }

    if (typeof addButton !== "undefined" && addButton) {
      addButton.style.display = "inline-block";
    }
  });

  item.dataset.bound = "true";
  });


  // 6. Setup internal company-tab switching
  const companyTabs = document.querySelectorAll(".user-tab");
  const companySections = document.querySelectorAll(".user-section");

  companyTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      companyTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      companySections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

    // 7. Add the back button (or re-bind if it already exists)
    let backBtn = document.getElementById("back_button_user");

    if (!backBtn) {
    backBtn = document.createElement("div");
    backBtn.id = "back_button_user";
    backBtn.className = "back-button";
    backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
    formWrapper.insertBefore(backBtn, formWrapper.firstChild);
    console.log("Back button created and inserted");
    } else {
    console.log("Back button already exists – re-binding event");
    }

    // Re-bind click event every time to be safe
    backBtn.onclick = () => {
    console.log("Back button clicked");
    formWrapper.style.display = "none";
    if (layoutWrapper) layoutWrapper.style.display = "none";
    if (addButton) addButton.style.display = "inline-block";
    if (menuTab) menuTab.style.display = "block";
    backBtn.remove();
    };

 }

function edit_users() {
  const companyWrapperId = "user_edit_form_wrapper";
  const formWrapper = document.getElementById(companyWrapperId);

  console.log("user_edit_form_wrapper triggered");

  // 1. Show the company form
  if (formWrapper) {
    formWrapper.style.display = "flex";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the company menu tab
  const menuTab = document.getElementById("tab_8");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("Company menu tab hidden");
  }

    // 4. Hide the company menu tab
  const individual_vessel_wrapper = document.getElementById("individual_vessel_wrapper");
  if (individual_vessel_wrapper) {
    individual_vessel_wrapper.style.display = "none";
    console.log("individual_vessel_wrapper  hidden");
  }

      // 4. Hide the company menu tab
  const user_form_wrapper = document.getElementById("user_form_wrapper");
  if (individual_vessel_wrapper) {
    user_form_wrapper.style.display = "none";
    console.log("user_form_wrappe hidden");
  }

      // 4. Hide the company menu tab
  const tab_3 = document.getElementById("tab_3");
  if (tab_3) {
    tab_3.style.display = "none";
    console.log("tab_3 hidden");
  }
      // 4. Hide the company menu tab
  const tab_4 = document.getElementById("tab_4");
  if (tab_4) {
    tab_4.style.display = "none";
    console.log("tab_4 hidden");
  }

        // 4. Hide the company menu tab
  const tab_5 = document.getElementById("tab_5");
  if (tab_5) {
    tab_5.style.display = "none";
    console.log("tab_5 hidden");
  }
  // 5. Bind .menu-item click handlers only once
  const menuItems = document.querySelectorAll(".menu-item");

  menuItems.forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    const menuId = this.id;

    const layoutId = menuId
      .replace("Button", "")
      .replace("_menu", "")
      .toLowerCase() + "_form_wrapper";

    console.log("Clicked menu ID:", menuId);
    console.log("Computed layout ID to show:", layoutId);

    let found = false;

    document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
      if (wrapper.id === layoutId) {
        wrapper.style.display = "flex";
        found = true;
      } else {
        wrapper.style.display = "none";
      }
    });

    if (!found) {
      console.warn("No wrapper found with ID:", layoutId);
    }

    if (typeof addButton !== "undefined" && addButton) {
      addButton.style.display = "inline-block";
    }
  });

  item.dataset.bound = "true";
  });


  // 6. Setup internal company-tab switching
  const companyTabs = document.querySelectorAll(".user-edit-tab");
  const companySections = document.querySelectorAll(".user-edit-section");

  companyTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      companyTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      companySections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

    // 7. Add the back button (or re-bind if it already exists)
    let backBtn = document.getElementById("back_button_user_edit");

    if (!backBtn) {
    backBtn = document.createElement("div");
    backBtn.id = "back_button_user_edit";
    backBtn.className = "back-button";
    backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
    formWrapper.insertBefore(backBtn, formWrapper.firstChild);
    console.log("Back button created and inserted");
    } else {
    console.log("Back button already exists – re-binding event");
    }

    // Re-bind click event every time to be safe
    backBtn.onclick = () => {
    console.log("Back button clicked");
    formWrapper.style.display = "none";
    if (layoutWrapper) layoutWrapper.style.display = "none";
    if (addButton) addButton.style.display = "inline-block";
    if (menuTab) menuTab.style.display = "block";
    backBtn.remove();
    };

 }

 
function log_edit() {
  document.getElementById("individual_vessel_wrapper").style.display = "none";
  const companyWrapperId = "tab_7";
  const formWrapper = document.getElementById(companyWrapperId);

  console.log("individual_vessel_edit triggered");

  // 1. Show the company form
  if (formWrapper) {
    formWrapper.style.display = "block";
    console.log("Form wrapper shown");
  } else {
    console.error("Form wrapper not found");
    return;
  }

  // 2. Show the general .layout-wrapper if it's hidden
  const layoutWrapper = document.querySelector(".layout-wrapper");
  if (layoutWrapper) {
    layoutWrapper.style.display = "flex";
    console.log("Layout wrapper shown");
  }

  // 3. Hide the add button
  const addButton = document.querySelector(".add_line_button");
  if (addButton) {
    addButton.style.display = "none";
    console.log("Add button hidden");
  }

  // 4. Hide the company menu tab
  const menuTab = document.getElementById("tab_1");
  if (menuTab) {
    menuTab.style.display = "none";
    console.log("Company menu tab hidden");
  }

  // 5. Bind .menu-item click handlers only once
  const menuItems = document.querySelectorAll(".menu-item");

  menuItems.forEach(item => {
  if (item.dataset.bound === "true") return;

  item.addEventListener("click", function () {
    const menuId = this.id;

    const layoutId = menuId
      .replace("Button", "")
      .replace("_menu", "")
      .toLowerCase() + "_form_wrapper";

    console.log("Clicked menu ID:", menuId);
    console.log("Computed layout ID to show:", layoutId);

    let found = false;

    document.querySelectorAll(".layout-wrapper").forEach(wrapper => {
      if (wrapper.id === layoutId) {
        wrapper.style.display = "flex";
        found = true;
      } else {
        wrapper.style.display = "none";
      }
    });

    if (!found) {
      console.warn("No wrapper found with ID:", layoutId);
    }

    if (typeof addButton !== "undefined" && addButton) {
      addButton.style.display = "inline-block";
    }
  });

  item.dataset.bound = "true";
  });


  // 6. Setup internal company-tab switching
  const companyTabs = document.querySelectorAll(".port-tab");
  const companySections = document.querySelectorAll(".port-section");

  companyTabs.forEach(tab => {
    tab.addEventListener("click", function () {
      companyTabs.forEach(t => t.classList.remove("active-tab"));
      this.classList.add("active-tab");

      companySections.forEach(section => section.style.display = "none");

      const targetId = this.dataset.target;
      const target = document.getElementById(targetId);
      if (target) {
        target.style.display = "block";
      }
    });
  });

    // 7. Add the back button (or re-bind if it already exists)
    let backBtn = document.getElementById("back_button_log_edit");

    if (!backBtn) {
    backBtn = document.createElement("div");
    backBtn.id = "back_button_log_edit";
    backBtn.className = "back-button";
    backBtn.innerHTML = '<span class="back-arrow">&#8592;</span> Back';
    formWrapper.insertBefore(backBtn, formWrapper.firstChild);
    console.log("Back button created and inserted");
    } else {
    console.log("Back button already exists – re-binding event");
    }

    // Re-bind click event every time to be safe
    backBtn.onclick = () => {
    console.log("Back button clicked");
    formWrapper.style.display = "none";
    if (layoutWrapper) layoutWrapper.style.display = "none";
    if (addButton) addButton.style.display = "inline-block";
    if (menuTab) menuTab.style.display = "block";
    backBtn.remove();
    };

 }




  // Function to show the questionnaire section
  function questionnaires_open() {
    openRightBox();
    clear_pages();
    clear_colours();


    if (document.getElementById("tab_6_button")) {
        document.getElementById("tab_6_button").style.backgroundColor = "#223139";
        document.getElementById("tab_6_button").classList.remove('gray_colour_onhover');
    }
    document.getElementById("questionnaire_section").style.display = "block";
  }

  // Function to hide the questionnaire section
  function hideQuestionnaire() {
    document.getElementById("questionnaire_section").style.display = "none";
  }

  // Run after page load
  document.addEventListener("DOMContentLoaded", function () {
    const allMenuButtons = document.querySelectorAll('.menu-item');
    
    allMenuButtons.forEach(button => {
      button.addEventListener("click", function (e) {
        // If the clicked button is not the Questionnaires tab, hide it
        if (this.id !== "tab_6_button") {
          hideQuestionnaire();
        }
      });
    });
  });


  // User dropdown
function toggleUserDropdown() {
  const dropdown = document.getElementById('userDropdown');
  const isHidden = dropdown.style.display === 'none' || dropdown.style.display === '';

  closeAllPanels();

  if (isHidden) {
    dropdown.style.display = 'block';
  }
}

  // Optional: Hide dropdown if clicked outside
  document.addEventListener('click', function (event) {
    const button = document.getElementById('userDropdownButton');
    const dropdown = document.getElementById('userDropdown');

    if (!button.contains(event.target) && !dropdown.contains(event.target)) {
      dropdown.style.display = 'none';
    }
  });





    // Function to hide the questionnaire section
  function hidelog() {
    document.getElementById("tab_7").style.display = "none";
  }

  // Run after page load
  document.addEventListener("DOMContentLoaded", function () {
    const allMenuButtons = document.querySelectorAll('.menu-item');
    
    allMenuButtons.forEach(button => {
      button.addEventListener("click", function (e) {
        // If the clicked button is not the Questionnaires tab, hide it
        if (this.id !== "tab_7") {
          hidelog();
        }
      });
    });
});


// Log popup

  function log_popup() {
    closePopup();
    document.getElementById("logPopup").style.display = "flex";
  }

  function logclosePopup() {
    document.getElementById("logPopup").style.display = "none";
  }

  // Optional: Close when clicking outside the popup
  window.addEventListener('click', function (e) {
    const popup = document.querySelector('.popup-box');
    const overlay = document.getElementById('logPopup');
    if (e.target === overlay) {
      closePopup();
    }
  });

// Log Delete

  function deletePopup() {
    closePopup();
    document.getElementById("deletePopup").style.display = "flex";
  }

  function dltclosePopup() {
    document.getElementById("deletePopup").style.display = "none";
  }

  // Optional: Close when clicking outside the popup
  window.addEventListener('click', function (e) {
    const popup = document.querySelector('.popup-box');
    const overlay = document.getElementById('deletePopup');
    if (e.target === overlay) {
      closePopup();
    }
  });

  // Log Delete

  function addint() {
    closePopup();
    document.getElementById("intPopup").style.display = "flex";
  }

  function addclosePopup() {
    document.getElementById("intPopup").style.display = "none";
  }

  // Optional: Close when clicking outside the popup
  window.addEventListener('click', function (e) {
    const popup = document.querySelector('.popup-box');
    const overlay = document.getElementById('intPopup');
    if (e.target === overlay) {
      closePopup();
    }
  });





function isMobileOrTablet() {
  return window.innerWidth <= 992;
}

function handleMobileView() {
  // ✅ Put your expand/toggle logic here
  // For example: show a menu, expand panels, or call your custom function
  reset_play(); // or any function like togglePanel()
}

// Run on initial load
if (isMobileOrTablet()) {
 // handleMobileView();
}

let wasMobile = isMobileOrTablet();

// Run on resize
window.addEventListener('resize', function () {
  const isMobile = isMobileOrTablet();

  // ✅ Only trigger when resizing *into* mobile view
  if (isMobile && !wasMobile) {
   // handleMobileView();
  }

  wasMobile = isMobile;
});

// Prevent clicks inside popup-boxes from closing them
var popupBoxes = document.querySelectorAll('.popup-box');
popupBoxes.forEach(function(box) {
  box.addEventListener('click', function(event) {
    event.stopPropagation(); // Prevent bubbling to overlay
  });
});

// Set up overlay click detection for each popup
var overlays = document.querySelectorAll('.popup-overlay');
overlays.forEach(function(overlay) {
  overlay.addEventListener('click', function(event) {
    // Only handle clicks directly on the overlay (outside the popup-box)
    if (event.target === overlay) {
      if (overlay.id === 'intPopup') {
        addclosePopup();
      } else if (overlay.id === 'deletePopup') {
        dltclosePopup();
      } else if (overlay.id === 'logPopup') {
        logclosePopup();
      }

      // Call universal panel closer
      closeAllPanels(); clear_pages(); closeRightBox(); clear_colours();
    }
  });
});


document.addEventListener('DOMContentLoaded', function () {
   
  reset_mode();
  reset_play();

  const logoLink = document.querySelector('.logo a');
  const geocoder = document.getElementById('geocoder');
  const close_btn = document.getElementById('tab_3_button');
  const main_close_btn = document.getElementById('tab_7_button');
  


  if (logoLink && geocoder) {
    logoLink.addEventListener('click', function () {
      closeAllPanels();
      geocoder.style.display = 'none';
    });

  }
      close_btn.addEventListener('click', function () {
      geocoder.style.display = 'none';
      //closeAllPanels();
    });
    main_close_btn.addEventListener('click', function () {
      geocoder.style.display = 'none';
      //closeAllPanels();
    });
});


// Active for option tggole menu 

 document.querySelectorAll('#logoBox li').forEach(li => {
    li.addEventListener('click', function (e) {
      e.stopPropagation(); // Prevent outside click from firing

      const isActive = this.classList.contains('active');

      // Remove .active from all
      document.querySelectorAll('#logoBox li').forEach(item => item.classList.remove('active'));

      // Toggle .active if it wasn't already
      if (!isActive) {
        this.classList.add('active');
      }
    });
  });

  // Remove .active when clicking outside #logoBox or on any <a>
  document.addEventListener('click', function (e) {
    const clickedInside = document.getElementById('logoBox').contains(e.target);
    const isAnchor = e.target.closest('a');

    if (!clickedInside || isAnchor) {
      document.querySelectorAll('#logoBox li').forEach(item => item.classList.remove('active'));
    }
  });


  document.querySelectorAll('.accordion-toggle').forEach(button => {
    button.addEventListener('click', function () {
      const isOpen = this.classList.contains('active');

      // Close all
      document.querySelectorAll('.accordion-toggle').forEach(btn => btn.classList.remove('active'));

      // Open only if not already open
      if (!isOpen) {
        this.classList.add('active');
      }
    });
  });

// DMZ tab
    const tabs = document.querySelectorAll('.region-tab');
    const contents = document.querySelectorAll('.region-tab-content');

    tabs.forEach(tab => {
      tab.addEventListener('click', () => {
        // Remove active class from all tabs
        tabs.forEach(t => t.classList.remove('active'));

        // Add active class to current tab
        tab.classList.add('active');

        // Hide all content sections
        contents.forEach(c => c.classList.remove('active'));

        // Show selected content
        const targetId = 'tab-' + tab.dataset.tab;
        document.getElementById(targetId).classList.add('active');
      });
    });

// Dropdown menu tab
    const button = document.querySelector('.add_line_button.mobile');
    const menu = document.getElementById('dropdownMenu');

    button.addEventListener('click', () => {
      menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
    });

    // Close dropdown if clicked outside
    document.addEventListener('click', (e) => {
      if (!button.contains(e.target) && !menu.contains(e.target)) {
        menu.style.display = 'none';
      }
    });