// ADD SPACES IN DATE INPUT IN BETWEEN DAY MONTH AND YEAR
$(document).ready(function() {
  $(document).on('keydown input', '.DateInput_input', function(e) {
    var input = this.value;
    var key = e.key || String.fromCharCode(e.keyCode || e.which || e.charCode);

    var caretPosition = this.selectionStart;

    if (key === 'Backspace') {
      var previousChar = input[caretPosition - 1];

      // Allow deletion of spaces
      if (previousChar === ' ' && (caretPosition === 3 || caretPosition === 7)) {
        this.value = input.slice(0, caretPosition - 2) + input.slice(caretPosition);
        this.setSelectionRange(caretPosition - 2, caretPosition - 2);
        e.preventDefault();
        return;
      }
    }

    if (input.length === 11) return;

    var values = input.split(' ');
    var output = values.map(function(v, i) {
      if (v.length === 2 && i < 1) {
        return v + ' ';
      } else if (v.length === 3 && i < 2) {
        return v + ' ';
      } else {
        return v;
      }
    });

    this.value = output.join('').substr(0, 11);

    // Adjust caret position after modifying the input value
    var newCaretPosition = caretPosition - (input.length - this.value.length);
    this.setSelectionRange(newCaretPosition, newCaretPosition);
  });
});

// MOVE DATEPICKER ABOVE THE TIMESERIES AREA
$(document).ready(function () {
	$(document).on('click', ".SingleDatePickerInput_clearDate, .SingleDatePicker", function moveDatePicker () {
		const element = document.getElementsByClassName('DayPicker')[0];
		// We still want the menu to go below on eval/vis for modis
		const evalVis = document.getElementById('eval-date');
		if (evalVis != null) {
		    return
		}else if (element != null) {
		    element.style.position = 'absolute';
		    element.style.bottom = '78px';
		}else {
		    setTimeout(moveDatePicker, 20);
		};
	});
});

// CLEAR DATEPICKER WITHOUT RESETTING
$(document).ready(function () {
    $(document).on('click', "#clear_button", function () {
	const date = document.getElementById('date');
	date.focus();
	date.click();
	date.value = '';
    })
})

