{% extends "base.html" %}
{% block content %}

<div id="set_anchor_alarm_modal" tabindex="-1" class="modal fade" data-backdrop="static"
     xmlns="http://www.w3.org/1999/html"
     role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content" id="set_anchor_alarm_modal_content">
            <div class="modal-header">
                <h5 class="modal-title">Anchor alarm configuration</h5>
            </div>
            <div class="modal-body">
                <h4>Anchor position</h4>
                <div class="container mb-2" style="border: 1px solid #000; padding: 10px;">
                    <div class="row">
                        <div class="row border-1">
                            <label class="col col-sm-3">
                                <input type="radio" name="toggleRadio" value="default"
                                       id="default_anchor_configuration_button_id"
                                       onchange="setAnchorDefaultConfigurationOnChange()" checked> Default
                            </label>
                            <label class="col col-sm-4">
                                <input type="radio" name="toggleRadio" value="alternative"
                                       id="alternative_anchor_configuration_button_id"
                                       onchange="setAnchorAlternativeConfigurationOnChange()"> Alternative
                            </label>
                        </div>
                        <div class="row align-items-center" id="default_anchor_configuration_div_id">
                            <div class="col col-sm">
                                <div class="row">
                            <span>Latitude:&nbsp<input type="text" id="set_anchor_alarm_latitude_text_id"
                                                       placeholder="Latitude"/></span>
                                </div>
                                <div class="row">
                            <span>Longitude:&nbsp<input type="text" id="set_anchor_alarm_longitude_text_id"
                                                        placeholder="Longitude"/></span>
                                </div>
                            </div>
                            <div class="col-12 col-sm">
                                <button class="btn btn-outline-primary" type="button" onclick="useCurrentPosition()">
                                    <span><i class="bi bi-crosshair"></i>&nbspUse current position</span>
                                </button>
                            </div>
                        </div>
                        <div id="alternative_anchor_configuration_div_id" style="display: none; visibility: hidden">
                            <div class="col col-sm">
                                <div class="row">
                            <span>Bearing to anchor:&nbsp<input type="number" id="set_anchor_alarm_bearing_text_id"
                                                                placeholder="Bearing (in degrees)"/></span>
                                </div>
                                <div class="row">
                            <span>Distance to anchor:&nbsp<input type="number" id="set_anchor_alarm_distance_text_id"
                                                                 placeholder="Distance (in meters)"/></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mb-2">
                    <span>Allowed distance:&nbsp<input type="number" step="1"
                                                       id="set_anchor_alarm_allowed_distance_text_id"
                                                       placeholder="Distance (in meters)"/>&nbspin meters</span>
                </div>
            </div>
            <div class="modal-footer">
                <div class="d-flex col" id="set_anchor_check_your_input_div_id"
                     style="visibility: hidden; display: none">
                    <label class="text-danger">Check your input! </label>
                </div>
                <button type="button" class="btn btn-success" onclick="setAnchor()">
                    Set Anchor
                </button>
                <button type="button" class="close btn btn-secondary" onclick="hideSetAnchorAlarmModal()">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<div id="update_anchor_alarm_modal" tabindex="-1" class="modal fade" data-backdrop="static"
     xmlns="http://www.w3.org/1999/html"
     role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content" id="update_anchor_alarm_modal_content">
            <div class="modal-header">
                <h5 class="modal-title">Anchor alarm configuration</h5>
            </div>
            <div class="modal-body">
                <div class="container mb-2" style="border: 1px solid #000; padding: 10px;">
                    <div class="row">
                        <div class="col">
                            <h4>Anchor position</h4>
                            <div class="row mb-2">
                                <div class="col">
                                    <div class="row">
                                                <span>Latitude:&nbsp<span
                                                        id="update_anchor_alarm_latitude_label_id"></span></span>
                                    </div>
                                    <div class="row">
                                    <span>Longitude:&nbsp<span
                                            id="update_anchor_alarm_longitude_label_id"></span></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col">
                            <h4>Current position</h4>
                            <div class="row mb-2">
                                <div class="col">
                                    <div class="row">
                                        <span>Latitude:&nbsp<span
                                                id="update_anchor_alarm_current_latitude_label_id"></span></span>
                                    </div>
                                    <div class="row">
                                    <span>Longitude:&nbsp<span
                                            id="update_anchor_alarm_current_longitude_label_id"></span></span>
                                    </div>
                                    <div class="row text-success fw-bolder"
                                         id="update_anchor_alarm_distance_from_anchor_div_id">
                                    <span>Distance from anchor:&nbsp<span
                                            id="update_anchor_alarm_distance_from_anchor_label_id"></span>&nbspm</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mb-2">
                    <span>Allowed distance:&nbsp<input type="number" step="1"
                                                       id="update_anchor_alarm_allowed_distance_text_id"
                                                       placeholder="Distance (in meters)"/>&nbspin meters</span>
                </div>
            </div>
            <div class="modal-footer">
                <div class="d-flex col" id="update_anchor_check_your_input_div_id"
                     style="visibility: hidden; display: none">
                    <label class="text-danger">Check your input! </label>
                </div>
                <button type="button" class="btn btn-success" onclick="updateAnchor()">
                    <span>Update</span>
                </button>
                <button type="button" class="btn btn-danger" onclick="showCancelAnchorAlarmModal()">
                    <span>Cancel</span>
                </button>
                <button type="button" class="close btn btn-secondary" onclick="hideUpdateAnchorAlarmModal()">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<div id="cancel_anchor_alarm_modal" tabindex="-1" class="modal fade" data-backdrop="static"
     xmlns="http://www.w3.org/1999/html">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content" id="cancel_anchor_alarm_modal_content">
            <div class="modal-header">
                <h5 class="modal-title">Cancel anchor alarm?</h5>
            </div>
            <div class="modal-body">
                Are you sure you want to cancel the existing anchor alarm?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideCancelAnchorAlarmModal()">No</button>
                <button type="button" class="btn btn-primary" onclick="cancelAnchorAlarm()">Yes</button>
            </div>
        </div>
    </div>
</div>

<div class="container p-0 mt-1">
    <div id="warning_notification" class="alert alert-warning ms-2 me-2 mb-0 text-danger" role="alert"
         style="display: none">
        <span><i class="bi bi-exclamation-triangle mb-2 me-2"></i><span id="warning_notification_message">This is the warning notification message placeholder</span></span>
    </div>
    <div id="success_notification" class="alert alert-success ms-2 me-2 mb-0" role="alert"
         style="display: none">
        <span><i class="bi bi-check-square mb-2 me-2"></i><span id="success_notification_message">This is the success notification message placeholder</span></span>
    </div>
</div>

<div class="container-fluid">
    <div class="d-lg-flex flex-lg-row d-sm-flex flex-sm-row mb-1">
        <div class="col-lg-5 col-md-4 col-sm-4 m-2 border border-5 border-success rounded text-center">
            <!-- System metrics column-->
            <h5 class="fw-bolder mb-2">System metrics</h5>
            <div class="container">
                <div class="row">
                    <div class="col">
                        <div class="mb-1" style="font-weight: regular;">Battery SOC</div>
                        <canvas id="battery_soc_gauge" style="width: 200px; height: 95px;"></canvas>
                        <div class="container">
                            <div class="row justify-content-center">
                                <span>
                                    <span id="battery_soc_value"></span>&nbsp;%
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="mb-1" style="font-weight: regular;">Fuel Tank Level</div>
                        <canvas id="fuel_tank_gauge" style="width: 200px; height: 95px;"></canvas>
                        <div class="container">
                            <div class="row justify-content-center">
                                <span>
                                    <span id="fuel_tank_value"></span>&nbsp;%
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col">
                        <div class="mb-1" style="font-weight: regular;">Starter Batt. V.</div>
                        <canvas id="starter_battery_voltage_gauge" style="width: 200px; height: 95px;"></canvas>
                        <div class="container">
                            <div class="row justify-content-center">
                                <span>
                                    <span id="starter_battery_voltage_value"></span>&nbsp;V
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="mb-1" style="font-weight: regular;">Water Tank Level</div>
                        <canvas id="water_tank_gauge" style="width: 200px; height: 95px;"></canvas>
                        <div class="container">
                            <div class="row justify-content-center">
                                <span>
                                    <span id="water_tank_value"></span>&nbsp;%
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mt-2 mb-2 align-items-center">
                    <div class="col">
                        <div class="mb-1" style="font-weight: regular;">PV Power</div>
                        <canvas id="pv_power_gauge" style="width: 200px; height: 95px;"></canvas>
                        <div class="container">
                            <div class="row justify-content-center">
                                <span>
                                    <span id="pv_power_value"></span>&nbsp;W
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div id="summary-box-id"
                             class="container border-1 border border-light rounded gx-0 gy-0 text-start">
                            <div class="row ms-1 mt-1">
                                <span>
                                    Active input source:&nbsp;<span id="active_input_source_value">N/A</span>
                                </span>
                            </div>
                            <div class="row ms-1">
                                <span>
                                    VE.Bus state:&nbsp;<span id="ve_bus_state_value">N/A</span>
                                </span>
                            </div>
                            <div class="row ms-1">
                                <span>
                                    Housing battery state:&nbsp;<span id="housing_battery_state_value">N/A</span>
                                </span>
                            </div>
                            <div class="row ms-1">
                                <span>
                                    Housing battery current:&nbsp;<span id="housing_battery_current_value">N/A</span>A
                                </span>
                            </div>
                            <div class="row ms-1 mb-1">
                                <span>
                                    PV current:&nbsp;<span id="pv_current_value">N/A</span>A
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col m-2">
            <div class="row">
                <ul class="nav nav-tabs" id="session-anchor-navbar" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="session-tab" data-bs-toggle="tab" data-bs-target="#session"
                                type="button" role="tab" aria-controls="session" aria-selected="true">Session
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="anchor-tab" data-bs-toggle="tab" data-bs-target="#anchor"
                                type="button" role="tab" aria-controls="anchor" aria-selected="false">Anchor
                        </button>
                    </li>
                </ul>
            </div>
            <div class="row border border-5 border-danger rounded text-center d-flex">
                <div class="tab-content">
                    <div class="tab-pane fade show active" id="session" role="tabpanel" aria-labelledby="session-tab">
                        <!-- Session panel-->
                        <div id="no_session_message" class="container-fluid align-self-center">
                            <h5>No session in progress</h5>
                        </div>
                        <div id="session_container" style="display: none; visibility: hidden;"
                             class="container-fluid align-self-top">
                            <h5 id="session_name">Session name</h5>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Start time (Local):&nbsp;<span id="start_time"></span></span>
                                </div>
                                <div class="col">
                                    <span>Start time (UTC):&nbsp;<span id="start_time_utc"></span></span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <span>Duration:&nbsp;<span id="duration"></span></span>
                            </div>
                            <div class="row">
                                <hr class="mt-1 mb-1"/>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Starting GPS latitude:&nbsp;<span id="start_gps_lat"></span></span>
                                </div>
                                <div class="col">
                                    <span>Starting GPS longitude:&nbsp;<span id="start_gps_lon"></span></span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Distance:&nbsp;<span id="distance"></span>&nbsp;miles</span>
                                </div>
                                <div class="col">
                                    <span>Heading:&nbsp;<span id="heading"></span>&nbsp;Degrees</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Average wind speed:&nbsp;<span
                                            id="average_wind_speed"></span>&nbsp;knots</span>
                                </div>
                                <div class="col">
                                    <span>Average wind direction:&nbsp;<span id="average_wind_direction"></span>&nbsp;Degrees</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Average water temperature:&nbsp;<span id="average_water_temperature"></span>&nbsp;Celsius</span>
                                </div>
                                <div class="col">
                                    <span>Average depth:&nbsp;<span id="average_depth"></span>&nbsp;meters</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Average speed over ground:&nbsp;<span
                                            id="average_sog"></span>&nbsp;knots</span>
                                </div>
                                <div class="col">
                                    <span>Average speed over water:&nbsp;<span
                                            id="average_sow"></span>&nbsp;knots</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                        <span>Housing battery max voltage:&nbsp;<span
                                id="housing_battery_max_voltage"></span>&nbsp;V</span>
                                </div>
                                <div class="col">
                        <span>Housing battery min voltage:&nbsp;<span
                                id="housing_battery_min_voltage"></span>&nbsp;V</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                        <span>Housing battery avg. voltage:&nbsp;<span
                                id="housing_battery_avg_voltage"></span>&nbsp;V</span>
                                </div>
                                <div class="col">
                        <span>Housing battery max current:&nbsp;<span
                                id="housing_battery_max_current"></span>&nbsp;A</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                        <span>Housing battery avg. current:&nbsp;<span
                                id="housing_battery_avg_current"></span>&nbsp;A</span>
                                </div>
                                <div class="col">
                                    <span>Housing battery max power:&nbsp;<span id="housing_battery_max_power"></span>&nbsp;W</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                        <span>Housing battery avg. power:&nbsp;<span
                                id="housing_battery_avg_power"></span>&nbsp;W</span>
                                </div>
                                <div class="col">
                                    <span>PV max power:&nbsp;<span id="pv_max_power"></span>&nbsp;W</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>PV avg. power:&nbsp;<span id="pv_avg_power"></span>&nbsp;W</span>
                                </div>
                                <div class="col">
                                    <span>PV max current:&nbsp;<span id="pv_max_current"></span>&nbsp;A</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>PV avg. current:&nbsp;<span id="pv_avg_current"></span>&nbsp;A</span>
                                </div>
                                <div class="col">
                        <span>Starter battery max voltage:&nbsp;<span
                                id="starter_battery_max_voltage"></span>&nbsp;V</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                        <span>Starter battery min voltage:&nbsp;<span
                                id="starter_battery_min_voltage"></span>&nbsp;V</span>
                                </div>
                                <div class="col">
                        <span>Starter battery avg. voltage:&nbsp;<span
                                id="starter_battery_avg_voltage"></span>&nbsp;V</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Tank 1 max level:&nbsp;<span id="tank1_max_level"></span>&nbsp;%</span>
                                </div>
                                <div class="col">
                                    <span>Tank 1 min level:&nbsp;<span id="tank1_min_level"></span>&nbsp;%</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Tank 1 avg. level:&nbsp;<span id="tank1_avg_level"></span>&nbsp;%</span>
                                </div>
                                <div class="col">
                                    <span>Tank 2 max level:&nbsp;<span id="tank2_max_level"></span>&nbsp;%</span>
                                </div>
                            </div>
                            <div class="row text-start">
                                <div class="col">
                                    <span>Tank 2 min level:&nbsp;<span id="tank2_min_level"></span>&nbsp;%</span>
                                </div>
                                <div class="col">
                                    <span>Tank 2 avg. level:&nbsp;<span id="tank2_avg_level"></span>&nbsp;%</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="anchor" role="tabpanel" aria-labelledby="anchor-tab">
                        <!-- Anchor panel-->
                        <div id="anchor_alarm_is_not_set_message" class="container-fluid align-self-center">
                            <h5>Anchor alarm is not set</h5>
                        </div>
                        <div id="anchor_container" style="display: none; visibility: hidden;"
                             class="container-fluid align-self-top">
                            <div class="row text-start">
                                <div class="col-12 col-sm-6 col-xl-4 mb-2">
                                    <h5 class="fw-bolder">Start time</h5>
                                    <span>Local:&nbsp;<span id="anchor_start_time"></span></span>
                                    <br>
                                    <span>UTC:&nbsp;<span id="anchor_start_time_utc"></span></span>
                                </div>
                                <div class="col-12 col-sm-6 col-xl-4 mb-2">
                                    <h5 class="fw-bolder">Distance</h5>
                                    <span class="fw-bolder">Allowed Distance:&nbsp<span
                                            id="anchor_allowed_distance"></span>&nbspm</span>
                                    <br>
                                    <span id="distance_from_anchor_span" class="fw-bolder text-success">Distance from anchor:&nbsp<span
                                            id="anchor_distance"></span>&nbspm</span>
                                </div>
                                <div class="col-12 col-sm-6 col-xl-4 mb-2">
                                    <h5 class="fw-bolder">Anchor position</h5>
                                    <span>Latitude:&nbsp<span id="anchor_latitude"></span></span>
                                    <br>
                                    <span>Longitude:&nbsp<span id="anchor_longitude"></span></span>
                                </div>
                                <div class="col-12 col-sm-6 col-xl-4 mb-2">
                                    <h5 class="fw-bolder">Current position</h5>
                                    <span>Latitude:&nbsp<span id="current_latitude"></span></span>
                                    <br>
                                    <span>Longitude:&nbsp<span id="current_longitude"></span></span>
                                </div>
                                <div class="col-12 col-sm-6 col-xl-4 mb-2">
                                    <h5 class="fw-bolder">Other metrics</h5>
                                    <span>Duration:&nbsp<span
                                            id="anchor_duration"></span></span>
                                    <br>
                                    <span>Anchor bearing:&nbsp<span
                                            id="anchor_bearing"></span>&nbspdegrees</span>
                                    <br>
                                    <span>GPS Accuracy:&nbsp<span
                                            id="gps_accuracy"></span></span>
                                </div>
                            </div>
                            <div class="row">
                                <hr class="mt-1 mb-1"/>
                            </div>
                            <div id="map-container">
                                <div id="map-button-container">
                                    <button id="default_map_layer_button" class="bg-secondary"
                                            onclick="showDefaultMapLayer()" disabled>Default
                                    </button>
                                    <button id="satellite_map_layer_button" class="bg-secondary text-light"
                                            onclick="showSatelliteMapLayer()">Satellite
                                    </button>
                                    <button id="zoom_in_button" class="bg-secondary text-light" onclick="zoomIn()">Zoom
                                        In <i class="bi bi-zoom-in"></i></button>
                                    <button id="zoom_out_button" class="bg-secondary text-light" onclick="zoomOut()">
                                        Zoom Out <i class="bi bi-zoom-out"></i></button>
                                    <label class="bg-secondary text-light p-1">
                                        <input type="checkbox" id="track_current_position_checkbox">
                                        <span>Track current position</span>
                                    </label>
                                </div>
                                <div id="anchor-map"></div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row mb-2">
        <div class="col d-flex justify-content-center">
            <span>
                <span class="spinner-grow text-danger me-2" style="width: 1rem; height: 1rem;"
                      id="victron_module_spinner" role="status"></span>Victron module:&nbsp;<span
                    id="victron_module_status"></span>
            </span>
        </div>
        <div class="col d-flex justify-content-center">
            <span>
                <span class="spinner-grow text-danger me-2" style="width: 1rem; height: 1rem;" id="nmea_module_spinner"
                      role="status"></span>NMEA0183 module:&nbsp;<span id="nmea_module_status"></span>
            </span>
        </div>
        <div class="col d-flex justify-content-center">
            <span>
                <span class="spinner-grow text-danger me-2" style="width: 1rem; height: 1rem;" id="gps_module_spinner"
                      role="status"></span>GPS module:&nbsp;<span id="gps_module_status"></span>
            </span>
        </div>
    </div>
</div>

<script type="text/javascript">
first_refresh_data_call = true;

{% if session_run_mode == 'manual' %}
document.getElementById('session_button_id').disabled = false;
{% else %}
document.getElementById('session_button_id').disabled = true;
{% endif %}

{% if anchor_alarm_module %}
document.getElementById('anchor_alarm_section').style.display = 'block';
document.getElementById('anchor_alarm_section').style.visibility = 'visible';
{% else %}
document.getElementById('anchor_alarm_section').style.display = 'none';
document.getElementById('anchor_alarm_section').style.visibility = 'hidden';
{% endif %}

anchorMap = new ol.Map({
    layers: [
            new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ],
    target: 'anchor-map',
    controls: []
});

anchorDecimalLatitude = ''
anchorDecimalLongitude = ''
anchorAllowedDistance = ''
anchorPositionHistory = ''
boatMarker = undefined;
lastPositionLatitude = '';
lastPositionLongitude = '';

const connectionLostModal = new bootstrap.Modal(document.getElementById('connection_lost_modal'), {backdrop: 'static'});
const setAnchorAlarmModal = new bootstrap.Modal(document.getElementById('set_anchor_alarm_modal'), {backdrop: 'static'});
const updateAnchorAlarmModal = new bootstrap.Modal(document.getElementById('update_anchor_alarm_modal'), {backdrop: 'static'});
const cancelAnchorAlarmModal = new bootstrap.Modal(document.getElementById('cancel_anchor_alarm_modal'), {backdrop: 'static'});

var common_gauge_options_dark = {
  angle: 0.15, // The span of the gauge arc
  lineWidth: 0.44, // The line thickness
  radiusScale: 1, // Relative radius
  pointer: {
    length: 0.6, // // Relative to gauge radius
    strokeWidth: 0.035, // The thickness
    color: '#ffffff' // Fill color
  },
  limitMax: false,     // If false, max value increases automatically if value > maxValue
  limitMin: false,     // If true, the min value of the gauge will be fixed
  percentColors: [[0.0, "#ff0000" ], [0.5, "#f9c802"], [1, "#a9d70b"]], // !!!!
  colorStart: '#6FADCF',   // Colors
  colorStop: '#8FC0DA',    // just experiment with them
  strokeColor: '#E0E0E0',  // to see which ones work best for you
  generateGradient: true,
  highDpiSupport: true,     // High resolution support
  staticLabels: {
  font: "10px sans-serif",  // Specifies font
  labels: [25, 50, 75, 100],  // Print labels at these values
  color: "#ffffff",  // Optional: Label text color
  fractionDigits: 0  // Optional: Numerical precision. 0=round off.
	},
};

var common_gauge_options_light = {
  angle: 0.15, // The span of the gauge arc
  lineWidth: 0.44, // The line thickness
  radiusScale: 1, // Relative radius
  pointer: {
    length: 0.6, // // Relative to gauge radius
    strokeWidth: 0.035, // The thickness
    color: '#000000' // Fill color
  },
  limitMax: false,     // If false, max value increases automatically if value > maxValue
  limitMin: false,     // If true, the min value of the gauge will be fixed
  percentColors: [[0.0, "#ff0000" ], [0.5, "#f9c802"], [1, "#a9d70b"]], // !!!!
  colorStart: '#6FADCF',   // Colors
  colorStop: '#8FC0DA',    // just experiment with them
  strokeColor: '#E0E0E0',  // to see which ones work best for you
  generateGradient: true,
  highDpiSupport: true,     // High resolution support
  staticLabels: {
  font: "10px sans-serif",  // Specifies font
  labels: [25, 50, 75, 100],  // Print labels at these values
  color: "#000000",  // Optional: Label text color
  fractionDigits: 0  // Optional: Numerical precision. 0=round off.
	},
};

var battery_voltage_gauge_options_dark = {
  lines: 12,
  angle: 0.15,
  lineWidth: 0.44,
  pointer: {
    length: 0.6, // // Relative to gauge radius
    strokeWidth: 0.035, // The thickness
    color: '#ffffff' // Fill color
  },
  limitMax: 'false',
  percentColors: [[0.0, "#ff0000" ], [0.6, "#f9c802"], [0.7, "#a9d70b"]], // !!!!
  strokeColor: '#E0E0E0',
  generateGradient: true,
  staticLabels: {
  font: "10px sans-serif",  // Specifies font
  labels: [11, 12, 13, 14],  // Print labels at these values
  color: "#ffffff",  // Optional: Label text color
  fractionDigits: 0  // Optional: Numerical precision. 0=round off.
    },
    renderTicks: {
          divisions: 3,
          divWidth: 1.2,
          divLength: 0.7,
          divColor: "#333333",
          subDivisions: 3,
          subLength: 0.5,
          subWidth: 0.6,
          subColor: "#666666",
        },
};

var battery_voltage_gauge_options_light = {
  lines: 12,
  angle: 0.15,
  lineWidth: 0.44,
  pointer: {
    length: 0.6, // // Relative to gauge radius
    strokeWidth: 0.035, // The thickness
    color: '#000000' // Fill color
  },
  limitMax: 'false',
  percentColors: [[0.0, "#ff0000" ], [0.6, "#f9c802"], [0.7, "#a9d70b"]], // !!!!
  strokeColor: '#E0E0E0',
  generateGradient: true,
  staticLabels: {
  font: "10px sans-serif",  // Specifies font
  labels: [11, 12, 13, 14],  // Print labels at these values
  color: "#000000",  // Optional: Label text color
  fractionDigits: 0  // Optional: Numerical precision. 0=round off.
    },
    renderTicks: {
          divisions: 3,
          divWidth: 1.2,
          divLength: 0.7,
          divColor: "#333333",
          subDivisions: 3,
          subLength: 0.5,
          subWidth: 0.6,
          subColor: "#666666",
        },
};

var power_gauge_options_dark = {
  angle: 0.15, // The span of the gauge arc
  lineWidth: 0.44, // The line thickness
  radiusScale: 1, // Relative radius
  pointer: {
    length: 0.6, // // Relative to gauge radius
    strokeWidth: 0.035, // The thickness
    color: '#ffffff' // Fill color
  },
  limitMax: false,     // If false, max value increases automatically if value > maxValue
  limitMin: false,     // If true, the min value of the gauge will be fixed
  percentColors: [[0.0, "#ff0000" ], [0.5, "#f9c802"], [1, "#a9d70b"]], // !!!!
  colorStart: '#6FADCF',   // Colors
  colorStop: '#8FC0DA',    // just experiment with them
  strokeColor: '#E0E0E0',  // to see which ones work best for you
  generateGradient: true,
  highDpiSupport: true,     // High resolution support
  staticLabels: {
  font: "10px sans-serif",  // Specifies font
  labels: [100, 200, 300, 400, 450],  // Print labels at these values
  color: "#ffffff",  // Optional: Label text color
  fractionDigits: 0  // Optional: Numerical precision. 0=round off.
	},
};

var power_gauge_options_light = {
  angle: 0.15, // The span of the gauge arc
  lineWidth: 0.44, // The line thickness
  radiusScale: 1, // Relative radius
  pointer: {
    length: 0.6, // // Relative to gauge radius
    strokeWidth: 0.035, // The thickness
    color: '#000000' // Fill color
  },
  limitMax: false,     // If false, max value increases automatically if value > maxValue
  limitMin: false,     // If true, the min value of the gauge will be fixed
  percentColors: [[0.0, "#ff0000" ], [0.5, "#f9c802"], [1, "#a9d70b"]], // !!!!
  colorStart: '#6FADCF',   // Colors
  colorStop: '#8FC0DA',    // just experiment with them
  strokeColor: '#E0E0E0',  // to see which ones work best for you
  generateGradient: true,
  highDpiSupport: true,     // High resolution support
  staticLabels: {
  font: "10px sans-serif",  // Specifies font
  labels: [100, 200, 300, 400, 450],  // Print labels at these values
  color: "#000000",  // Optional: Label text color
  fractionDigits: 0  // Optional: Numerical precision. 0=round off.
	},
};

var battery_soc_gauge_target = document.getElementById('battery_soc_gauge');
var battery_soc_gauge = new Gauge(battery_soc_gauge_target).setOptions(common_gauge_options_light);
battery_soc_gauge.maxValue = 100; // set max gauge value
battery_soc_gauge.setMinValue(0);  // Prefer setter over gauge.minValue = 0
battery_soc_gauge.setTextField(document.getElementById("battery_soc_value"));
battery_soc_gauge.animationSpeed = 32; // set animation speed (32 is default value)

var starter_battery_voltage_gauge_target = document.getElementById('starter_battery_voltage_gauge');
var starter_battery_voltage_gauge = new Gauge(starter_battery_voltage_gauge_target).setOptions(battery_voltage_gauge_options_dark);
starter_battery_voltage_gauge.maxValue = 14; // set max gauge value
starter_battery_voltage_gauge.setMinValue(11);  // Prefer setter over gauge.minValue = 0
starter_battery_voltage_gauge.setTextField(document.getElementById("starter_battery_voltage_value"));
starter_battery_voltage_gauge.animationSpeed = 32; // set animation speed (32 is default value)

var pv_power_gauge_target = document.getElementById('pv_power_gauge');
var pv_power_gauge = new Gauge(pv_power_gauge_target).setOptions(power_gauge_options_dark);
pv_power_gauge.setMinValue(0);  // Prefer setter over gauge.minValue = 0
pv_power_gauge.setTextField(document.getElementById("pv_power_value"));
pv_power_gauge.animationSpeed = 32; // set animation speed (32 is default value)

var fuel_tank_gauge_target = document.getElementById('fuel_tank_gauge');
var fuel_tank_gauge = new Gauge(fuel_tank_gauge_target).setOptions(common_gauge_options_dark);
fuel_tank_gauge.maxValue = 100; // set max gauge value
fuel_tank_gauge.setMinValue(0);  // Prefer setter over gauge.minValue = 0
fuel_tank_gauge.setTextField(document.getElementById("fuel_tank_value"));
fuel_tank_gauge.animationSpeed = 32; // set animation speed (32 is default value)

var water_tank_gauge_target = document.getElementById('water_tank_gauge');
var water_tank_gauge = new Gauge(water_tank_gauge_target).setOptions(common_gauge_options_dark);
water_tank_gauge.maxValue = 100; // set max gauge value
water_tank_gauge.setMinValue(0);  // Prefer setter over gauge.minValue = 0
water_tank_gauge.setTextField(document.getElementById("water_tank_value"));
water_tank_gauge.animationSpeed = 32; // set animation speed (32 is default value)

// Create the OpenStreetMap layer
const osmLayer = new ol.layer.Tile({
  source: new ol.source.OSM(),
  maxZoom: 19 // Adjust max zoom level as needed
});

// Create the Mapbox Satellite layer
const mapboxSatelliteLayer = new ol.layer.Tile({
    source: new ol.source.OSM ({
        // Set the OSM source to use satellite imagery
        url: 'https://{a-c}.tiles.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token={{anchor_alarm_mapbox_api_key}}',
        maxZoom: 19 // Adjust max zoom level as needed
    })
});


function setAnchorDefaultConfigurationOnChange() {
    document.getElementById('alternative_anchor_configuration_div_id').style.display = 'none';
    document.getElementById('alternative_anchor_configuration_div_id').style.visibility = 'hidden';
    document.getElementById('default_anchor_configuration_div_id').style.display = 'block';
    document.getElementById('default_anchor_configuration_div_id').style.visibility = 'visible';
}

function setAnchorAlternativeConfigurationOnChange() {
    document.getElementById('default_anchor_configuration_div_id').style.display = 'none';
    document.getElementById('default_anchor_configuration_div_id').style.visibility = 'hidden';
    document.getElementById('alternative_anchor_configuration_div_id').style.display = 'block';
    document.getElementById('alternative_anchor_configuration_div_id').style.visibility = 'visible';
}

function useCurrentPosition() {
    // Fill up GPS anchor position on the set anchor dialog from last gps coordinates
    $.ajax({
        type: 'GET',
        url: '/gps_coordinates',
        success: function(data) {
            document.getElementById('set_anchor_alarm_latitude_text_id').value = data['gps_latitude']
            document.getElementById('set_anchor_alarm_longitude_text_id').value = data['gps_longitude'];
        }
    });
}

function dmsToDD(dms) {
    dms = dms.replace('\"', '');
    dms = dms.replace('\'', ' ');
    dms = dms.replace('°', ' ');
    const [degrees, minutes, seconds, hemisphere] = dms.split(' ');
    const dd = parseFloat(degrees) + parseFloat(minutes) / 60 + parseFloat(seconds) / 3600;

    if (hemisphere === 'S' || hemisphere === 'W') {
        return -dd; // For south (S) or west (W) hemispheres
    }

    return dd;
}

function radiusFromValue(value) {
    const earthRadius = 6371000; // Earth's radius in meters
    const circumference = 2 * Math.PI * earthRadius;
    const scale = circumference / 360;

    return (value / scale)
}

function showDefaultMapLayer() {
    anchorMap.removeLayer(mapboxSatelliteLayer);
    anchorMap.addLayer(osmLayer);

    // Disable the default map layer button and enable the satellite button
    document.getElementById('default_map_layer_button').disabled = true;
    document.getElementById("default_map_layer_button").classList.remove('text-light');
    document.getElementById('satellite_map_layer_button').disabled = false;
    document.getElementById("satellite_map_layer_button").classList.add('text-light');


    // redraw map layers
    redrawMapLayers();
}

function showSatelliteMapLayer() {
    anchorMap.removeLayer(osmLayer);
    anchorMap.addLayer(mapboxSatelliteLayer);

    // Disable the satellite button and enable the default button
    document.getElementById('satellite_map_layer_button').disabled = true;
    document.getElementById("satellite_map_layer_button").classList.remove('text-light');
    document.getElementById('default_map_layer_button').disabled = false;
    document.getElementById("default_map_layer_button").classList.add('text-light');

    // redraw map layers
    redrawMapLayers();
}

function zoomIn() {
    // Get the current view from the map
    const view = anchorMap.getView();

    // Get the current zoom level
    currentZoom = view.getZoom();

    // Set the new zoom level for the view
    view.setZoom(currentZoom + 1);
}

function zoomOut() {
    // Get the current view from the map
    const view = anchorMap.getView();

    // Get the current zoom level
    currentZoom = view.getZoom();

    // Set the new zoom level for the view
    view.setZoom(currentZoom - 1);
}

function clearMapLayers() {
    // Get a reference to the map's layers
    const mapLayers = anchorMap.getLayers();

    // Loop through the layers and remove each one
    mapLayers.forEach((layer) => {
        if (layer !== osmLayer && layer !== mapboxSatelliteLayer) {
            anchorMap.removeLayer(layer);
        }
    });
}

function redrawMapLayers() {
    // first clear all map layers except the tile layer
    clearMapLayers();

    // Calculate the anchor circle's geometry taking into consideration the allowed distance
    radiusMeters = radiusFromValue(anchorAllowedDistance);
    circle = new ol.geom.Circle([anchorDecimalLongitude, anchorDecimalLatitude], radiusMeters);

    // Create a feature for the circle
    circleFeature = new ol.Feature({
      geometry: circle,
    });

    // Create a vector source for the circle feature
    vectorSource = new ol.source.Vector({
      features: [circleFeature],
    });

    // Create a vector layer for the circle
    vectorLayer = new ol.layer.Vector({
      source: vectorSource,
      style: new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: 'red', // Circle border color
          width: 1, // Border width
        }),
        fill: new ol.style.Fill({
          color: 'rgba(0, 0, 255, 0.1)', // Circle fill color with transparency
        })
      })
    });

    // Add the circle layer to the map
    anchorMap.addLayer(vectorLayer);

    // draw position history markers if provided
    if (anchorPositionHistory && anchorPositionHistory.length > 0) {
        // Create a vector source for the position dots feature
        positionHistoryVectorSource = new ol.source.Vector();

        // Create a style for the dots (points)
        positionHistoryDotStyle = new ol.style.Style({
          image: new ol.style.Circle({
            radius: 5, // Adjust the size of the dots as needed
            fill: new ol.style.Fill({ color: 'yellow' }), // Dot color
            stroke: new ol.style.Stroke({ color: 'black', width: 1 }), // Dot border color
          }),
        });

        // Create a vector layer and add features (points) to it
        positionHistoryVectorLayer = new ol.layer.Vector({
          source: positionHistoryVectorSource,
          style: positionHistoryDotStyle,
        });

        for (let i = 0; i < anchorPositionHistory.length; i++) {
            relevantPositionLatitude = anchorPositionHistory[i][0];
            relevantPositionLongitude = anchorPositionHistory[i][1];
            decimalLon = dmsToDD(relevantPositionLongitude);
            decimalLat = dmsToDD(relevantPositionLatitude);

            const point = new ol.Feature({
                geometry: new ol.geom.Point([decimalLon, decimalLat]),
            });
            positionHistoryVectorSource.addFeature(point);

            lastPositionLatitude = relevantPositionLatitude;
            lastPositionLongitude = relevantPositionLongitude;
        }

        // Add the dots layer to the map
        anchorMap.addLayer(positionHistoryVectorLayer);
    }
}

function drawAnchorOnMap(latitude, longitude, allowed_distance, position_history) {
    divContainer = document.getElementById('anchor-map'); // Replace 'yourDivId' with the actual ID of your div
    // Empty the div by setting its innerHTML to an empty string
    divContainer.innerHTML = '';

    // re-initialize the anchor map
    anchorMap = new ol.Map({
        layers: [osmLayer],
        target: 'anchor-map',
        controls: []
    });

    {% if anchor_alarm_mapbox_api_key | length > 0 %}

    {% else %}
    document.getElementById('satellite_map_layer_button').disabled = true;
    document.getElementById("satellite_map_layer_button").classList.remove('text-light');
    {% endif %}

    decimalLat = dmsToDD(latitude);
    decimalLon = dmsToDD(longitude)

    anchorDecimalLatitude = decimalLat;
    anchorDecimalLongitude = decimalLon;

    anchorView = new ol.View({
        projection: 'EPSG:4326',
        center: [decimalLon, decimalLat],
        zoom: 8,
    });

    anchorMap.setView(anchorView);

    anchorMarker = new ol.Overlay({
      position: [decimalLon, decimalLat], // Convert GPS coordinates to map coordinates
      positioning: 'center-center',
      element: document.createElement('div')
    });
    anchorMarker.getElement().className = 'anchor-marker'; // Apply CSS class for styling
    anchorMap.addOverlay(anchorMarker);

    anchorAllowedDistance = allowed_distance;
    anchorPositionHistory = position_history;

    redrawMapLayers();

    // Set the center coordinate to the target coordinate and apply the zoom animation
    anchorView.animate({
      center: [decimalLon, decimalLat],
      zoom: 18, // Adjust the zoom level as needed
      duration: 4000,
      easing: ol.easing.easeOut, // Use a suitable easing function
    });
}

function isValidGPSCoordinate(value) {
    // Regular expression for matching valid GPS coordinates
    // The pattern allows for degrees (0-90) and minutes/seconds (0-59), with the hemisphere at the end (N, S, E, or W)
    const regex = /^(-?\d{1,3})°(\d{1,2})'((\d{1,2}(\.\d*)?)|(\.\d+))" [NSEW]$/;

    return regex.test(value);
}

function setAnchor() {
    // validate the form before proceeding any further
    if (document.getElementById("default_anchor_configuration_button_id").checked) {
        if (!isValidGPSCoordinate(document.getElementById("set_anchor_alarm_latitude_text_id").value) ||
            !isValidGPSCoordinate(document.getElementById("set_anchor_alarm_longitude_text_id").value) ||
            parseInt(document.getElementById("set_anchor_alarm_allowed_distance_text_id").value) <= 0) {
            document.getElementById('set_anchor_check_your_input_div_id').style.display = 'block';
            document.getElementById('set_anchor_check_your_input_div_id').style.visibility = 'visible';
            return;
        }
        else {
            document.getElementById('set_anchor_check_your_input_div_id').style.display = 'none';
            document.getElementById('set_anchor_check_your_input_div_id').style.visibility = 'hidden';
        }
    }
    else {
        if (parseInt(document.getElementById("set_anchor_alarm_bearing_text_id").value) > 359 ||
            parseInt(document.getElementById("set_anchor_alarm_bearing_text_id").value) < 0 ||
            parseInt(document.getElementById("set_anchor_alarm_distance_text_id").value) < 0 ||
            parseInt(document.getElementById("set_anchor_alarm_allowed_distance_text_id").value) <= 0) {
            document.getElementById('set_anchor_check_your_input_div_id').style.display = 'block';
            document.getElementById('set_anchor_check_your_input_div_id').style.visibility = 'visible';
            return;
        }
        else {
            document.getElementById('set_anchor_check_your_input_div_id').style.display = 'none';
            document.getElementById('set_anchor_check_your_input_div_id').style.visibility = 'hidden';
        }
    }

    hideSetAnchorAlarmModal();
    $('#loading_modal').modal('show');

    if (document.getElementById("default_anchor_configuration_button_id").checked) {
        $.ajax({
            url: '/set_anchor',
            method: 'POST',
            data: { latitude: document.getElementById("set_anchor_alarm_latitude_text_id").value,
                    longitude: document.getElementById("set_anchor_alarm_longitude_text_id").value,
                    allowed_distance: document.getElementById("set_anchor_alarm_allowed_distance_text_id").value },
            success: function (response) {
                $('#loading_modal').modal('hide');
                if (!response)
                    notify_warning('Error while setting anchor alarm! Please check your anchor configuration');
                else {
                    notify_success('Anchor alarm successfully set!');

                    // draw the anchor position and allowed distance radius on the map
                    latitude = document.getElementById("set_anchor_alarm_latitude_text_id").value;
                    longitude = document.getElementById("set_anchor_alarm_longitude_text_id").value;
                    allowed_distance = parseInt(document.getElementById("set_anchor_alarm_allowed_distance_text_id").value);

                    // switch to the anchor tab
                    var anchorTab = new bootstrap.Tab(document.getElementById("anchor-tab"));
                    anchorTab.show();

                    // show the default map layer
                    showDefaultMapLayer();

                    // draw anchor on map
                    drawAnchorOnMap(latitude, longitude, allowed_distance, undefined);
                }
            },
            error: function (error) {
                $('#loading_modal').modal('hide');
                notify_warning('Error while setting anchor alarm! Please check your anchor configuration');
            }
        });
    }
    else {
        current_latitude = ''
        current_longitude = ''
        $.ajax({
            type: 'GET',
            url: '/gps_coordinates',
            async: false, // Synchronous request
            success: function(data) {
                current_latitude = data['gps_latitude']
                current_longitude = data['gps_longitude'];
            }
        });

        $.ajax({
            url: '/set_anchor_alternative',
            method: 'POST',
            data: { latitude: current_latitude,
                    longitude: current_longitude,
                    bearing: document.getElementById("set_anchor_alarm_bearing_text_id").value,
                    distance: document.getElementById("set_anchor_alarm_distance_text_id").value,
                    allowed_distance: document.getElementById("set_anchor_alarm_allowed_distance_text_id").value },
            success: function (response) {
                $('#loading_modal').modal('hide');
                if (!response)
                    notify_warning('Error while setting anchor alarm! Please check your anchor configuration');
                else {
                    notify_success('Anchor alarm successfully set!');

                    // draw the anchor position and allowed distance radius on the map
                    latitude = document.getElementById("set_anchor_alarm_latitude_text_id").value;
                    longitude = document.getElementById("set_anchor_alarm_longitude_text_id").value;
                    allowed_distance = parseInt(document.getElementById("set_anchor_alarm_allowed_distance_text_id").value);

                    // switch to the anchor tab
                    var anchorTab = new bootstrap.Tab(document.getElementById("anchor-tab"));
                    anchorTab.show();

                    // show the default map layer
                    showDefaultMapLayer();

                    // draw anchor on map
                    drawAnchorOnMap(latitude, longitude, allowed_distance, undefined);
                }
            },
            error: function (error) {
                $('#loading_modal').modal('hide');
                notify_warning('Error while setting anchor alarm! Please check your anchor configuration');
            }
        });
    }
}

function updateAnchor() {
    // validate the form before proceeding any further
    if (parseInt(document.getElementById("update_anchor_alarm_allowed_distance_text_id").value) <= 0) {
        document.getElementById('update_anchor_check_your_input_div_id').style.display = 'block';
        document.getElementById('update_anchor_check_your_input_div_id').style.visibility = 'visible';
        return;
    }
    else {
        document.getElementById('update_anchor_check_your_input_div_id').style.display = 'none';
        document.getElementById('update_anchor_check_your_input_div_id').style.visibility = 'hidden';
    }

    hideUpdateAnchorAlarmModal();
    $('#loading_modal').modal('show');

    $.ajax({
        url: '/set_anchor',
        method: 'POST',
        data: { latitude: document.getElementById("update_anchor_alarm_latitude_label_id").innerHTML,
                longitude: document.getElementById("update_anchor_alarm_longitude_label_id").innerHTML,
                allowed_distance: document.getElementById("update_anchor_alarm_allowed_distance_text_id").value },
        success: function (response) {
            $('#loading_modal').modal('hide');
            if (!response)
                notify_warning('Error while updating anchor alarm! Please check your anchor configuration');
            else {
                notify_success('Anchor alarm successfully updated!');

                // draw the anchor position and allowed distance radius on the map
                latitude = document.getElementById("update_anchor_alarm_latitude_label_id").innerHTML;
                longitude = document.getElementById("update_anchor_alarm_longitude_label_id").innerHTML;
                allowed_distance = parseInt(document.getElementById("update_anchor_alarm_allowed_distance_text_id").value);

                // switch to the anchor tab
                var anchorTab = new bootstrap.Tab(document.getElementById("anchor-tab"));
                anchorTab.show();

                // show the default map layer
                showDefaultMapLayer();

                // draw anchor on map
                drawAnchorOnMap(latitude, longitude, allowed_distance, undefined);
            }
        },
        error: function (error) {
            $('#loading_modal').modal('hide');
            notify_warning('Error while updating anchor alarm! Reason: ' + error);
        }
    });
}

function cancelAnchor() {
    hideCancelAnchorAlarmModal();
    hideSetAnchorAlarmModal();

    $.ajax({
        type: 'GET',
        url: '/cancel_anchor',
        success: function(data) {
            notify_success('Anchor alarm successfully canceled!');
        },
        error: function (error) {
            notify_warning('Error while canceling the anchor alarm! Reason: ' + error);
        }
    });
}

function toggleSession() {
    $.ajax({
        type: 'GET',
        url: '/toggle_session',
        success: function(data) {
            // switch to the session tab
            var sessionTab = new bootstrap.Tab(document.getElementById("session-tab"));
            sessionTab.show();
        }
    });
}

function showSetAnchorAlarmModal() {
    $('#loading_modal').modal('show');

    $.ajax({
        type: 'GET',
        url: '/anchor_alarm_data',
        success: function(data) {
            $('#loading_modal').modal('hide');
            document.getElementById('set_anchor_alarm_allowed_distance_text_id').value = data['anchor_alarm_default_allowed_distance'];

            // Fill up GPS anchor position from last gps coordinates
            $.ajax({
                type: 'GET',
                url: '/gps_coordinates',
                async: false, // Synchronous request
                success: function(data) {
                    document.getElementById('set_anchor_alarm_latitude_text_id').value = data['gps_latitude']
                    document.getElementById('set_anchor_alarm_longitude_text_id').value = data['gps_longitude'];
                }
            });

            // hide the check your input warning message
            document.getElementById('set_anchor_check_your_input_div_id').style.display = 'none';
            document.getElementById('set_anchor_check_your_input_div_id').style.visibility = 'hidden';

            setAnchorAlarmModal.show();
        },
        error: function (error) {
            $('#loading_modal').modal('hide');
            notify_warning('Error while retrieving anchor alarm configuration! Reason: ' + error);
        }
    });
}

function showUpdateAnchorAlarmModal() {
    $('#loading_modal').modal('show');

    $.ajax({
        type: 'GET',
        url: '/anchor_alarm_data',
        success: function(data) {
            $('#loading_modal').modal('hide');
            document.getElementById('update_anchor_alarm_allowed_distance_text_id').value = data['anchor_allowed_distance'];
            document.getElementById('update_anchor_alarm_latitude_label_id').innerHTML = data['anchor_latitude']
            document.getElementById('update_anchor_alarm_longitude_label_id').innerHTML = data['anchor_longitude'];
            document.getElementById('update_anchor_alarm_current_latitude_label_id').innerHTML = data['current_latitude']
            document.getElementById('update_anchor_alarm_current_longitude_label_id').innerHTML = data['current_longitude'];
            document.getElementById('update_anchor_alarm_distance_from_anchor_label_id').innerHTML = data['anchor_distance']

            if (data['anchor_distance'] > data['anchor_allowed_distance']) {
                document.getElementById("update_anchor_alarm_distance_from_anchor_div_id").classList.remove('text-success');
                document.getElementById("update_anchor_alarm_distance_from_anchor_div_id").classList.add('text-danger');
            }
            else {
                document.getElementById("update_anchor_alarm_distance_from_anchor_div_id").classList.remove('text-danger');
                document.getElementById("update_anchor_alarm_distance_from_anchor_div_id").classList.add('text-success');
            }

            // hide the check your input warning message
            document.getElementById('update_anchor_check_your_input_div_id').style.display = 'none';
            document.getElementById('update_anchor_check_your_input_div_id').style.visibility = 'hidden';

            updateAnchorAlarmModal.show();
        },
        error: function (error) {
            $('#loading_modal').modal('hide');
            notify_warning('Error while retrieving anchor alarm configuration! Reason: ' + error);
        }
    });
}

function hideUpdateAnchorAlarmModal() {
    updateAnchorAlarmModal.hide();
}

function hideSetAnchorAlarmModal() {
    setAnchorAlarmModal.hide();
}

function showCancelAnchorAlarmModal() {
    cancelAnchorAlarmModal.show();
}

function hideCancelAnchorAlarmModal() {
    cancelAnchorAlarmModal.hide();
}

function cancelAnchorAlarm() {
    hideCancelAnchorAlarmModal();
    hideUpdateAnchorAlarmModal();

    $('#loading_modal').modal('show');

    $.ajax({
        type: 'GET',
        url: '/cancel_anchor',
        success: function(data) {
            $('#loading_modal').modal('hide');
            notify_success('Anchor alarm successfully canceled!');
        },
        error: function (error) {
            $('#loading_modal').modal('hide');
            notify_warning('Error while trying to cancel the anchor alarm! Reason: ' + error);
        }
    });
}

function switch_to_light_mode() {
    document.getElementById("set_anchor_alarm_modal_content").classList.remove('bg-dark');
    document.getElementById("update_anchor_alarm_modal_content").classList.remove('bg-dark');
    document.getElementById("cancel_anchor_alarm_modal_content").classList.remove('bg-dark');
    document.getElementById("body-element-id").classList.add('text-dark');
    document.getElementById("body-element-id").classList.remove('bg-dark');
    document.getElementById("body-element-id").classList.remove('text-light');
    document.getElementById("navbar-element-id").classList.remove('bg-dark');
    document.getElementById("navbar-element-id").classList.add('bg-primary');
    document.getElementById("summary-box-id").classList.add('border-dark');
    document.getElementById("summary-box-id").classList.remove('border-light');
    battery_soc_gauge.setOptions(common_gauge_options_light);
    starter_battery_voltage_gauge.setOptions(battery_voltage_gauge_options_light);
    pv_power_gauge.setOptions(power_gauge_options_light);
    fuel_tank_gauge.setOptions(common_gauge_options_light);
    water_tank_gauge.setOptions(common_gauge_options_light);
}

function switch_to_dark_mode() {
    document.getElementById("set_anchor_alarm_modal_content").classList.add('bg-dark');
    document.getElementById("update_anchor_alarm_modal_content").classList.add('bg-dark');
    document.getElementById("cancel_anchor_alarm_modal_content").classList.add('bg-dark');
    document.getElementById("body-element-id").classList.add('bg-dark');
    document.getElementById("body-element-id").classList.add('text-light');
    document.getElementById("body-element-id").classList.remove('text-dark');
    document.getElementById("navbar-element-id").classList.remove('bg-primary');
    document.getElementById("navbar-element-id").classList.add('bg-dark');
    document.getElementById("summary-box-id").classList.add('border-light');
    document.getElementById("summary-box-id").classList.remove('border-dark');
    battery_soc_gauge.setOptions(common_gauge_options_dark);
    starter_battery_voltage_gauge.setOptions(battery_voltage_gauge_options_dark);
    pv_power_gauge.setOptions(power_gauge_options_dark);
    fuel_tank_gauge.setOptions(common_gauge_options_dark);
    water_tank_gauge.setOptions(common_gauge_options_dark);
}

// Function to format minutes into "%d days %h hours %m minutes"
function formatMinutes(minutes) {
    const days = Math.floor(minutes / (24 * 60));
    const hours = Math.floor((minutes % (24 * 60)) / 60);
    const remainingMinutes = minutes % 60;

    return `${days} days ${hours} hours ${remainingMinutes} minutes`;
}

function refreshData() {
    $.ajax({
        type: 'GET',
        url: '/data',
        success: function(data) {
            // Update the relevant part of the webpage with the new data
            if (data['web_theme'] == 'auto') {
                if (data['day_light']) {
                    switch_to_light_mode();
                }
                else {
                    switch_to_dark_mode();
                }
            } else if (data['web_theme'] == 'light') {
                    switch_to_light_mode();
            } else if (data['web_theme'] == 'dark') {
                    switch_to_dark_mode();
            }

            if (data['last_notification'] != '') {
                if (data['last_notification'].toLowerCase().includes('cleared')) {
                    notify_success(data['last_notification'])
                } else {
                    notify_warning(data['last_notification']);
                }
            }

            if (data['victron_module']) {
                battery_soc_gauge.set(data['battery_soc']);
                document.getElementById('battery_soc_value').innerHTML = data['battery_soc'];
                starter_battery_voltage_gauge.set(data['starter_battery_voltage']);
                document.getElementById('starter_battery_voltage_value').innerHTML = data['starter_battery_voltage'];
                pv_power_gauge.maxValue = data['pv_max_configured_power']
                pv_power_gauge.set(data['pv_power']);
                document.getElementById('pv_power_value').innerHTML = data['pv_power'];
                fuel_tank_gauge.set(data['fuel_tank']);
                document.getElementById('fuel_tank_value').innerHTML = data['fuel_tank'];
                water_tank_gauge.set(data['water_tank']);
                document.getElementById('water_tank_value').innerHTML = data['water_tank'];
                document.getElementById('active_input_source_value').innerHTML = data['active_input_source'];
                document.getElementById('ve_bus_state_value').innerHTML = data['ve_bus_state'];
                document.getElementById('housing_battery_state_value').innerHTML = data['housing_battery_state'];
                document.getElementById('housing_battery_current_value').innerHTML = data['housing_battery_current'];
                document.getElementById('pv_current_value').innerHTML = data['pv_current'];
                document.getElementById('victron_module_status').innerHTML = data['victron_status'];
                if (data['victron_status'] == "Running") {
                    document.getElementById("victron_module_spinner").className = "spinner-border text-success me-2";
                } else if (data['victron_status'] == "Down") {
                    document.getElementById("victron_module_spinner").className = "spinner-grow text-danger me-2";
                } else if (data['victron_status'] == "Starting") {
                    document.getElementById("victron_module_spinner").className = "spinner-grow text-warning me-2";
                }
            } else {
                document.getElementById('victron_module_status').innerHTML = "Disabled";
                document.getElementById("victron_module_spinner").className = "spinner-grow text-secondary me-2";
            }

            if (data['nmea_module']) {
                document.getElementById('nmea_module_status').innerHTML = data['nmea_status'];
                if (data['nmea_status'] == "Running") {
                    document.getElementById("nmea_module_spinner").className = "spinner-border text-success me-2";
                } else if (data['nmea_status'] == "Down") {
                    document.getElementById("nmea_module_spinner").className = "spinner-grow text-danger me-2";
                } else if (data['nmea_status'] == "Starting") {
                    document.getElementById("nmea_module_spinner").className = "spinner-grow text-warning me-2";
                }
            } else {
                document.getElementById('nmea_module_status').innerHTML = "Disabled";
                document.getElementById("nmea_module_spinner").className = "spinner-grow text-secondary me-2";
            }

            if (data['gps_module']) {
                document.getElementById('gps_module_status').innerHTML = data['gps_status'];
                if (data['gps_status'] == "Running") {
                    document.getElementById("gps_module_spinner").className = "spinner-border text-success me-2";
                } else if (data['gps_status'] == "Down") {
                    document.getElementById("gps_module_spinner").className = "spinner-grow text-danger me-2";
                } else if (data['gps_status'] == "Starting") {
                    document.getElementById("gps_module_spinner").className = "spinner-grow text-warning me-2";
                }
            } else {
                document.getElementById('gps_module_status').innerHTML = "Disabled";
                document.getElementById("gps_module_spinner").className = "spinner-grow text-secondary me-2";
            }

            if (data['status'] === "idle") {
                if (document.getElementById("session_button_id").classList.contains('btn-danger'))
                {
                    document.getElementById('session_button_text').innerHTML = "Start Session";
                    document.getElementById("session_button_id").classList.remove('btn-danger');
                    document.getElementById("session_button_id").classList.add('btn-success');
                    document.getElementById('session_button_spinner').style.display = 'none';
                    document.getElementById('session_button_spinner').style.visibility = 'hidden';
                }

                document.getElementById('session_container').style.display = 'none';
                document.getElementById('session_container').style.visibility = 'hidden';
                document.getElementById('no_session_message').style.display = 'block';
                document.getElementById('no_session_message').style.visibility = 'visible';
                document.getElementById('session_name').innerHTML = "Session name";
            }
            else
            {
                if (document.getElementById("session_button_id").classList.contains('btn-success'))
                {
                    document.getElementById('session_button_text').innerHTML = "End Session";
                    document.getElementById("session_button_id").classList.remove('btn-success');
                    document.getElementById("session_button_id").classList.add('btn-danger');
                    document.getElementById('session_button_spinner').style.display = 'inline-block';
                    document.getElementById('session_button_spinner').style.visibility = 'visible';
                }
                document.getElementById('no_session_message').style.display = 'none';
                document.getElementById('no_session_message').style.visibility = 'hidden';
                document.getElementById('session_container').style.display = 'block';
                document.getElementById('session_container').style.visibility = 'visible';
                document.getElementById('session_name').innerHTML = data['session_name'];
                document.getElementById('start_time').innerHTML = data['start_time'];
                document.getElementById('start_time_utc').innerHTML = data['start_time_utc'];
                document.getElementById('duration').innerHTML = data['duration'];
                document.getElementById('start_gps_lat').innerHTML = data['start_gps_lat'];
                document.getElementById('start_gps_lon').innerHTML = data['start_gps_lon'];
                document.getElementById('distance').innerHTML = data['distance'];
                document.getElementById('heading').innerHTML = data['heading'];
                document.getElementById('average_wind_speed').innerHTML = data['average_wind_speed'];
                document.getElementById('average_wind_direction').innerHTML = data['average_wind_direction'];
                document.getElementById('average_water_temperature').innerHTML = data['average_water_temperature'];
                document.getElementById('average_depth').innerHTML = data['average_depth'];
                document.getElementById('average_sog').innerHTML = data['average_sog'];
                document.getElementById('average_sow').innerHTML = data['average_sow'];
                document.getElementById('housing_battery_max_voltage').innerHTML = data['housing_battery_max_voltage'];
                document.getElementById('housing_battery_min_voltage').innerHTML = data['housing_battery_min_voltage'];
                document.getElementById('housing_battery_avg_voltage').innerHTML = data['housing_battery_avg_voltage'];
                document.getElementById('housing_battery_max_current').innerHTML = data['housing_battery_max_current'];
                document.getElementById('housing_battery_avg_current').innerHTML = data['housing_battery_avg_current'];
                document.getElementById('housing_battery_max_power').innerHTML = data['housing_battery_max_power'];
                document.getElementById('housing_battery_avg_power').innerHTML = data['housing_battery_avg_power'];
                document.getElementById('pv_max_power').innerHTML = data['pv_max_power'];
                document.getElementById('pv_avg_power').innerHTML = data['pv_avg_power'];
                document.getElementById('pv_max_current').innerHTML = data['pv_max_current'];
                document.getElementById('pv_avg_current').innerHTML = data['pv_avg_current'];
                document.getElementById('starter_battery_max_voltage').innerHTML = data['starter_battery_max_voltage'];
                document.getElementById('starter_battery_min_voltage').innerHTML = data['starter_battery_min_voltage'];
                document.getElementById('starter_battery_avg_voltage').innerHTML = data['starter_battery_avg_voltage'];
                document.getElementById('tank1_max_level').innerHTML = data['tank1_max_level'];
                document.getElementById('tank1_min_level').innerHTML = data['tank1_min_level'];
                document.getElementById('tank1_avg_level').innerHTML = data['tank1_avg_level'];
                document.getElementById('tank2_max_level').innerHTML = data['tank2_max_level'];
                document.getElementById('tank2_min_level').innerHTML = data['tank2_min_level'];
                document.getElementById('tank2_avg_level').innerHTML = data['tank2_avg_level'];
            }

            // Refresh anchor data if anchor alarm is active
            $.ajax({
                type: 'GET',
                url: '/anchor_alarm_data',
                async: false, // Synchronous request
                success: function(data) {
                    if (data['anchor_alarm_module'] && data['anchor_is_set']) {
                        if (first_refresh_data_call) {
                            drawAnchorOnMap(data['anchor_latitude'], data['anchor_longitude'], data['anchor_allowed_distance'], data['position_history']);
                        }

                        document.getElementById('anchor_alarm_is_not_set_message').style.display = 'none';
                        document.getElementById('anchor_alarm_is_not_set_message').style.visibility = 'hidden';
                        document.getElementById('anchor_container').style.display = 'block';
                        document.getElementById('anchor_container').style.visibility = 'visible';
                        document.getElementById('anchor_latitude').innerHTML = data['anchor_latitude'];
                        document.getElementById('anchor_longitude').innerHTML = data['anchor_longitude'];
                        document.getElementById('anchor_start_time').innerHTML = data['anchor_timestamp_local'];
                        document.getElementById('anchor_start_time_utc').innerHTML = data['anchor_timestamp_utc'];
                        document.getElementById('current_latitude').innerHTML = data['current_latitude'];
                        document.getElementById('current_longitude').innerHTML = data['current_longitude'];
                        document.getElementById('anchor_distance').innerHTML = data['anchor_distance'];
                        document.getElementById('anchor_allowed_distance').innerHTML = data['anchor_allowed_distance'];
                        document.getElementById('anchor_duration').innerHTML = formatMinutes(Math.round(data['anchor_duration_in_seconds'] / 60));
                        document.getElementById('anchor_bearing').innerHTML = data['anchor_bearing'];
                        document.getElementById('gps_accuracy').innerHTML = data['gps_accuracy'];

                        if (data['anchor_distance'] > data['anchor_allowed_distance']) {
                            document.getElementById("distance_from_anchor_span").classList.remove('text-success');
                            document.getElementById("distance_from_anchor_span").classList.add('text-danger');
                        }
                        else {
                            document.getElementById("distance_from_anchor_span").classList.remove('text-danger');
                            document.getElementById("distance_from_anchor_span").classList.add('text-success');
                        }

                        // draw relevant boat positions on the map
                        if (data['position_history'] && data['position_history'].length > 0) {
                            anchorPositionHistory = data['position_history'];
                            redrawMapLayers();
                        }

                        // Draw the boat marker on the map for the current boat position
                        if (boatMarker)
                            anchorMap.removeOverlay(boatMarker);

                        decimalLon = dmsToDD(data['current_longitude']);
                        decimalLat = dmsToDD(data['current_latitude']);
                        boatMarker = new ol.Overlay({
                          position: [decimalLon, decimalLat], // Convert GPS coordinates to map coordinates
                          positioning: 'center-center',
                          element: document.createElement('div')
                        });
                        boatMarker.getElement().className = 'boat-marker'; // Apply CSS class for styling
                        anchorMap.addOverlay(boatMarker);

                        if (document.getElementById('track_current_position_checkbox').checked) {
                            // recenter the map to the latest boat position
                            anchorMap.getView().setCenter([decimalLon, decimalLat]);
                        }
                    }
                    else {
                        document.getElementById('anchor_container').style.display = 'none';
                        document.getElementById('anchor_container').style.visibility = 'hidden';
                        document.getElementById('anchor_alarm_is_not_set_message').style.display = 'block';
                        document.getElementById('anchor_alarm_is_not_set_message').style.visibility = 'visible';
                    }
                },
                error: function (error) {
                    notify_warning('Error while retrieving anchor alarm configuration! Reason: ' + error);
                }
            });

            if (first_refresh_data_call) {
                $('#loading_modal').modal('hide');
                first_refresh_data_call = false;
            }
        },
        error: function (error) {
            if (first_refresh_data_call) {
                $('#loading_modal').modal('hide');
                first_refresh_data_call = false;
            }

            if (!connection_lost_dialog_shown) {
                notify_warning('Error refreshing data: ' + error);
            }
        }
    });
}

$(document).ready(function() {
    $('#loading_modal').modal('show');
    // Call the refreshData function every 1 seconds
    setInterval(refreshData, 1000);
});

function notify_success(message) {
    $('#success_notification_message').html(message);
    $("#success_notification").fadeIn();
    setTimeout(function () {
        $("#success_notification").fadeOut();
    }, 5000);
}

function notify_warning(message) {
    $('#warning_notification_message').html(message);
    $("#warning_notification").fadeIn();
    setTimeout(function () {
        $("#warning_notification").fadeOut();
    }, 5000);
}













</script>

{% endblock %}