/* Minification failed. Returning unminified contents.
(340,21): run-time error JS1004: Expected ';'
(340,31-32): run-time error JS1010: Expected identifier: (
(344,22): run-time error JS1004: Expected ';'
(553,24-32): run-time error JS1006: Expected ')': function
(553,36-37): run-time error JS1006: Expected ')': {
(562,40): run-time error JS1004: Expected ';'
(565,43): run-time error JS1004: Expected ';'
(582,5-6): run-time error JS1195: Expected expression: )
(588,1-2): run-time error JS1002: Syntax error: }
(588,2-3): run-time error JS1195: Expected expression: )
 */
ws.loginModal = function (text) {
    //make undefined text equal an empty string for easier conditionals later on
    text = typeof text === "undefined" ? "" : text;

    if (!$('.login-modal').exists()) {
        var $loading = $("<img src='/Content/img/misc/ajax-loader.gif' class='loader' />");

        var $modal = $("<div class='login-modal'></div>").append($loading);

        $modal.dialog({
            autoOpen: false,
            width: 550,
            modal: true,
            resizable: false,
            title: "Log in",
            close: function (event, ui) {
                $(this).dialog("destroy").remove();
            },
            open: function () {
                $('.form__password').each(function (i, el) {
                    const $this = $(el);
                    const $eye = $this.find('.form__passwordEye');
                    const $input = $this.find('input');

                    $eye.on('click', function () {
                        const type = $input.attr('type');
                        $eye.toggleClass('open');

                        $input.attr('type',
                            type == 'text' ? 'password' : 'text'
                        );
                    });
                });
            }
        });

        $.get("/account/logon",
            {
                returnUrl: window.location.pathname
            },
            function (htmlResult) {
                var modalHtml = "";

                if (text.length > 0) {

                    modalHtml += "<p>" + text + "</p>";

                }

                modalHtml += htmlResult;

                $(".login-modal")
                    .html(modalHtml)
                    .dialog("open");
            }
        );
    }
    else {

        $('.login-modal').dialog('open');

    }
};
;
/****************************************************************************
* WISHLIST
*****************************************************************************/
var wishlist = (function () {

    var init = function () {
        $(".wishListToggle").unbind("click");

        $('.wishListToggle').click(function () {

            var $icon = $(this).find('i');

            if ($icon.hasClass("icon-heart-full")) {

                wishlist.remove($(this).data('id'))
                    .then(function () {

                        $icon.addClass("icon-heart");

                        $icon.removeClass("icon-heart-full");

                    });

            } else {

                wishlist.add($(this).data('id'))
                    .then(result => {

                        if (result) {

                            $icon.removeClass("icon-heart");

                            $icon.addClass("icon-heart-full");

                        }
                    });
            }

            return false;
        });
    };

    var remove = function (productId) {

        return ws.post(
            "/Account/RemoveFromWishList",
            { productId }
        );
    };

    var add = function (productId) {

        return ws.post(
            "/Account/AddToWishlist",
            { id: productId }
        ).then(function (data) {

            if (data.message.toLowerCase() === "login") {

                ws.loginModal("Please login to use your wish list.");

                return false;
            }

            return true;
        });
    };

    return {
        init,
        remove,
        add
    };
}());;
/****************************************************************************
 * ZIP CODE WIDGET
 *****************************************************************************/
var zip = (function () {
	var $loading = $("<img src='/Content/img/misc/ajax-loader.gif' class='loader' />");

	var launch = function (callback) {
		zip.enterZipModal(callback);

		return false;
	};

	var enterZipModal = function (callback) {
		var $dialog = $('<div class="zip-widget"></div>')
			.append(`<div style='display:flex; justify-content: center'>
                <img src='/Content/img/misc/ajax-loader.gif' class='loader' />
            </div>`);

		let cbSaveData = function () {
			if (!$('#zipModal').validate().element('.zipModal')) {
				return;
			}

			$('#enterZipModalContinue').attr('disabled', true);

			$('#goToShipping').attr('disabled', true);

			zip.saveZip(
				$.trim($('#zipModal .zipModal').val()),
				$dialog,
				callback ? callback : ws.reload,
			);
		};

		$dialog.dialog({
			autoOpen: false,
			modal: true,
			width: 450,
			autoResize: true,
			resizable: false,
			title: 'Please enter your shipping zip code',
			buttons: {
				continue: {
					text: 'Continue',
					class: 'button button--block',
					id: 'enterZipModalContinue',
					click: cbSaveData,
				},
			},
			close: function (event, ui) {
				$(this).dialog('destroy').remove();
			},
		});

		$dialog.on('submit', 'form', function (event) {
			event.preventDefault();
			cbSaveData();
		});

		$dialog.dialog('open');

		ws.get('/Deliveryzip/ZipModal').then(function (data) {
			$dialog.html(data);
		});

		return false;
	};

	var storeLocatorZipModal = function (callback) {
		let _formSubmitted = false;
		let cbSaveData = function () {
			if (_formSubmitted || !$('#zipModal').validate().element('.zipModal')) {
				return;
			}

			_formSubmitted = true;

			$('#storeLocatorZipModalContinue').attr('disabled', true);

			zip.saveZip(
				$.trim($('#zipModal .zipModal').val()),
				$dialog,
				callback ? callback : ws.reload,
			);
		};

		var $dialog = $('<div class="zip-widget"></div>')
			.append(`<div style='display:flex; justify-content: center'>
                <img src='/Content/img/misc/ajax-loader.gif' class='loader' />
            </div>`);

		$dialog.dialog({
			autoOpen: false,
			modal: true,
			width: 450,
			autoResize: true,
			resizable: false,
			title: 'Find the store closest to you',
			buttons: {
				continue: {
					text: 'Continue',
					class: 'button button--block',
					id: 'storeLocatorZipModalContinue',
					click: cbSaveData,
				},
			},
			close: function (event, ui) {
				if (_formSubmitted) {
					$(this).dialog('destroy').remove();
				} else {
					// Set default zip, if form was not submitted
					zip.saveZip(undefined, $dialog, callback);
				}

				ws.loadingStop();
			},
			open: function () {
				_formSubmitted = false;
			},
		});

		$dialog.on('submit', 'form', function (event) {
			event.preventDefault();
			cbSaveData();
		});

		$dialog.dialog('open');

		ws.get('/Deliveryzip/ZipModal').then(function (data) {
			$dialog.html(data);
		});

		return false;
	};

	var changeZipSave = function (e) {
		e = window.event || e;

		var elem = e.target || e.srcElement;

		var form = $(elem).closest('.change-zip-form');

		form.validate({
			rules: {
				'change-zip-to': {
					required: true,
					zipcodeUS: true,
				},
			},
			messages: {
				'change-zip-to': {
					required: 'Required field',
					zipcodeUS: 'Enter a valid zipcode',
				},
			},
		});

		if (form.valid()) {
			form.find('.change-zip-inputs').append(ws.$loading.clone());

			zip.saveZip($.trim(form.find('[name="change-zip-to"]').val()), null, () =>
				window.location.reload(),
			);
		}

		return false;
	};

	var toggleChangeZip = function (e) {
		e = window.event || e;
		var elem = e.target || e.srcElement;

		var $container = $(elem).closest('.change-zip-container');
		var $theForm = $container.find('.change-zip-form');

		if ($container.hasClass('visible')) {
			$theForm.hide({
				duration: 200,
				direction: 'up',
				easing: 'linear',
				complete: function () {
					$(this).validate().resetForm();
				},
			});

			$container.removeClass('visible');
		} else {
			$theForm.show({
				duration: 200,
				direction: 'up',
				easing: 'linear',
			});

			$container.addClass('visible');
		}

		return false;
	};

	const DELIVERY_ZIP_URL = '/DeliveryZip/SetDeliveryZip';

	var saveZip = async function (zipCode, $dialogOrModal, callback) {
		$('#zip-change-error-message').html('');

		try {
			var result = await ws.post(DELIVERY_ZIP_URL, { zip: zipCode });

			if (!result.success) {
				if ($dialogOrModal) {
					$dialogOrModal.find('.loader').remove();
				}

				$('#zip-change-error-message').html(result.message);
				return;
			}

			if (!callback) {
				return;
			}

			callback(result.data);

			if (!$dialogOrModal) {
				return;
			}

			if (
				$dialogOrModal.hasClass('ui-dialog-content') &&
				$dialogOrModal.dialog('isOpen') === true
			) {
				$dialogOrModal.dialog('close');
			}

			if ($dialogOrModal.hasClass('modal') && $dialogOrModal.hasClass('in')) {
				$dialogOrModal.modal('hide');
			}
		} catch (error) {
			console.error('Error occurred while saving zip: ', error);
		}
	};

	var getZip = function () {
		return ws
			.post('/DeliveryZip/GetDeliveryZip')
			.then(function (data) {
				if (data.zipCode.toLowerCase() === 'no zip found') {
					return 0;
				}

				return data.zipCode;
			})
			.catch(function (error) {
				console.error('Error occurred while getting zip: ', error);
				throw error; // or handle the error in another way
			});
	};

	// a modal that asks the user to change their delivery zip or make a new shipping selection
	var checkZipsModal = function (zip) {
		var deliveryZip = zip;

		var $dialog = $('<div id="zipCheck"></div>').append(ws.$loading.clone());

		var yesOption = function () {
			$(document).off('keypress', keyPressOption);
			$('.shippingStepZipCodeChangeBtn').attr('disabled', true);

			ws.post('/DeliveryZip/SetDeliveryZip', {
				zip: $('#PostalCode').val(),
			}).then(function () {
				window.location.replace('/shoppingcart');
			});
		};

		var noOption = function () {
			$dialog.dialog('close');

			$('#PostalCode').val(deliveryZip);
		};

		var keyPressOption = function (e) {
			if (e.which == $.ui.keyCode.ENTER) {
				yesOption();
			}
		}

		$dialog.dialog({
			autoOpen: false,
			modal: true,
			width: 450,
			title: 'Shipping Zip Code Change',
			closeOnEscape: true,
			buttons: {
				Yes: {
					click: yesOption,
					text: 'Yes',
					class: 'button button--block | shippingStepZipCodeChangeBtn',
				},

				No: {
					click: noOption,
					text: 'No',
					class: 'button button--block button--border | shippingStepZipCodeChangeBtn',
				},
			},
			close: function (event, ui) {
				$(this).dialog('destroy').remove();
				$(document).off('keypress', keyPressOption);
			},
			open: function (event, ui) {
				$(this).closest('.ui-dialog').find('.ui-dialog-titlebar-close').hide();
			},
		});

		$dialog.dialog('open');

		$(document).keypress(keyPressOption);

		$('.ui-dialog :button').blur();

		var text =
			'<small>Changing your shipping zip code now affects your service & delivery options.</small><br/><br/><small>Would you like to return to your cart to change or confirm your delivery method and services using this new zip code?</small>';

		$dialog.html(text);
	};

	// a modal that asks the user to change their delivery zip or make a new shipping selection
	var changeZipCheckModal = function (financingInvolved) { 
		if (!financingInvolved) {
			financingInvolved = false;
		}

		var $dialog = $('<div id="changeZipCheck"></div>').append(ws.$loading.clone());

		var yesOption = function () {
			$dialog.remove();
			$(document).off('keypress', keyPressOption);
			zip.enterZipModal();
		};

		var noOption = function () {
			$dialog.remove();
		};

		var keyPressOption = function (e) {
			if (e.which == $.ui.keyCode.ENTER) {
				yesOption();
			}
		}

		$dialog.dialog({
			autoOpen: false,
			modal: true,
			width: 450,
			title: 'Shipping Zip Code Change',
			closeOnEscape: true,
			buttons: {
				yes: {
					click: yesOption,
					class: 'button button--block',
					text: 'Yes',
				},

				no: {
					click: noOption,
					text: 'No',
					class: 'button button--block button--border',
				},
			},
			close: function (event, ui) {
				$(this).dialog('destroy').remove();
				$(document).off('keypress', keyPressOption);
			},
		});

		$dialog.dialog('open');

		$(document).keypress(keyPressOption);

		$('.ui-dialog :button').blur();

		var text =
			'<small>Changing your shipping zip code now affects your ' +
			(financingInvolved ? 'financing, ' : '') +
			'service & delivery options.</small><br/><br/><small>You' +
			(financingInvolved ? 'r financing will be removed, and you' : '') +
			' will need to re-select your delivery method and services after entering this new zip code.</small><br/><br/><small>Would you like to continue?</small>';

		$dialog.html(text);
	};

	return {
		checkZipsModal,
		changeZipCheckModal,
		changeZipSave,
		enterZipModal,
		storeLocatorZipModal,
		getZip,
		launch,
		toggleChangeZip,
		saveZip,
	};
})();
;
$(document).ready(function () {
    const DEBOUNCE_DELAY = 300;
    const MIN_SEARCH_LENGTH = 2;

    const $form = $("#search-form");
    const $input = $form.find("input[type=text]");
    const suggestionUrl = $form.data("suggestions-url");

    $input.on(
        "input",
        debounce(async function () {
            const val = $input.val();

            if (!suggestionUrl) {
                return;
            }

            if (val.length > MIN_SEARCH_LENGTH) {
                try {
                    const token = await grecaptcha.execute(ws.googleReCaptchaV3SiteKey, {
                        action: "siteSearch",
                    });
                    const response = await $.ajax({
                        url: suggestionUrl,
                        type: 'POST',
                        data: {
                            siteSearchCaptchaResponse: token,
                            q: val
                        }
                    });

                    window.showSearchResults(response.results, response.suggested_terms, val);
                } catch (error) {
                    console.error('Error executing site search:', error);
                }
            } else {
                window.hideSearchResults();
            }
        }, DEBOUNCE_DELAY)
    );

    $form.on("submit", function () {
        ws.loadingStart();
        window.hideSearchResults();
    });
});;
