').insertAfter($(this));\n }\n charCountContainer.html(charCountHtml);\n // trigger the keydown event so that any existing character data is calculated\n $(this).change();\n });\n };\n\n SmartOrderRefill.creatContainer = function (selector) {\n var $target,\n id;\n if (jQuery.type(selector) === 'string') {\n if (selector.indexOf('#') === 0) {\n $target = $(selector, document);\n $target.selector = selector;\n } else {\n $target = $('#' + selector, document);\n $target.selector = '#' + selector;\n }\n } else if (selector instanceof jQuery) {\n $target = selector;\n }\n\n if ($target && $target.length === 0) {\n if ($target.selector && $target.selector.indexOf('#') === 0) {\n id = $target.selector.substr(1);\n $target = $('
').attr('id', id).appendTo('body');\n }\n }\n return $target;\n };\n\n function getURLParameter(url, name) {\n const match = RegExp(name + '=' + '(.+?)(&|$)').exec(url);\n return match ? match[1] : null;\n }\n\n /* ****** End of Util section ****** */\n\n\n /* ****** Start of Account section ******* */\n\n SmartOrderRefill.initAddressChangeForm = function (target, urlview) {\n $(document).off('click', '.changeaddress').on('click', '.changeaddress', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n $container = SmartOrderRefill.creatContainer('#addresschange'),\n options = SmartOrderRefill.ModalOptions.addressChangeFormOptions(target, urlview, $container);\n\n $container.load(url, function () {\n SmartOrderRefill.CreateModal($container, options);\n var $form = $('#editAddressForm');\n\n $('select[name$=\"_changeaddress\"]', $form).on('change', function () {\n var selected = $(this).children(':selected').first(),\n selectedAddress = $(selected).data('address');\n if (!selectedAddress) {\n return;\n }\n fillAddressFields(selectedAddress, $form);\n SmartOrderRefill.validateForm($form);\n });\n });\n });\n };\n\n function fillAddressFields(address, $form) {\n for (var field in address) {\n if (field === 'ID' || field === 'UUID' || field === 'key') {\n continue;\n }\n $form.find('[name$=\"' + field.replace('Code', '') + '\"]').val(address[field]);\n\n if (field === 'countryCode') {\n $form.find('[name$=\"country\"]').trigger('change');\n $form.find('[name$=\"state\"]').val(address.stateCode);\n }\n }\n }\n\n /**\n * @private\n * @function\n * @description initialize dialog for order view\n */\n SmartOrderRefill.initOrderView = function () {\n $('.order.view').on('click', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n $container = SmartOrderRefill.creatContainer('#orderview');\n\n $container.load(url, function () {\n SmartOrderRefill.limitCharacters();\n SmartOrderRefill.CreateModal($container, SmartOrderRefill.ModalOptions.orderViewOptions);\n SmartOrderRefill.initAddressChangeForm('#orderview', url);\n });\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize dialog for subscription view\n */\n SmartOrderRefill.initSubscriptionView = function () {\n $('.subscription.view').on('click', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n $container = SmartOrderRefill.creatContainer('#subscriptionview');\n\n $container.load(url, function () {\n SmartOrderRefill.limitCharacters();\n SmartOrderRefill.CreateModal($container, SmartOrderRefill.ModalOptions.subscriptionViewOptions);\n SmartOrderRefill.initAddressChangeForm('#subscriptionview', url);\n SmartOrderRefill.initUpdateCreditCardForm();\n });\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize update product quantity\n */\n SmartOrderRefill.initUpdateProductQuantity = function () {\n $(document).on('click', '.update-item', function (e) {\n e.preventDefault();\n\n var url = $(this).attr('data-link'),\n item = getURLParameter(url, 'item'),\n quantity = $(this).parents('.order-section').find('#quantity_' + item).val();\n $.ajax({\n type: 'POST',\n url: url,\n data: {\n quantity: quantity\n }\n }).done(function (response) {\n if (response) {\n if ($('#qtyError').length) {\n $('#qtyError').remove();\n }\n if (response.success) {\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n } else if (!$('#qtyError').length) {\n $('
').insertAfter('#quantity_' + item);\n }\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_QUANTITY_ERROR, false);\n }\n }).fail(function () {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n });\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize remove product\n */\n SmartOrderRefill.initRemoveProduct = function () {\n $(document).on('click', '.remove-item', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link');\n $.ajax({\n type: 'POST',\n url: url\n }).done(function (response) {\n handleRefillResponse(response);\n }).fail(function () {\n handleRefillError();\n });\n });\n };\n\n /**\n * Handles the response of the refill update AJAX request.\n *\n * @param {Object} response - The response object from the AJAX request.\n */\n function handleRefillResponse(response) {\n if (response && response.success) {\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_QUANTITY_ERROR, false);\n }\n }\n\n /**\n * Handles errors that occur during the refill update AJAX request.\n *\n */\n function handleRefillError() {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n }\n\n /**\n * Validate input for delivery address\n */\n function validateInput(input) {\n var pattern = input.attr('pattern') ? input.attr('pattern') : null;\n var maxLength = input.attr('maxLength') ? input.attr('maxLength') : null;\n var minLength = input.attr('minLength') ? input.attr('minLength') : null;\n var value = input.val();\n var isMandatory = input.attr('required') == 'required' ? true : false;\n var isValidByAllParams = false;\n var isValidByPattern = false;\n var isValidMinLength = false;\n var isValidMaxLength = false;\n if (value) {\n if (!pattern || new RegExp(pattern).test(value)) {\n isValidByPattern = true;\n }\n if (!minLength || value.length >= minLength) {\n isValidMinLength = true;\n }\n if (!maxLength || value.length <= maxLength) {\n isValidMaxLength = true;\n }\n isValidByAllParams = isValidByPattern && isValidMinLength && isValidMaxLength;\n } else {\n if (!isMandatory) {\n isValidByAllParams = true;\n }\n }\n\n input.removeClass('is-invalid');\n input.parent().find('.invalid-feedback').hide();\n if (!isValidByAllParams) {\n input.addClass('is-invalid');\n if (!value) {\n input.parent().find('.invalid-feedback.invalid-missing').show();\n } else if (!isValidByPattern) {\n input.parent().find('.invalid-feedback.invalid-pattern').show();\n } else if (!isValidMinLength || !isValidMaxLength) {\n input.parent().find('.invalid-feedback.invalid-length').show();\n }\n }\n\n return isValidByAllParams;\n }\n\n SmartOrderRefill.initUpdateSubscription = function () {\n $(document).on('click', '.save-subscription-changes', function (e, data) {\n e.preventDefault();\n\n // data to update products quantity\n var updateProductModel;\n var updateProductModels = [];\n $('.product-item').each(function () {\n updateProductModel = {\n orderProductId: $(this).find('input').data('pid'),\n orderQuantity: $(this).find('.product-quantity .quantity-input').val()\n };\n updateProductModels.push(updateProductModel);\n });\n\n //check if all products are deleted from subscription\n if (updateProductModels.length === 0) {\n $('#emptySubscriptionModal').modal('show');\n return false;\n }\n\n var deliveryAddress = {};\n var shipmentSelectedOption = $('#shipmentSelector-default').find(':selected');\n var isPostalCodeValid;\n var isAddressOneValid;\n var isAddressTwoValid;\n var isCityValid;\n var isShippingCountryValid;\n if ($('.js-account-address-selector').hasClass('d-none')) {\n isPostalCodeValid = validateInput($('#shippingZipCodedefault'));\n isAddressOneValid = validateInput($('#shippingAddressOnedefault'));\n isAddressTwoValid = validateInput($('#shippingAddressTwodefault'));\n isCityValid = validateInput($('#shippingAddressCitydefault'));\n isShippingCountryValid = validateInput($('#shippingCountrydefault'));\n if (!isPostalCodeValid || !isAddressOneValid || !isAddressTwoValid || !isCityValid || !isShippingCountryValid) {\n return;\n }\n deliveryAddress = {\n postalCode: $('#shippingZipCodedefault').val(),\n address1: $('#shippingAddressOnedefault').val(),\n address2: $('#shippingAddressTwodefault').val(),\n city: $('#shippingAddressCitydefault').val(),\n stateCode: $('#shippingCountrydefault').val()\n };\n } else {\n deliveryAddress = {\n postalCode: shipmentSelectedOption.data('postal-code'),\n address1: shipmentSelectedOption.data('address1'),\n address2: shipmentSelectedOption.data('address2'),\n city: shipmentSelectedOption.data('city'),\n stateCode: shipmentSelectedOption.data('state-code')\n };\n }\n\n var billingAddress = {};\n var billingSelectedOption = $('#billingAddressSelector').find(':selected');\n var isBillingPostalCodeValid;\n var isBillingAddressOneValid;\n var isBillingAddressTwoValid;\n var isBillingCityValid;\n var isBillingCountryValid;\n if ($('#billingAddressSelector').hasClass('d-none')) {\n isBillingPostalCodeValid = validateInput($('#billingZipCode'));\n isBillingAddressOneValid = validateInput($('#billingAddressOne'));\n isBillingAddressTwoValid = validateInput($('#billingAddressTwo'));\n isBillingCityValid = validateInput($('#billingAddressCity'));\n isBillingCountryValid = validateInput($('#billingState'));\n if (!isBillingPostalCodeValid || !isBillingAddressOneValid || !isBillingAddressTwoValid || !isBillingCityValid || !isBillingCountryValid) {\n return;\n }\n billingAddress = {\n postalCode: $('#billingZipCode').val(),\n address1: $('#billingAddressOne').val(),\n address2: $('#billingAddressTwo').val(),\n city: $('#billingAddressCity').val(),\n stateCode: $('#billingState').val()\n };\n } else {\n billingAddress = {\n postalCode: billingSelectedOption.data('postal-code'),\n address1: billingSelectedOption.data('address1'),\n address2: billingSelectedOption.data('address2'),\n city: billingSelectedOption.data('city'),\n stateCode: billingSelectedOption.data('state-code')\n };\n }\n\n var requestObject = {\n sid: $(this).attr('data-subscriptionId'),\n oid: $(this).attr('data-orderId'),\n replacementConfiguration: $('input[name=replacementConfiguration]:checked').val(),\n newTitle: $('#subscriptionTitleId').val(),\n updateProductModels: JSON.stringify(updateProductModels),\n deliveryAddress: JSON.stringify(deliveryAddress),\n billingAddress: JSON.stringify(billingAddress),\n instructionsOption: $('.shippingInstructionsOptions option:selected').val(),\n shippingMethod: $('.shippingMethodID').val(),\n shippingWareHouseID: $('.shippingWareHouseID').val(),\n repeatOrder: $('.shippingRepeatOrder option:selected').val(),\n instructions: $('#shippingInstructionsdefault').val(),\n deliveryDate: $('.shippingDeliveryDateEdit').val(),\n braintreePaymentMethodNonce: $('#braintreeCreditCardNonce').val(),\n cardOwner: $('#braintreeCardHolder').val(),\n selectedCreditCardUuid: $('select[name=braintreeCreditCardList] option').filter(':selected').val(),\n paymentMethodUUID: $('select[name=braintreePaypalAccountList] option').filter(':selected').val(),\n isPayPal: $('.payment-information').attr('data-payment-method-id') == 'PayPal'\n };\n\n if (data) {\n requestObject.paypalEmail = data.get('dwfrm_braintreepaypalaccount_email');\n requestObject.paypalNonce = data.get('dwfrm_braintreepaypalaccount_nonce');\n requestObject.paypalAddress = data.get('dwfrm_braintreepaypalaccount_addresses');\n requestObject.paypalShippingAddress = data.get('dwfrm_braintreepaypalaccount_shippingAddress');\n }\n\n $.ajax({\n type: 'POST',\n url: $(this).attr('data-link'),\n data: requestObject\n }).done(function (response) {\n if (response.error) {\n $.spinner().stop();\n $('.braintree-loader-container').hide();\n var errorHtml = '
' +\n '' + response.errorMessage + '
';\n\n $('.error-messaging').append(errorHtml);\n $('.error-messaging').show();\n if ($('.payment-information').attr('data-payment-method-id') == 'PayPal') {\n $('.js_braintree_accountPaypalButton_wrapper').removeClass('d-none');\n } else {\n $('.braintreeCreditCardBtn').show();\n }\n } else if (response.redirectUrl) {\n if ($('.success-message').length == 0) {\n $('body').append(\n '
'\n );\n }\n\n $('.success-message')\n .append('
Changes saved
');\n\n setTimeout(() => {\n $('.success-message').remove();\n window.location.replace(response.redirectUrl);\n window.location.replace(response.redirectUrl);\n }, 3000);\n }\n });\n });\n\n // Trigger subscription cancellation on user's confirmation\n $(document).on('click', '.subscription-delete-confirmation-btn', function (e, _data) {\n e.preventDefault();\n // trigger subscription cancellation button \n $('.cancelsubscription').trigger('click');\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize change product form\n */\n SmartOrderRefill.initChangeProductForm = function () {\n $(document).off('click', '.change-item').on('click', '.change-item', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n $container = SmartOrderRefill.creatContainer('#changeproduct'),\n options = SmartOrderRefill.ModalOptions.changeProductFormOptions;\n\n $container.load(url, function () {\n SmartOrderRefill.CreateModal($container, options);\n });\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize dialog for update credit card view\n */\n SmartOrderRefill.initUpdateCreditCardForm = function () {\n $(document).off('click', '.update-card').on('click', '.update-card', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n $container = SmartOrderRefill.creatContainer('#updatecreditcard'),\n options = SmartOrderRefill.ModalOptions.updateCreditCardFormOptions;\n\n $container.load(url, function () {\n SmartOrderRefill.CreateModal($container, options);\n $('.choose-card-item').on('click', function () {\n $(this).find('input[type=\"radio\"]').prop('checked', true);\n });\n $('select[id$=\\'_updatecard_expiration_month\\']').val(parseInt($('#updatecreditcard').find('.expiration-date-wrapper').attr('data-expmonth'), 10));\n $('select[id$=\\'_updatecard_expiration_year\\']').val($('#updatecreditcard').find('.expiration-date-wrapper').attr('data-expyear'));\n });\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize update refill\n */\n SmartOrderRefill.initUpdateRefill = function () {\n $(document).on('click', '.update-refill', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n item = getURLParameter(url, 'item'),\n periodicity = $('#select-everydelivery-' + item).val(),\n interval = (periodicity == 'month') ? $('#sorMonth-' + item).val() : $('#sorWeek-' + item).val();\n $.ajax({\n type: 'POST',\n url: url,\n data: {\n periodicity: periodicity,\n interval: interval\n }\n }).done(function (response) {\n handleRefillResponse(response);\n }).fail(function () {\n handleRefillError();\n });\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize credit card expiration warning\n */\n SmartOrderRefill.initCreditCardExpirationWarning = function () {\n $(document).on('change', '.pt_checkout [name$=\"creditCard_expiration_month\"], .pt_checkout [name$=\"creditCard_expiration_year\"]', function () {\n var month = $('.pt_checkout [name$=\"creditCard_expiration_month\"]').val(),\n year = $('.pt_checkout [name$=\"creditCard_expiration_year\"]').val();\n toggleExpirationWarning(month, year);\n });\n $(document).on('change', '#checkout-main [name$=\"creditCardFields_expirationMonth\"], #checkout-main [name$=\"creditCardFields_expirationYear\"]', function () {\n var month = $('#checkout-main [name$=\"creditCardFields_expirationMonth\"]').val(),\n year = $('#checkout-main [name$=\"creditCardFields_expirationYear\"').val();\n toggleExpirationWarning(month, year);\n });\n\n function toggleExpirationWarning(month, year) {\n if (typeof month !== 'undefined' && typeof year !== 'undefined' && month && year) {\n var expirationDate = new Date(new Date(year, month).setDate(0)),\n currentDate = new Date(),\n nextYear = new Date(currentDate.getFullYear() + 1, currentDate.getMonth(), currentDate.getDate() - 1);\n\n if ((expirationDate - nextYear) <= 0) {\n $('.credit_card_expiration_warning').show();\n } else {\n $('.credit_card_expiration_warning').hide();\n }\n }\n }\n };\n\n /**\n * @private\n * @function\n * @description initialize reactivate order view\n */\n SmartOrderRefill.initReactivateOrderView = function () {\n $(document).off('click', '.order.reactivate').on('click', '.order.reactivate', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n order = getURLParameter(url, 'sid');\n $.ajax({\n type: 'POST',\n url: url,\n data: {\n order: order\n }\n }).done(function (response) {\n if (response) {\n if (!response.success) {\n var $container = SmartOrderRefill.creatContainer('#reactivate-order');\n $container.html('
' + SmartOrderRefillSettings.Resources.SOR_REACTIVE_ORDER_MESSAGE + '
');\n SmartOrderRefill.CreateModal($container, SmartOrderRefill.ModalOptions.reactivateOrderViewOptions);\n } else {\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n }\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n }\n }).fail(function () {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n });\n });\n };\n\n /**\n * @private\n * @function\n * @description initialize reactivate subscription view\n */\n SmartOrderRefill.initReactivateSubscriptionView = function () {\n $(document).off('click', '.reactivatesubscription').on('click', '.reactivatesubscription', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n $container = SmartOrderRefill.creatContainer('#reactivate-subscription'),\n options = SmartOrderRefill.ModalOptions.reactivateSubscriptionOptions;\n\n $container.load(url, function () {\n SmartOrderRefill.CreateModal($container, options);\n });\n });\n };\n /* ****** End of Account section ****** */\n\n /* ******* Start of Cart section ******* */\n\n SmartOrderRefill.initModifyRefill = function () {\n $(document).on('click', '#modifyRefill', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n $container = SmartOrderRefill.creatContainer('#modify-smart-order-refill');\n\n $container.load(url, function () {\n SmartOrderRefill.limitCharacters();\n SmartOrderRefill.CreateModal($container, SmartOrderRefill.ModalOptions.modifyRefillOptions);\n // force to load the selected value of sor subscriptions\n $('[name=\"everyDelivery\"]').trigger('change');\n $('#modify-smart-order-refill select').on('change', function () {\n $('#multipleRefill').prop('checked', true);\n });\n });\n });\n };\n\n SmartOrderRefill.initRemoveRefill = function () {\n $(document).on('click', '#removeRefill', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n cartShow = SmartOrderRefillSettings.Urls.cartShow;\n\n $.ajax({\n type: 'GET',\n url: url,\n success: function (response) {\n if (response && response.success) {\n window.location = cartShow;\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n }\n }\n });\n });\n };\n\n SmartOrderRefill.initLoginFromCart = function () {\n $(document).on('click', '#message_wrapper a', function () {\n var $container = SmartOrderRefill.creatContainer('#sorlogin'),\n options = {\n modal: true,\n width: '800px',\n open: function () {\n // This is intentional\n }\n };\n $container.load(SmartOrderRefillSettings.Urls.loginFromCartPage, function () {\n SmartOrderRefill.limitCharacters();\n SmartOrderRefill.CreateModal($container, options);\n });\n });\n $(document).on('click', '#sorlogin button', function (e) {\n e.preventDefault();\n var form = $(this).parents('form:first');\n if (SmartOrderRefill.validateForm(form)) {\n var url = form.attr('action'),\n data = {};\n form.serializeArray().map(function (param) {\n data[param.name] = param.value;\n });\n\n $.ajax({\n type: 'POST',\n url: url,\n data: data,\n success: function (response) {\n if (!response) {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n } else if (response.success) {\n if ($('#loginFromCartError').length) {\n $('#loginFromCartError').remove();\n }\n window.location = response.url;\n } else if (!$('#loginFromCartError').length) {\n form.prepend('
' + SmartOrderRefillSettings.Resources.SOR_LOGINFROMCART_ERROR + '
');\n }\n }\n });\n }\n });\n };\n\n /* ******* End of Cart section ******* */\n\n /* ******* Start of Product section ******* */\n\n SmartOrderRefill.initializePdp = function () {\n initOptions();\n\n $(document).on('click', '#pdpMain .product-add-to-cart select#SorDeliveryMonthInterval', function () {\n $('input[name=\"hasSmartOrderRefill\"]').val(['true']);\n });\n\n $('input[name=hasSmartOrderRefill]').change(function () {\n hideOrShowSchedules($(this).is(':checked') ? 'true' : 'false', $(this).closest('.product-detail'));\n }).change();\n\n // Show or hide the schedule select based on user selection.\n function hideOrShowSchedules(value, $context) {\n if (value === 'true') {\n if (window.innerWidth < 568) {\n $('.smart-order-refill-period', $context).attr('style', 'margin: 15px 20px');\n }\n $('.smart-order-refill-period', $context).attr('style', 'display:inline-block');\n $('#everyDelivery', $context).trigger('change');\n $('.weeks-block', $context).addClass('show');\n\n // Get the default interval option value from the checkbox data attribute\n var defaultIntervalOption = $('#OsfSorRefillProductYes', $context).data('default-interval-option');\n $('button.btn-week.js-sor-interval-pdp', $context).removeClass('active');\n $('button.btn-week.js-sor-interval-pdp[data-value=\\'' + defaultIntervalOption + '\\']', $context).addClass('active');\n } else {\n $('.or-cancel-edit-text', $context).attr('style', 'margin-top:10px');\n $('.smart-order-refill-period', $context).attr('style', 'display:none');\n $('.weeks-block', $context).removeClass('show');\n if ($('input[name=variantSelected]').val()) {\n $('#add-to-cart', $context).removeAttr('disabled');\n }\n }\n }\n\n function initOptions() {\n if (!$('.smart-order-refill-options').data('sorOneTime')) {\n $('.smart-order-refill-options [for=\"OsfSorRefillProductNo\"], .smart-order-refill-options [for=\"OsfSorRefillProductYes\"]').hide();\n $('#OsfSorRefillProductYes').prop('checked', true).change();\n }\n if ($('.smart-order-refill-period p').data('disableDropdown')) {\n $('#SorDeliveryWeekInterval, #SorDeliveryMonthInterval').css({\n display: 'none'\n });\n }\n }\n\n $(document).on('change', '[name=\"everyDelivery\"]', function () {\n if ($('.js-repeat-order').hasClass('noInferiorBorder')) {\n $('.js-repeat-order').removeClass('noInferiorBorder');\n }\n else {\n $('.js-repeat-order').addClass('noInferiorBorder');\n }\n if ($(this).val() === 'month') {\n $('select[name=SorDeliveryWeekInterval]').hide();\n $('select[name=SorDeliveryMonthInterval]').show();\n if ($('.smart-order-refill-period p').data('disableDropdown')) {\n $('#SorDeliveryWeekInterval, #SorDeliveryMonthInterval').css({\n display: 'none'\n });\n }\n } else if ($(this).val() === 'week') {\n $('select[name=SorDeliveryMonthInterval]').hide();\n $('select[name=SorDeliveryWeekInterval]').show();\n if ($('.smart-order-refill-period p').data('disableDropdown')) {\n $('#SorDeliveryWeekInterval, #SorDeliveryMonthInterval').css({\n display: 'none'\n });\n }\n }\n });\n\n $('[name=\"everyDelivery\"], select[name=\"SorDeliveryWeekInterval\"], select[name=\"SorDeliveryMonthInterval\"]').on('change', function () {\n var everyDeliveryHasValueSelected = $('[name=\"everyDelivery\"]').val(),\n weekIntervalHasValueSelected = $('select[name=SorDeliveryWeekInterval]').val(),\n monthIntervalHasValueSelected = $('select[name=SorDeliveryMonthInterval]').val(),\n sorDataInformed = everyDeliveryHasValueSelected || (weekIntervalHasValueSelected || monthIntervalHasValueSelected),\n variantSelected = $('input[name=variantSelected]').val(),\n shouldEnableAddToCartButton = sorDataInformed && variantSelected;\n\n if (shouldEnableAddToCartButton) {\n $('#add-to-cart').removeAttr('disabled');\n } else {\n $('#add-to-cart').attr('disabled', 'disabled');\n }\n });\n\n $('body').on('product:afterAddToCart', function (e, response) {\n if (!response.error) {\n $.ajax({\n type: 'POST',\n url: SmartOrderRefillSettings.Urls.updateRefillData,\n data: {\n action: 'update',\n hasSmartOrderRefill: $('[name=\"hasSmartOrderRefill\"]').filter(':checked').val(),\n everyDelivery: $('[name=\"everyDelivery\"]').val(),\n SorDeliveryWeekInterval: $('[name=\"SorDeliveryWeekInterval\"]').val(),\n SorDeliveryMonthInterval: $('[name=\"SorDeliveryMonthInterval\"]').val(),\n liuuid: response.pliUUID\n }\n });\n }\n });\n $('body').on('product:afterAttributeSelect', function (e, response) {\n if (response.data && response.data.product && response.data.product.id) {\n $.ajax({\n type: 'GET',\n url: SmartOrderRefillSettings.Urls.updatePDPOptions,\n data: {\n pid: response.data.product.id\n },\n success: function (innerResponse) {\n var refillOptions = $(innerResponse).filter('.smart-order-refill-options');\n var everyDelivery = refillOptions.find('[name=\"everyDelivery\"]').val();\n var weekInterval = refillOptions.find('[name=\"SorDeliveryWeekInterval\"]').val();\n var monthInterval = refillOptions.find('[name=\"SorDeliveryMonthInterval\"]').val();\n\n var sorPrice = refillOptions.find('.sor-price');\n var sorPriceMessage = refillOptions.find('.sor-price-message');\n\n $('[name=\"everyDelivery\"]').val(everyDelivery).change();\n $('[name=\"SorDeliveryWeekInterval\"]').val(weekInterval).change();\n $('[name=\"SorDeliveryMonthInterval\"]').val(monthInterval).change();\n $('.smart-order-refill-options .sor-price').remove();\n $('.smart-order-refill-options .sor-price-message').remove();\n if (sorPrice.length) {\n $('.smart-order-refill-options').append(sorPrice);\n $('.smart-order-refill-options').append(sorPriceMessage);\n }\n initOptions();\n }\n });\n }\n });\n if ($('input[name=hasSmartOrderRefill]').length > 0) {\n hideOrShowSchedules($('input[name=hasSmartOrderRefill]:checked').val());\n }\n };\n\n // generic method for functions without Ajax calls\n SmartOrderRefill.initLinkModel = function () {\n $(document).off('click', '.sorshowmodal').on('click', '.sorshowmodal', function (e) {\n e.preventDefault();\n var url = $(this).attr('data-link'),\n title = $(this).attr('data-title'),\n content = $(this).attr('data-content'),\n yes = $(this).attr('data-yes'),\n no = $(this).attr('data-no'),\n $container = SmartOrderRefill.creatContainer('#link-model'),\n context = $(this).attr('data-context'),\n options = {\n url: url,\n innerUrl: $(this).attr('data-innerurl'),\n autoOpen: true,\n modal: true,\n title: title,\n width: '400px',\n buttons: {},\n context: context\n };\n\n if ($(this).hasClass('add-products-to-subscription')) {\n options.addnewproducts = true;\n $container.addClass('add-products-subscription-container');\n }\n\n if ($(this).hasClass('cancelsubscription')) {\n options.cancel = true;\n }\n\n if ($(this).hasClass('pausesubscription')) {\n options.pause = true;\n $container.addClass('pause-subscription-container');\n }\n\n if ($(this).hasClass('renewsubscription')) {\n options.renew = true;\n $container.addClass('renew-subscription-container');\n }\n\n if (yes) {\n if (options.innerUrl) {\n if (options.addnewproducts) {\n options.buttons[yes] = SmartOrderRefill.ButtonFunctions.redirectToUrl.bind($container, options.innerUrl);\n } else if (options.renew) {\n options.buttons[yes] = SmartOrderRefill.ButtonFunctions.reactivateSubscriptionSave.bind($container, options.innerUrl);\n } else {\n options.buttons[yes] = SmartOrderRefill.ButtonFunctions.linkModelReloadPage.bind($container, options.innerUrl);\n }\n } else {\n options.buttons[yes] = SmartOrderRefill.ButtonFunctions.linkModelYes.bind($container, url);\n }\n }\n if (no) {\n options.buttons[no] = SmartOrderRefill.CloseModal;\n }\n\n $container.html('
' + content + '
');\n if ($(this).hasClass('pausesubscription') && $(this).attr('data-isFrozen') == 'true') {\n var frozenMessage = $(this).attr('data-frozen');\n var warningBlock = `\n
\n \n ${frozenMessage}\n
\n `;\n $container.append(warningBlock);\n }\n\n SmartOrderRefill.CreateModal($container, options);\n });\n };\n\n // generic method for error messages\n SmartOrderRefill.initErrorModal = function (content, refresPage) {\n var $container = SmartOrderRefill.creatContainer('#error-model'),\n options = {\n autoOpen: true,\n modal: true,\n title: SmartOrderRefillSettings.Resources.SOR_ERROR_TITLE,\n width: '400px',\n buttons: {\n SOR_GLOBAL_OK: SmartOrderRefill.ButtonFunctions.reloadDashboard.bind($container, refresPage)\n }\n };\n\n $container.html('
' + content + '
');\n SmartOrderRefill.CreateModal($container, options);\n };\n\n\n // ***** BUTTONS FUNCTIONS ******\n SmartOrderRefill.ButtonFunctions = {\n linkModelReloadPage: function (url) {\n $.ajax({\n type: 'GET',\n url: url,\n success: function (response) {\n if (response && response.success) {\n location.reload();\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n }\n }\n });\n SmartOrderRefill.CloseModal(this);\n },\n\n redirectToUrl: function (url) {\n window.location.href = url;\n },\n\n // reactivateSubscription\n reactivateSubscriptionSave: function () {\n var $form = $('#renewSubscription');\n var nextDeliveryDate = $('#shippingDeliveryDate').val();\n var sid = $('.renewsubscription').attr('data-sid');\n\n if ($form && $form.attr('action') && sid && nextDeliveryDate) {\n var url = $form.attr('action') + '?sid=' + sid + '&nextDeliveryDate=' + nextDeliveryDate + '&reactiveType=remaining';\n setTimeout(function () {\n $.ajax({\n type: 'POST',\n url: url\n }).done(function (response) {\n if (response && response.success) {\n SmartOrderRefill.CloseModal();\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n }\n }).fail(function () {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n });\n }, 1000);\n } else if (!nextDeliveryDate) {\n $('.error-block').removeClass('d-none');\n $('.content-error-msg').html($('.renewsubscription').attr('data-content'));\n }\n },\n reloadDashboard: function (refresPage) {\n if (refresPage) {\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n }\n },\n // initReactivateOrderView\n reactivateOrderViewOk: function () {\n setTimeout(function () {\n $.ajax({\n type: 'POST',\n url: SmartOrderRefillSettings.Urls.cancelOneOrder,\n data: {\n sid: order // eslint-disable-line no-undef\n }\n }).done(function (response) {\n if (response && response.success) {\n SmartOrderRefill.CloseModal();\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n }\n }).fail(function () {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n });\n }, 1000);\n },\n\n linkModelYes: function (url) {\n $.ajax({\n type: 'GET',\n url: url,\n success: function (response) {\n if (response) {\n if (response.success) {\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n } else if (response.message) {\n SmartOrderRefill.initErrorModal(response.message, true);\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, true);\n }\n }\n }\n });\n SmartOrderRefill.CloseModal();\n },\n\n skipOrderViewYes: function (url) {\n $.ajax({\n type: 'GET',\n url: url,\n success: function (response) {\n handleRefillResponse(response);\n }\n });\n SmartOrderRefill.CloseModal();\n },\n\n // initUpdateCreditCardForm\n updateCreditCardFormSave: function () {\n var $form = $('#editCreditCard');\n var formValid = SmartOrderRefill.validateForm($form);\n var today = new Date();\n today.setHours(0, 0, 0);\n var expirationDate = new Date();\n var year = parseInt($form.find('[name$=\\'updatecard_expiration_year\\']').val(), 10);\n var month = parseInt($form.find('[name$=\\'updatecard_expiration_month\\']').val(), 10);\n if (year && month) {\n expirationDate.setMonth(month - 1);\n expirationDate.setFullYear(year);\n expirationDate.setHours(0, 0, 0);\n if (expirationDate.getTime() <= today.getTime()) {\n formValid = false;\n alert(SmartOrderRefillSettings.Resources.SOR_CREDITCARD_ERROR); // NOSONAR\n }\n }\n\n if (formValid) {\n if ($form.find('.choose-card-wrapper').length > 0) {\n var $cardSelects = $('#editCreditCard').find('[name$=\"updatecard_confirm\"]');\n if ($form.find('[name$=\"updatecard_confirm\"]').filter(':checked').length) {\n $cardSelects.each(function () {\n var $cardSelect = $(this);\n if (!$cardSelect.prop('checked')) {\n $cardSelect.parents('.choose-card-item').remove();\n }\n });\n } else {\n return false;\n }\n }\n setTimeout(function () {\n $.ajax({\n type: 'POST',\n url: $form.attr('action'),\n data: $form.serialize()\n }).done(function (response) {\n if (response && response.success) {\n SmartOrderRefill.CloseModal();\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n } else {\n alert(SmartOrderRefillSettings.Resources.SOR_CREDITCARD_ERROR); // NOSONAR\n }\n }).fail(function () {\n alert(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR); // NOSONAR\n });\n }, 1000);\n }\n },\n\n // initChangeProductForm\n changeProductFormSave: function () {\n var $form = $('#editProductForm');\n var product = $('.product-select').val();\n\n setTimeout(function () {\n $.ajax({\n type: 'POST',\n url: $form.attr('action'),\n data: {\n newProduct: product\n }\n }).done(function (response) {\n if (response && response.success) {\n SmartOrderRefill.CloseModal.call($container); // eslint-disable-line no-undef\n window.location = SmartOrderRefillSettings.Urls.manageOrders;\n } else {\n alert(SmartOrderRefillSettings.Resources.SOR_PRODUCT_ERROR); // NOSONAR\n }\n }).fail(function () {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n });\n }, 1000);\n },\n\n // initAddressChangeForm\n addressChangeFormSave: function () {\n var $form = $('#editAddressForm');\n var formValid = SmartOrderRefill.validateForm($form);\n var target = SmartOrderRefill.addressChangeInfo.target;\n var urlview = SmartOrderRefill.addressChangeInfo.urlview;\n var $container = SmartOrderRefill.addressChangeInfo.container;\n\n setTimeout(function () {\n if (!formValid) {\n return;\n }\n $.ajax({\n type: 'POST',\n url: $form.attr('action'),\n data: $form.serialize()\n }).done(function (response) {\n if (response) {\n if (response.success) {\n var bootstrapModalBody = $(target).find('.modal .modal-body');\n if (bootstrapModalBody.length > 0) {\n target = bootstrapModalBody;\n }\n $(target).load(urlview, function () {\n SmartOrderRefill.limitCharacters();\n });\n SmartOrderRefill.CloseModal.call($container);\n } else if ($('input[name$=\"_postal\"]:invalid').length) {\n $('input[name$=\"_postal\"]').parent().append('
');\n }\n } else {\n alert(SmartOrderRefillSettings.Resources.SOR_ADDRESS_ERROR); // NOSONAR\n }\n }).fail(function () {\n alert(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR); // NOSONAR\n });\n }, 1000);\n },\n\n modifyRefillUpdate: function () {\n var url = $('#modify-smart-order-refill form').attr('action');\n var data = {\n hasSmartOrderRefill: $('[name=\"hasSmartOrderRefill\"]').filter(':checked').val(),\n everyDelivery: $('[name=\"everyDelivery\"]').val(),\n SorDeliveryWeekInterval: $('[name=\"SorDeliveryWeekInterval\"]').val(),\n SorDeliveryMonthInterval: $('[name=\"SorDeliveryMonthInterval\"]').val()\n };\n $.ajax({\n type: 'POST',\n url: url,\n data: data,\n success: function (response) {\n if (response && response.success) {\n window.location = SmartOrderRefillSettings.Urls.cartShow;\n } else {\n SmartOrderRefill.initErrorModal(SmartOrderRefillSettings.Resources.SOR_UNEXPECTED_ERROR, false);\n }\n }\n });\n }\n };\n\n\n // ****** OPTIONS *******\n\n SmartOrderRefill.ModalOptions = {\n // initReactivateSubscriptionView\n reactivateSubscriptionOptions: {\n autoOpen: true,\n bgiframe: true,\n title: SmartOrderRefillSettings.Resources.SOR_REACTIVE_SUBSCRIPTION_TITLE,\n modal: true,\n emptyOnClose: false,\n width: '400px',\n buttons: {\n SOR_GLOBAL_CANCEL: SmartOrderRefill.CloseModal,\n SOR_GLOBAL_SAVE: SmartOrderRefill.ButtonFunctions.reactivateSubscriptionSave\n }\n },\n\n // initReactivateOrderView\n reactivateOrderViewOptions: {\n autoOpen: true,\n bgiframe: true,\n title: SmartOrderRefillSettings.Resources.SOR_REACTIVE_ORDER_TITLE,\n modal: true,\n emptyOnClose: false,\n width: '400px',\n buttons: {\n SOR_GLOBAL_OK: SmartOrderRefill.ButtonFunctions.reactivateOrderViewOk\n }\n },\n\n // initUpdateCreditCardForm\n updateCreditCardFormOptions: {\n autoOpen: true,\n bgiframe: true,\n title: SmartOrderRefillSettings.Resources.SOR_UPDATE_CREDIT_CARD_TITLE,\n modal: true,\n emptyOnClose: false,\n width: '600px',\n buttons: {\n SOR_GLOBAL_CANCEL: SmartOrderRefill.CloseModal,\n SOR_GLOBAL_SAVE: SmartOrderRefill.ButtonFunctions.updateCreditCardFormSave\n }\n },\n // initChangeProductForm\n changeProductFormOptions: {\n autoOpen: true,\n bgiframe: true,\n modal: true,\n emptyOnClose: false,\n width: '400px',\n title: 'Change product',\n buttons: {\n SOR_GLOBAL_CANCEL: SmartOrderRefill.CloseModal,\n SOR_GLOBAL_SAVE: SmartOrderRefill.ButtonFunctions.changeProductFormSave\n }\n },\n // initSubscriptionView\n subscriptionViewOptions: {\n autoOpen: true,\n modal: true,\n dialogClass: 'smart-order-refill-modal',\n width: '700px',\n title: SmartOrderRefillSettings.Resources.SOR_DIALOG_SUBSCRIPTION,\n buttons: {\n SOR_GLOBAL_CLOSE: SmartOrderRefill.CloseModal\n }\n },\n // initOrderView\n orderViewOptions: {\n draggable: false,\n resizable: false,\n dialogClass: 'smart-order-refill-modal',\n autoOpen: true,\n modal: true,\n width: '700px',\n title: SmartOrderRefillSettings.Resources.SOR_DIALOG_ORDER,\n buttons: {\n SOR_GLOBAL_CLOSE: SmartOrderRefill.CloseModal\n }\n },\n modifyRefillOptions: {\n draggable: false,\n resizable: false,\n dialogClass: 'smart-order-refill-modal',\n modal: true,\n title: SmartOrderRefillSettings.Resources.SOR_MODIFY_SMART_ORDER_REFILL,\n width: '600px',\n buttons: {\n SOR_GLOBAL_UPDATE: SmartOrderRefill.ButtonFunctions.modifyRefillUpdate\n }\n },\n // initAddressChangeForm\n addressChangeFormOptions: function (target, urlview, $container) {\n SmartOrderRefill.addressChangeInfo = {\n target: target,\n urlview: urlview,\n container: $container\n };\n return {\n autoOpen: true,\n bgiframe: true,\n modal: true,\n emptyOnClose: false,\n width: '400px',\n title: 'Change address',\n buttons: {\n SOR_GLOBAL_CANCEL: SmartOrderRefill.CloseModal,\n SOR_GLOBAL_SAVE: SmartOrderRefill.ButtonFunctions.addressChangeFormSave\n }\n };\n },\n linkModelYes: function (url) {\n $.ajax({\n type: 'GET',\n url: url,\n success: function (response) {\n handleRefillResponse(response);\n }\n });\n SmartOrderRefill.CloseModal(this);\n }\n\n };\n\n\n SmartOrderRefill.initAccountSorView = function () {\n $('.show-hide-orders').each(function () {\n $(this).on('click', function () {\n $(this).closest('.subscriptionSection').find('.subscriptionOrders').slideToggle('slow');\n });\n });\n };\n\n SmartOrderRefill.initChangeProductQuantity = function () {\n $(document).on('click', '.button-plus-product, .button-minus-product', function (e) {\n e.preventDefault();\n var $input = $(this).siblings('.quantity-input');\n var stepValue = $input.attr('step');\n var minValue = $input.attr('min');\n var maxValue = $input.attr('max');\n var currentval = $input.val();\n\n if ($(e.currentTarget).hasClass('button-plus-product') && currentval < +maxValue) {\n $input.val(+currentval + +stepValue);\n } else if ($(e.currentTarget).hasClass('button-minus-product') && currentval > +minValue) {\n $input.val(+currentval - +stepValue);\n }\n $input.trigger('change');\n\n // check frozen products quantity\n var frozenProductsActionUrl = $('.products').data('frozenurl');\n var productData;\n var productsData = [];\n $('.product-item').each(function () {\n productData = {\n pid: $(this).find('input').data('pid'),\n quantity: $(this).find('.product-quantity .quantity-input').val()\n };\n productsData.push(productData);\n });\n var sid = $(this).closest('.products').data('sid');\n $.ajax({\n url: frozenProductsActionUrl,\n type: 'POST',\n dataType: 'json',\n data: { productsData: JSON.stringify(productsData), sid: sid },\n success: function (response) {\n if (response.isValidFrozenWeight) {\n $('#save-subscription-changes').addClass('save-subscription-changes').removeClass('disabled');\n $('.frozen-warning-message').addClass('d-none');\n } else {\n $('#save-subscription-changes').removeClass('save-subscription-changes').addClass('disabled');\n $('.frozen-warning-message').removeClass('d-none');\n }\n }\n });\n });\n };\n\n SmartOrderRefill.initRemoveProductFromSubscription = function () {\n $(document).on('click', '.remove-subscription-products', function (e) {\n e.preventDefault();\n var removeProductUrl = $(this).closest('.products').data('removeproducturl');\n var pid = $(this).closest('.product-item').data('pid');\n var sid = $(this).closest('.products').data('sid');\n var customerEmail = $('.subcription-detail').data('customeremail');\n var requestObject = {\n pid: pid,\n sid: sid,\n customerEmail: customerEmail\n };\n $.ajax({\n url: removeProductUrl,\n type: 'POST',\n dataType: 'json',\n data: requestObject,\n success: function (response) {\n if (response && response.success) {\n if (response.productsQuantity > 0) {\n $('.product-item[data-pid=\"' + pid + '\"]').remove();\n if (!response.isValidFrozenWeight) {\n $('.frozen-warning-message').removeClass('d-none');\n $('#save-subscription-changes').removeClass('save-subscription-changes').addClass('disabled');\n } else {\n $('.frozen-warning-message').addClass('d-none');\n $('#save-subscription-changes').addClass('save-subscription-changes').removeClass('disabled');\n }\n } else {\n window.location.href = $('.products').data('nomoreproductsurl');\n }\n }\n }\n });\n });\n };\n\n SmartOrderRefill.initOpenSubscriptionDetails = function () {\n $(document).on('click', '.subscription-section', function () {\n var redirectUrl = $(this).data('subscriptionurl');\n window.location.replace(redirectUrl);\n });\n\n // Update total price\n var subscriptions = [];\n if ($('.active-subscription').length > 0) {\n subscriptions = $('.active-subscription');\n } else {\n if ($('.subscriptions-mobile').is(':visible')) {\n subscriptions = $('.subscriptions-mobile .subscription-section');\n } else {\n subscriptions = $('.subscriptions .subscription-section');\n }\n }\n\n for (var i = 0; i < subscriptions.length; i++) {\n var $currentSubs = $(subscriptions[i]);\n\n $.ajax({\n url: $currentSubs.attr('data-updatesubscriptionprice'),\n type: 'GET',\n success: function (response) {\n if (response.id && response.price) {\n $('.' + response.id).find('.price .value').html(response.price);\n }\n }\n });\n }\n };\n\n SmartOrderRefill.initChangeDeliveryDateModal = function () {\n const urlChangeDeliveryData = $('#urlChangeDeliveryData');\n const searchParams = new URLSearchParams(window.location.href);\n\n if (urlChangeDeliveryData.length > 0 && searchParams.has('changeDate') && searchParams.get('changeDate') === 'true') {\n initializeChangeDeliveryDateModal(urlChangeDeliveryData.val());\n }\n\n $(document).on('click', '.js-dashboard-subscription-edit-delivery-button', function (e) {\n initializeChangeDeliveryDateModal($(e.currentTarget).attr('data-url'));\n });\n\n $(document).on('click', '.btn-update-delivery-date', function () {\n const $form = $('#changeDeliveryDateForm');\n const $modal = $('#changeDeliveryDateModal');\n const $error = $modal.find('.error-block');\n\n $modal.spinner().start();\n $error.addClass('d-none');\n\n $.ajax({\n url: $form.attr('action'),\n type: 'POST',\n dataType: 'JSON',\n data: $form.serialize(),\n success: function (response) {\n if (response.success) {\n if (new URLSearchParams(window.location.href).has('changeDate')) {\n window.location.href = removeChangeDateUrlParam();\n } else {\n location.reload();\n }\n } else {\n $error.removeClass('d-none');\n }\n\n $modal.spinner().stop();\n },\n error: function () {\n $error.removeClass('d-none');\n $modal.spinner().stop();\n }\n });\n });\n\n $(document).on('click', '.btn-cancel-update-delivery-date', function () {\n if (new URLSearchParams(window.location.href).has('changeDate')) {\n window.location.href = removeChangeDateUrlParam();\n } else {\n $('#changeDeliveryDateModal').modal('hide');\n }\n });\n\n function removeChangeDateUrlParam() {\n var updatedSearchParams = window.location.search.replace(/([?&])changeDate=[^&]+(&|$)/, '$1');\n return (window.location.origin + window.location.pathname + updatedSearchParams).toString().slice(0, -1);\n }\n\n function initializeChangeDeliveryDateModal(url) {\n $.spinner().start();\n\n $.ajax({\n url: url,\n type: 'GET',\n success: function (response) {\n if (response && response.length > 0) {\n const $container = SmartOrderRefill.creatContainer('#changeDelveryDatesContainer');\n\n $container.html(response);\n $container.find('.modal').modal({\n backdrop: 'static'\n });\n $container.find('.modal').modal('show');\n $container.find('.modal').on('hidden.bs.modal', function () {\n $container.remove();\n });\n\n const availableDates = JSON.parse($('#changeDeliveryDateModal').attr('data-available-dates'));\n const dayOfWeek = new Date(availableDates[0].date).getDay();\n\n var datePicker = new Lightpick({\n field: document.getElementById('subscriptionDeliveryDate'),\n singleDate: true,\n enabledDates: availableDates,\n minDate: moment().startOf('day').add(1, 'days'),\n maxDate: moment().startOf('day').add(32, 'days'),\n dropdowns: false,\n inline: true\n });\n\n datePicker.setDate(new Date($('#changeDeliveryDateModal').attr('data-next-refill-date')));\n\n if (dayOfWeek === 0 || dayOfWeek === 6) {\n $('.calendar-wrapper').addClass('boldWeekend');\n } else {\n $('.calendar-wrapper').addClass('boldWeekedays');\n }\n }\n $.spinner().stop();\n },\n error: function () {\n $.spinner().stop();\n }\n });\n }\n };\n\n /**\n * @private\n * @function\n * @description Binds events to the cart page (edit item's details, bonus item's actions, coupon code entry)\n */\n SmartOrderRefill.initialize = function () {\n SmartOrderRefill.initSubscriptionView();\n SmartOrderRefill.initOrderView();\n SmartOrderRefill.initAddressChangeForm();\n SmartOrderRefill.initCreditCardExpirationWarning();\n SmartOrderRefill.initChangeProductForm();\n SmartOrderRefill.initReactivateSubscriptionView();\n SmartOrderRefill.initReactivateOrderView();\n SmartOrderRefill.initUpdateProductQuantity();\n SmartOrderRefill.initRemoveProductFromSubscription();\n SmartOrderRefill.initRemoveProduct();\n SmartOrderRefill.initUpdateRefill();\n SmartOrderRefill.initModifyRefill();\n SmartOrderRefill.initRemoveRefill();\n SmartOrderRefill.initLoginFromCart();\n\n SmartOrderRefill.initLinkModel();\n\n SmartOrderRefill.initializePdp();\n SmartOrderRefill.initAccountSorView();\n SmartOrderRefill.initOpenSubscriptionDetails();\n SmartOrderRefill.initUpdateSubscription();\n SmartOrderRefill.initChangeProductQuantity();\n SmartOrderRefill.initChangeDeliveryDateModal();\n };\n\n\n $(document).ready(function () {\n SmartOrderRefill.initialize();\n if (typeof $.fn.dialog === 'undefined' && typeof $.fn.modal !== 'undefined') {\n SmartOrderRefillSettings.ModalType = 'modal';\n }\n\n $('.sorlink.visually-hidden').removeClass('visually-hidden');\n window.SmartOrderRefill = SmartOrderRefill;\n });\n}(window.jQuery));\n"],"sourceRoot":""}