$( document ).ready(function() {

    // Timepicker plugin init
    $('.timepicker').timepicker({
        showMeridian: false,
        showInputs: false,
    });

    // Stations listing using datatables plugin
    $('#route-list').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": base_url + "/stations/list_data",
            "type": "POST"
        },
        "order": [[ 0, "asc" ]]
    });

    // Pick from map icon click event
    $(document).on('click', '.pick-map', function (event) {
        event.preventDefault();
        $('#map-picker').modal('show');
    });

    $('#map-picker').on('shown.bs.modal', function () {
        var initLatLng;

        if ($('input[name="page_type"]').val() == 'edit') {
            initLatLng = new google.maps.LatLng($('input[name="station_lat"]').val(), $('input[name="station_lng"]').val());
            console.log(initLatLng);
            load_map(initLatLng);
        } else {
            // Sets users current location if geolocation is supported in the browser
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    initLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                    load_map(initLatLng);
                });
            } else {
                initLatLng = new google.maps.LatLng(31.8360368, 35.6674396);
                load_map(initLatLng);
            }
        }

    });

    // Loads google map
    function load_map(initLatLng) {
        var map = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 7,
            center: initLatLng,
        });

        var myMarker = new google.maps.Marker({
            position: initLatLng,
            draggable: true
        });

        var latitude = document.getElementById('pick-lat');
        var longitude = document.getElementById('pick-lng');

        google.maps.event.addListener(myMarker, 'dragend', function (evt) {
            document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
            latitude.value = evt.latLng.lat().toFixed(3);
            longitude.value = evt.latLng.lng().toFixed(3);
        });

        google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
            document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
        });

        map.setCenter(myMarker.position);
        myMarker.setMap(map);
    }

    // Map 'Select Location' modal 'select route' click event
    $(document).on('click', '.select-route', function (e) {
        e.preventDefault();
        $('input[name="station_lat"]').val($('#pick-lat').val());
        $('input[name="station_lng"]').val($('#pick-lng').val());
        $('#map-picker').modal('hide');
    })
});