$(document).ready(function(){
  const API = function() {
    const api = {};
    api.remove = function (url, itemId) {
      // alert('This function will be implemented with AJAX.' + itemId.toString());
      window.location.href = url;
    }

    return api;
  }

  window.__api__ = new API();
});

// predefine date ranges ex. YYYY-MM-DD - YYYY-MM-DD => YYYY-MM-DD to YYYY-MM-DD
const customDateRange = function (datepicker) {
  let start = moment();
  let end = moment();

  function cb(start, end) {
    datepicker.val(start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
  }

  cb(start, end);

  datepicker.daterangepicker({
    locale: {
      format: 'YYYY-MM-DD'
    }
  }, cb);

  cb(start, end);

  datepicker.on('apply.daterangepicker', function(ev, picker) {
      $(this).val(picker.startDate.format('YYYY-MM-DD') + ' to ' + picker.endDate.format('YYYY-MM-DD'));
  });

  datepicker.on('cancel.daterangepicker', function(ev, picker) {
    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' to ' + picker.endDate.format('YYYY-MM-DD'));
  });
}

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

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

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

window.setDefaultDate = function(form) {

  form = (form === null || form === 'undefined')
    ? $('body')
    : form;

  let start_date = form.find('#start_date');
  let end_date = form.find('#end_date');

  if ( ! start_date.val() && ! end_date.val()) {
      start_date
          .datepicker('setDate', moment(moment.now())
              .subtract(1, 'months').format("YYYY/MM/DD"));
      end_date
          .datepicker('setDate', moment(moment.now())
              .format("YYYY/MM/DD"));
  }
}

window.setDefaultDateWithMonths = function(form, month) {

    form = (form === null || form === 'undefined')
      ? $('body')
      : $(form);

    let start_date = form.find('#start_date').length !== 0 
      ? form.find('#start_date')
      : form.find('#from_date');
    let end_date = form.find('#end_date').length !== 0 
      ? form.find('#end_date')
      : form.find('#to_date');
  
    start_date.datepicker('setDate', moment(moment.now())
                .subtract(month, 'months').format("YYYY/MM/DD"));
    end_date.datepicker('setDate', moment(moment.now())
                .format("YYYY/MM/DD"));
}

window.addDatePicker = function(item) {
    $(item).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        clearBtn: true,
        format: "yyyy-mm-dd",
        onClose: function(selectedDate) {
          $(item).datepicker("option", "minDate", selectedDate);
        }
    });
}