/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 2
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   G: () => (/* binding */ getClientServerTimezoneOffsetHrs),
/* harmony export */   j: () => (/* binding */ displayError)
/* harmony export */ });
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(428);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* globals: booking_form_params */


/**
 * Returns the hour offset between the client and the server.
 *
 * @param {*} referenceDate at which to compute offset.
 * @return {number} Number of hours between server and client.
 */
function getClientServerTimezoneOffsetHrs(referenceDate) {
  if (!booking_form_params.timezone_conversion) {
    return 0;
  }
  const referenceTime = moment(referenceDate);
  const clientOffset = referenceTime.utcOffset();
  referenceTime.tz(booking_form_params.server_timezone);
  const serverOffset = referenceTime.utcOffset();
  return (clientOffset - serverOffset) / 60.0;
}
function displayError(errorMessage = booking_form_params.i18n_request_failed, after = '#wc-bookings-booking-form') {
  // Remove 'active' class from old notices.
  jquery__WEBPACK_IMPORTED_MODULE_0___default()('.woocommerce-error.wc-bookings-notice').removeClass('active');

  // Create a new error notice element.
  const errorMessageHTML = document.createElement('p');
  errorMessageHTML.setAttribute('class', 'woocommerce-error wc-bookings-notice active');
  errorMessageHTML.setAttribute('style', 'display: none;');
  errorMessageHTML.textContent = errorMessage;
  jquery__WEBPACK_IMPORTED_MODULE_0___default()(errorMessageHTML).insertAfter(after);

  // Show a new notice and hide old ones.
  jquery__WEBPACK_IMPORTED_MODULE_0___default()('.woocommerce-error.wc-bookings-notice.active').slideDown({
    complete() {
      jquery__WEBPACK_IMPORTED_MODULE_0___default()('.woocommerce-error.wc-bookings-notice:not(.active)').slideUp();
    }
  });
}

/***/ },

/***/ 771
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

/* unused harmony exports HookApi, BookingDisabledClass */
/**
 * Global variable for booking. This uses to expose public methods.
 *
 * @since 1.15.79
 */
const HookApi = () => {
  return window.wc_bookings.hooks;
};
const BookingDisabledClass = 'disabled';

/**
 * Set the button disabled state.
 *
 * @param {Object}  button   jQuery button.
 * @param {boolean} disabled Whether to disable the button.
 * @return {void}
 */
const SetButtonDisabled = (button, disabled) => {
  if (disabled) {
    button.addClass(BookingDisabledClass).attr('aria-disabled', 'true').attr('disabled', 'disabled');
  } else {
    button.removeClass(BookingDisabledClass).removeAttr('aria-disabled').removeAttr('disabled');
  }
};
/* harmony export */ __webpack_require__.d(__webpack_exports__, [
/* harmony export */   "ze", 0, /* binding */ SetButtonDisabled
/* harmony export */ ]);


/***/ },

/***/ 428
(module) {

module.exports = window["jQuery"];

/***/ }

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	const __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		const cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		const module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			const getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter/value functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			if(Array.isArray(definition)) {
/******/ 				var i = 0;
/******/ 				while(i < definition.length) {
/******/ 					var key = definition[i++];
/******/ 					var binding = definition[i++];
/******/ 					if(!__webpack_require__.o(exports, key)) {
/******/ 						if(binding === 0) {
/******/ 							Object.defineProperty(exports, key, { enumerable: true, value: definition[i++] });
/******/ 						} else {
/******/ 							Object.defineProperty(exports, key, { enumerable: true, get: binding });
/******/ 						}
/******/ 					} else if(binding === 0) { i++; }
/******/ 				}
/******/ 			} else {
/******/ 				for(var key in definition) {
/******/ 					if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 						Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 					}
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.hasOwn(obj, prop))
/******/ 	})();
/******/ 	
/************************************************************************/
let __webpack_exports__ = {};
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(428);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(771);
/* harmony import */ var _bookings_lib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/**
 * External dependencies
 */



/**
 * Internal dependencies
 */

jquery__WEBPACK_IMPORTED_MODULE_0___default()(document).ready(function ($) {
  const localTimezone = moment.tz.guess() || booking_form_params.server_timezone;
  if (booking_form_params.timezone_conversion) {
    $('.wc-bookings-date-picker-timezone').text(localTimezone.replace('_', ' '));
    $('[name="wc_bookings_field_start_date_local_timezone"]').val(localTimezone);
  }
  $('.block-picker').on('keydown', 'a', function (e) {
    if (e.keyCode === 32 || e.key === ' ') {
      e.preventDefault();
      $(this).trigger('click');
    }
  });
  $('.block-picker').on('click', 'a', function () {
    const bookingform = $(this).closest('form');

    // Don't enable this event for month duration.
    if (bookingform.find('[name="wc_bookings_field_start_date_yearmonth"]').length) {
      return false;
    }
    const value = $(this).data('value');
    const blockPicker = $(this).closest('ul');
    setSelectedTime(blockPicker, value);
    return false;
  });
  function setSelectedTime(blockPicker, value) {
    const submitButton = blockPicker.closest('form').find('.wc-bookings-booking-form-button');
    if (undefined === value) {
      (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .SetButtonDisabled */ .ze)(submitButton, true);
      return;
    }
    const selectedBlock = blockPicker.find('[data-value="' + value + '"]');
    if (undefined === selectedBlock.data('value')) {
      (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .SetButtonDisabled */ .ze)(submitButton, true);
      return;
    }
    const target = blockPicker.closest('div').find('input');
    target.val(value).trigger('change');
    blockPicker.closest('ul').find('a').removeClass('selected').removeAttr('aria-pressed');
    selectedBlock.addClass('selected').attr('aria-pressed', 'true');
    (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .SetButtonDisabled */ .ze)(submitButton, false);
  }
  function timePickerResetSelected(blockPicker) {
    blockPicker.closest('ul').find('a').removeClass('selected').removeAttr('aria-pressed');
  }
  wc_bookings_booking_form.time_picker_reset_selected = timePickerResetSelected;
  $('.wc-bookings-booking-form').on('change', '#wc-bookings-form-start-time', function () {
    const value = $(this).val();

    // Disable end time dropdown.
    $('#wc-bookings-form-end-time').attr('disabled', 'disabled');

    // Set the end time dropdown opacity.
    $('#wc-bookings-form-end-time').css('opacity', '0.5');

    // Hide the cost as a reset.
    $(this).closest('form').find('.wc-bookings-booking-cost').html('').hide();
    if (value === '0') {
      const submitButton = $(this).closest('form').find('.wc-bookings-booking-form-button');
      (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .SetButtonDisabled */ .ze)(submitButton, true);
      return false;
    }
    const bookingForm = $(this).closest('form');
    // Disable the Book button.
    const submitButton = bookingForm.find('.wc-bookings-booking-form-button');
    (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .SetButtonDisabled */ .ze)(submitButton, true);
    const yearStr = bookingForm.find('input.booking_date_year').val();
    const year = parseInt(yearStr, 10);
    const monthStr = bookingForm.find('input.booking_date_month').val();
    const month = parseInt(monthStr, 10);
    const dayStr = bookingForm.find('input.booking_date_day').val();
    const day = parseInt(dayStr, 10);
    if (!year || !month || !day) {
      return;
    }
    const id = $(this).parents('.wc-bookings-start-time-container').data('productId');
    const blocks = $(this).parents('.wc-bookings-start-time-container').data('blocks');
    const formField = $(this).parents('.form-field').eq(0);
    const resourceId = bookingForm.find('#wc_bookings_field_resource').val();
    const personQty = bookingForm.find('#wc_bookings_field_persons').val();
    const dateStr = yearStr + '-' + monthStr + '-' + dayStr;
    xhr = $.ajax({
      type: 'POST',
      url: booking_form_params.ajax_url,
      data: {
        action: 'wc_bookings_get_end_time_html',
        security: booking_form_params.nonce.get_end_time_html,
        start_date_time: value,
        product_id: id,
        blocks,
        resource_id: resourceId,
        person_qty: personQty
      },
      success(response) {
        bookingForm.find('.wc-bookings-end-time-container').replaceWith(response);
        offsetBlockTimesForEndTime(dateStr);
        formField.find('input.required_for_calculation').val(value);
      },
      dataType: 'html'
    });
    return false;
  });
  $('.wc-bookings-booking-form').on('change', '#wc-bookings-form-end-time', function () {
    // Hide the cost as a reset.
    $('.wc-bookings-booking-cost').html('').hide();
    const value = $(this).val(),
      blockPicker = $(this);
    $(this).parents('.wc-bookings-booking-form').find('.wc_bookings_field_duration').val(value);
    const submitButton = blockPicker.closest('form').find('.wc-bookings-booking-form-button');
    if (undefined === value || value === '0' || $(this).parents('.wc-bookings-booking-form').find('#wc-bookings-form-start-time').val() === '0') {
      (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .SetButtonDisabled */ .ze)(submitButton, true);
      return;
    }
    blockPicker.parents('.form-field').eq(0).find('input.required_for_calculation').trigger('change');
    (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .SetButtonDisabled */ .ze)(submitButton, false);
  });
  $('.wc_bookings_field_duration').on('change', function () {
    if (!['hour', 'minute'].includes(wc_bookings_booking_form.get_booking_duration_unit($(this)))) {
      return;
    }
    showAvailableTimeBlocks(this);
  });
  $('#wc_bookings_field_resource').on('change', function () {
    const durationUnit = wc_bookings_booking_form.get_booking_duration_unit($(this));
    if (durationUnit === 'month') {
      showAvailableMonthBlocks(this);
    } else if (!['hour', 'minute'].includes(durationUnit)) {
      return;
    }
    timePickerResetSelected($('.wc-bookings-booking-form').find('.block-picker'));
  });
  $('.wc-bookings-booking-form .wc-bookings-date-picker').on('date-selected', function () {
    $('.wc_bookings_field_duration').val(1);
    if (!['hour', 'minute'].includes(wc_bookings_booking_form.get_booking_duration_unit($(this)))) {
      return;
    }
    showAvailableTimeBlocks(this);
  });
  let xhr;
  function showAvailableMonthBlocks(element) {
    const $form = $(element).closest('form');
    const formVal = $form.serialize();
    const blockPicker = $(element).closest('div').find('.block-picker');
    blockPicker.closest('div').block({
      message: null,
      overlayCSS: {
        background: '#fff',
        backgroundSize: '16px 16px',
        opacity: 0.6
      }
    }).show();
    $.ajax({
      type: 'POST',
      url: booking_form_params.ajax_url,
      data: {
        action: 'wc_bookings_get_booking_blocks',
        form: formVal,
        security: booking_form_params.nonce.show_available_month_blocks
      },
      success(result) {
        result = JSON.parse(result);

        // Check for failure.
        if (!result.success) {
          window.alert(result.data); // eslint-disable-line no-alert
          return false;
        }
        blockPicker.closest('div').unblock();
        $('.block-picker').html(result.data);
      },
      error(jqXHR, exception) {
        if (exception === 'abort') {
          return; // Assuming the date is changed very quickly.
        }
        ;(0,_bookings_lib__WEBPACK_IMPORTED_MODULE_2__/* .displayError */ .j)();
      },
      dataType: 'html'
    });
  }
  function showAvailableTimeBlocks(element) {
    const datePickerWrapper = $(element).closest('.wc-bookings-date-picker');
    const yearStr = datePickerWrapper.find('input.booking_date_year').val();
    const year = parseInt(yearStr, 10);
    const monthStr = datePickerWrapper.find('input.booking_date_month').val();
    const month = parseInt(monthStr, 10);
    const dayStr = datePickerWrapper.find('input.booking_date_day').val();
    const day = parseInt(dayStr, 10);
    const dateStr = yearStr + '-' + monthStr + '-' + dayStr;
    if (!year || !month || !day) {
      return;
    }
    const $form = $(element).closest('form');
    const blockPicker = $form.find('.block-picker');
    const selectedBlock = blockPicker.find('.selected');

    // clear blocks
    blockPicker.closest('div').find('input').val('').trigger('change');
    blockPicker.closest('div').block({
      message: null,
      overlayCSS: {
        background: '#fff',
        backgroundSize: '16px 16px',
        opacity: 0.6
      }
    }).show();
    $form.find('.wc-bookings-booking-cost').html('').hide();

    // Get blocks via ajax
    if (xhr) {
      xhr.abort();
    }
    let formVal = $form.serialize();

    /*
     * Get previous/next day in addition to current day based on server/client timezone offset.
     * This will give the client enough blocks to fill out 24 hours of blocks in its timezone.
     */
    const serverOffset = (0,_bookings_lib__WEBPACK_IMPORTED_MODULE_2__/* .getClientServerTimezoneOffsetHrs */ .G)(dateStr);
    if (serverOffset < 0) {
      formVal += '&get_next_day=true';
    } else if (serverOffset > 0) {
      formVal += '&get_prev_day=true';
    }
    xhr = $.ajax({
      type: 'POST',
      url: booking_form_params.ajax_url,
      data: {
        action: 'wc_bookings_get_blocks',
        form: formVal
      },
      success(code) {
        blockPicker.html(code);
        resizeBlocks();
        offsetBlockTimes(dateStr, $(element));
        blockPicker.closest('div').unblock();
        setSelectedTime(blockPicker, selectedBlock.data('value'));

        // Focus on the first element.
        blockPicker.find('li:first a').trigger('focus');

        // Hide error notices.
        $('.woocommerce-error.wc-bookings-notice').slideUp();
      },
      error(jqXHR, exception) {
        if (exception === 'abort') {
          return; // Assuming the date is changed very quickly.
        }
        ;(0,_bookings_lib__WEBPACK_IMPORTED_MODULE_2__/* .displayError */ .j)();

        // Remove loading spin and refresh the datepicker.
        $('.blockOverlay').remove();
        wc_bookings_booking_form.wc_bookings_date_picker.clear_selection();
        wc_bookings_booking_form.wc_bookings_date_picker.refresh_datepicker();
      },
      dataType: 'html'
    });
  }
  function resizeBlocks() {
    let maxWidth = 0;
    let maxHeight = 0;
    $('.block-picker a').each(function () {
      const width = $(this).width();
      const height = $(this).height();
      if (width > maxWidth) {
        maxWidth = width;
      }
      if (height > maxHeight) {
        maxHeight = height;
      }
    });
    $('.block-picker a').width(maxWidth);
    $('.block-picker a').height(maxHeight);
  }
  function offsetBlockTimesForEndTime(dateStr) {
    if (!booking_form_params.timezone_conversion) {
      return;
    }
    const from = moment.tz(dateStr, localTimezone);
    const to = moment(from);
    const element = '.block-picker #wc-bookings-form-end-time > option';
    to.add(1, 'days');
    $(element).each(function () {
      const blockTime = $(this).data('value');
      if (typeof blockTime === 'undefined' || blockTime === '0') {
        return true;
      }
      const serverOffset = (0,_bookings_lib__WEBPACK_IMPORTED_MODULE_2__/* .getClientServerTimezoneOffsetHrs */ .G)(dateStr);
      const clientLocalTime = moment.tz(blockTime, booking_form_params.server_timezone);
      const durationDisplay = $(this).data('durationDisplay');
      clientLocalTime.add(serverOffset, 'hours');
      $(this).text(clientLocalTime.format(booking_form_params.server_time_format) + durationDisplay);
    });
  }
  function offsetBlockTimes(dateStr, element) {
    if (!booking_form_params.timezone_conversion) {
      return;
    }
    const bookingDurationType = wc_bookings_booking_form.get_booking_duration_type(element);
    const bookingDurationUnit = wc_bookings_booking_form.get_booking_duration_unit(element);
    const from = moment.tz(dateStr, localTimezone);
    const to = moment(from);
    let selector = '.block-picker .block a';
    to.add(1, 'days');
    if (bookingDurationType === 'customer' && ['hour', 'minute'].includes(bookingDurationUnit)) {
      selector = '.block-picker #wc-bookings-form-start-time > option';
    }
    $(selector).each(function () {
      const blockTime = selector === '.block-picker #wc-bookings-form-start-time > option' ? $(this).val() : $(this).attr('data-value'); // ISO 8601 time string.
      if (typeof blockTime === 'undefined' || blockTime === '0') {
        return true;
      }
      const serverOffset = (0,_bookings_lib__WEBPACK_IMPORTED_MODULE_2__/* .getClientServerTimezoneOffsetHrs */ .G)(dateStr);
      const serverLocalTime = moment.tz(blockTime, booking_form_params.server_timezone);
      const clientLocalTime = moment.tz(blockTime, booking_form_params.server_timezone);
      clientLocalTime.add(serverOffset, 'hours');
      if (!serverLocalTime.isBetween(from, to, null, '[)')) {
        if (selector === '.block-picker #wc-bookings-form-start-time > option') {
          // Delete any blocks outside of today.
          $(this).remove();
        } else {
          // Delete any blocks outside of today.
          $(this).parent().remove();
        }
      } else {
        if (selector === '.block-picker #wc-bookings-form-start-time > option') {
          const blockTimestamp = moment($(this).val()).unix();
          const currentBrowserTime = moment().unix();
          if (blockTimestamp <= currentBrowserTime) {
            // Delete any blocks outside of right now in the past.
            $(this).remove();
          } else {
            $(this).text(serverLocalTime);
          }
        }
        $(this).text(clientLocalTime.format(booking_form_params.server_time_format));

        // If the block has existing bookings, show the remaining slots after the time.
        if ($(this).data('remaining')) {
          if (selector === '.block-picker #wc-bookings-form-start-time > option') {
            $(this).append(' (' + $(this).data('remaining') + ')');
          } else {
            $(this).append(' <small class="booking-spaces-left">(' + $(this).data('remaining') + ')</small>');
          }
        }
      }
    });
  }
});
/******/ })()
;
//# sourceMappingURL=admin-time-picker.js.map