let map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 3.397,
      lng: 10.644
    },
    zoom: 3
  });
}

let loaded_data = new Array();

function showTranspModal(service_request_id) {
  if (typeof event !== 'undefined') {
    event.preventDefault();
  }
  //  alert(service_request_id);
  // collect data - either from forms or from data variables
  let id = $(this).data('id');

  // load the modal content with a loader gif and message
  $('#modal-content').html('Loading...');
  msg //alert(6);
  $.ajax({
    url: "/transp/transp_modal?service_request_id=" + service_request_id
  }).done(function(data) {
    //alert(data);
    //alert(7);
    $('#modal-content').html(data);
    //initialize_map();
    let myLatlng = new google.maps.LatLng(33.7489954, -84.3879824);
    let myOptions = {
      zoom: 13,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsDiv"));

    fitMapToBounds_map();

    calcRoute(loaded_data[0], loaded_data[1]);
    //alert(loaded_data[0]);
  });
}

function plotMarkers(locations) {
  let n = parseInt('' + locations.length / 2, 10) - 1;
  if (n < 0) n = 0;
  let map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: new google.maps.LatLng(locations[n].lat, locations[0].lng),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  let flightPath = new google.maps.Polyline({
    path: locations,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 4
  });
  flightPath.setMap(map);
}

function viewTracked(traked_group, page_no, render = false) {
  $('#member_tracking_form').find('#traked_group').val(traked_group);

  if (render) {
    $('#trackgroup_list').html('Processing...');
    $('#acc' + traked_group).prop('disabled', true);
  }

  let filters = {
    'traked_group': traked_group
  }

  $.ajax({
    url: '/member/viewtrackedgroup',
    type: 'post',
    dataType: 'json',
    data: {
      'row_no': page_no,
      'proc': 'PROCESS',
      'filters': filters
    },
    success: function(data) {
      $('#pagination-member-tracking').html(data.pagination);
      createMemberTrackingTable(data.result);
      if (render) {
        plotMarkers(data.locations);
        $('#acc' + traked_group).prop('disabled', false);
      }
    },
    complete: function() {

    }
  });

  return false;
}

function createMemberTrackingTable(result) {

  $('#member-tracking-list tbody').empty();

  for (index in result) {
    let id = result[index].id;
    let member_id = result[index].member_id;
    let tracked_group = result[index].traked_group;
    let speed = result[index].speed;
    let lat = result[index].lat;
    let lng = result[index].lng;
    let gps = result[index].gps;
    let ttime = result[index].ttime;
    let loc = result[index].loc;
    let dev_id = result[index].device_id;
    let prev_id = result[index].previous_id;
    let dis = result[index].distance;
    let dur = result[index].duration;

    let tr =
      `<tr>
      <td>${id}</td>
      <td>${member_id}</td>
      <td>${tracked_group}</td>
      <td>${speed}</td>
      <td>${lat}</td>
      <td>${lng}</td>
      <td>${gps}</td>
      <td>${ttime}</td>
      <td>${loc}</td>
      <td>${dev_id}</td>
      <td>${prev_id}</td>
      <td>${dis}</td>
      <td>${dur}</td>
    </tr>`;

    $('#member-tracking-list tbody').append(tr);
  }
}

$(document).ready(() => {
  // Datepicker
  $( "#traked_group_form #start_date" ).datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    format: 'yyyy-mm-dd',
    onClose: function( selectedDate ) {
      $( "#traked_group_form #start_date" ).datepicker( "option", "minDate", selectedDate );
    }
  });

  $( "#traked_group_form #end_date" ).datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    format: 'yyyy-mm-dd',
    onClose: function( selectedDate ) {
      $( "#traked_group_form #end_date" ).datepicker( "option", "maxDate", selectedDate );
    }
  });

  $( "#member_tracking_form #start_date" ).datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    format: 'yyyy-mm-dd',
    onClose: function( selectedDate ) {
      $( "#member_tracking_form #start_date" ).datepicker( "option", "minDate", selectedDate );
    }
  });

  $( "#member_tracking_form #end_date" ).datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    format: 'yyyy-mm-dd',
    onClose: function( selectedDate ) {
      $( "#member_tracking_form #end_date" ).datepicker( "option", "maxDate", selectedDate );
    }
  });

  $('#export_csv').click(function() {
    window.open("/member/export_member_tracking",'_blank');
  })

  $('#search').click(function() {
    let form = $('#traked_group_form');

    let filters = {
      'start_date': form.find('#start_date').val(),
      'end_date': form.find('#end_date').val(),
      'member_id':form.find('#member_id').val(),
    };
    let pageno = $(this).attr('data-ci-pagination-page');
    
    loadTrackedGroupRecord(pageno, filters, $(this));
  })

  // Detect pagination click
  $('#pagination_tracked_group').on('click', 'a', function(e) {
    e.preventDefault();

    let form = $('#traked_group_form');
    let pageno = $(this).attr('data-ci-pagination-page');
    let filters = {
      'start_date': form.find('#start_date').val(),
      'end_date': form.find('#end_date').val(),
      'member_id':form.find('#member_id').val(),
    };

    loadTrackedGroupRecord(pageno, filters);
  });

  // Prevent submit form by press the enter button
  $(window).keydown(function(event) {
    if (event.keyCode == 13) {
      event.preventDefault();

      let form = $('#traked_group_form');
      let filters = {
        'start_date': form.find('#start_date').val(),
        'end_date': form.find('#end_date').val(),
        'member_id':form.find('#member_id').val(),
      };

      loadTrackedGroupRecord(0, filters);
    }
  });

  function createTrackedGroupTable(result) {
    $('#tracked-group-list tbody').empty();

    for (index in result) {
      let tracked_group = result[index].traked_group;
      let count = result[index].count;

      let tr =
        `<tr>
            <td><button type="button" class="btn btn-info btn-xs" onclick="viewTracked('${tracked_group}', 0, true);" >View</button></td>
            <td>${tracked_group}</td>
            <td>${count}</td>
          </tr>`;

      $('#tracked-group-list tbody').append(tr);
    }
  }

  // Load Page Tracked Group When Initialize 
  loadTrackedGroupRecord(0, {
    'member_id': $('#traked_group_form').find('#member_id').val()
  });

  function loadTrackedGroupRecord(pagno, filters, btnSearch = null) {
    loadingButton(btnSearch);

    $.ajax({
      url: '/member/loadTrackedGroupRecord',
      type: 'post',
      dataType: 'json',
      data: {
        'row_no': pagno,
        'filters': filters
      },
      success: function(response) {
        if (response.hasOwnProperty("error")) {
          $('#error-msg').html(response.error);
          $('#print-error-msg').show();
          $('#pagination_tracked_group, #tracked-group-list').hide();
        } else {
          $('#pagination_tracked_group').html(response.pagination);
          createTrackedGroupTable(response.result);
          $('#pagination_tracked_group, #tracked-group-list').show();
        }
      },
      complete: function() {
        stopLoadingButton(btnSearch);
      }
    });
  }

  // Detect member tracking pagination click
  $('#pagination-member-tracking').on('click', 'a', function(e) {
    e.preventDefault();
    let pageno = $(this).attr('data-ci-pagination-page');
    let url = $(this).attr('href');
    viewTracked(getURLParameter(url, 'traked_group'), pageno);
  });

  function getURLParameter(url, name) {
    return (RegExp(name + '=' + '(.+?)(&|$)').exec(url) || [, null])[1];
  }

  $('#search_member_tracking').on('click', function(event) {
    event.preventDefault();

    let form = $('#member_tracking_form');

    let traked_group = form.find('#traked_group').val();

    if (!traked_group) {
      alert('Please choose a tracked group !!!');
      return;
    }

    let filters = {
      'start_date': form.find('#start_date').val(),
      'end_date': form.find('#end_date').val(),
      'device_id': form.find('#device_id').val(),
      'radius': form.find('#radius').val(),
      'lat': form.find('#lat').val(),
      'lng': form.find('#lng').val(),
      'traked_group': traked_group
    }

    let btnSearch = $(this);

    loadingButton(btnSearch);

    $.ajax({
      url: '/member/viewtrackedgroup',
      type: 'post',
      dataType: 'json',
      data: {
        'proc': 'PROCESS',
        'filters': filters
      },
      success: function(data) {
        $('#pagination-member-tracking').html(data.pagination);
        createMemberTrackingTable(data.result);
        if (data.hasOwnProperty("error")) {
          $('#member-tracking-error-msg').html(data.error);
          $('#print-member-tracking-error-msg').show();
          $('#pagination-member-tracking, #member-tracking-list').hide();
        } else {
          $('#print-member-tracking-error-msg').hide();
          $('#pagination-member-tracking').html(data.pagination);
          createMemberTrackingTable(data.result);
          $('#pagination-member-tracking, #member-tracking-list').show();
        }
      },
      complete: function() {
        stopLoadingButton(btnSearch);
      }
    });
  })

  // close errror message
  $('.close').on('click', function(e) {
    e.preventDefault();
    $(this).parent().hide();
  })

  function loadingButton(btn) {
    if (btn !== null) btn.button('loading');
  }

  function stopLoadingButton(btn) {
    if (btn !== null) btn.button('reset');
  }
});
