(function ($) {

  $(document).ready(function () {

    /* =====================================
       1) CATEGORY -> SUBCATEGORY
    ===================================== */
    var $category = $('#wcmv-category');
    var $subcategoryWrap = $('#wcmv-subcategory-wrap');
    var $subcategory = $('#wcmv-subcategory');

    function syncSubcategories() {
      if (!$category.length || !$subcategory.length || !$subcategoryWrap.length) {
        return;
      }

      var parentId = parseInt($category.val(), 10) || 0;
      var hasVisibleOption = false;

      $subcategory.find('option').each(function () {
        var $opt = $(this);
        var optVal = $opt.val();
        if (!optVal) {
          return;
        }

        var optParent = parseInt($opt.data('parent'), 10) || 0;
        var visible = (parentId > 0 && optParent === parentId);
        $opt.prop('hidden', !visible);
        $opt.prop('disabled', !visible);

        if (!visible && $opt.is(':selected')) {
          $opt.prop('selected', false);
        }
        if (visible) {
          hasVisibleOption = true;
        }
      });

      if (parentId > 0 && hasVisibleOption) {
        $subcategoryWrap.removeClass('wcmv-hidden');
        $subcategory.prop('disabled', false);
      } else {
        $subcategoryWrap.addClass('wcmv-hidden');
        $subcategory.prop('disabled', true).val('');
      }
    }

    if ($category.length) {
      $category.on('change', syncSubcategories);
      syncSubcategories();
    }

    /* =====================================
       2️⃣ LISTING TYPE TOGGLER (ALWAYS RUNS)
    ===================================== */

    var $typeInput = $('#wcmv-listing-type');
    if (!$typeInput.length) return;
    var $modeTabs = $('[data-wcmv-mode-tab]');
    var $auctionBuyNowToggleWrap = $('#wrap-auction-buy-now-toggle');
    var $auctionBuyNowToggle = $('#wcmv-auction-enable-buy-now');

    var $startWrap   = $('#wrap-start-price');
    var $buyNowWrap  = $('#wrap-buy-now');
    var $acceptOffersWrap = $('#wrap-accept-offers');
    var $endWrap     = $('#wrap-end-date');

    var $startInput  = $('#start-price');
    var $buyNowInput = $('#buy-now-price');
    var $acceptOffersInput = $('#wcmv-accept-offers');
    var $endInput    = $('#end-date');
    var buyNowReadonlyClass = 'wcmv-readonly-input';

    function hide($wrap, $input) {
      if ($wrap.length) $wrap.addClass('wcmv-hidden');
      if ($input && $input.length) {
        // Keep existing value so edit forms remain populated when toggling modes.
        $input.prop({ required: false });
      }
    }

    function show($wrap, $input, required) {
      if ($wrap.length) $wrap.removeClass('wcmv-hidden');
      if ($input && $input.length) {
        $input.prop({ required: !!required });
      }
    }

    function setTabs(tabName) {
      $modeTabs.each(function () {
        var isActive = $(this).data('wcmv-mode-tab') === tabName;
        $(this).toggleClass('is-active', isActive).attr('aria-selected', isActive ? 'true' : 'false');
      });
    }

    function setBuyNowEnabled(enabled, required) {
      if (!$buyNowInput.length) return;
      $buyNowInput.prop({ required: !!required, disabled: !enabled });
      $buyNowInput.toggleClass(buyNowReadonlyClass, !enabled);

      if ($acceptOffersWrap.length) {
        $acceptOffersWrap.toggleClass('wcmv-hidden', !enabled);
      }
      if ($acceptOffersInput.length) {
        $acceptOffersInput.prop('disabled', !enabled);
        if (!enabled) {
          $acceptOffersInput.prop('checked', false);
        }
      }
    }

    function applyMode() {
      var type = $typeInput.val();
      var isBuyNowOnly = (type === 'buy_now_only');
      var isAuctionBuyNow = (type === 'auction_buy_now');

      hide($startWrap, $startInput);
      hide($buyNowWrap, $buyNowInput);
      hide($endWrap, $endInput);

      if (isBuyNowOnly) {
        setTabs('buy_now');
        if ($auctionBuyNowToggleWrap.length) $auctionBuyNowToggleWrap.addClass('wcmv-hidden');
        if ($auctionBuyNowToggle.length) $auctionBuyNowToggle.prop('checked', false);
        show($buyNowWrap, $buyNowInput, true);
        setBuyNowEnabled(true, true);
        return;
      }

      // Auction tab (auction_only or auction_buy_now)
      setTabs('auction');
      if ($auctionBuyNowToggleWrap.length) $auctionBuyNowToggleWrap.removeClass('wcmv-hidden');
      if ($auctionBuyNowToggle.length) $auctionBuyNowToggle.prop('checked', isAuctionBuyNow);

      show($startWrap, $startInput, true);
      show($buyNowWrap, $buyNowInput, false);
      show($endWrap, $endInput, true);
      setBuyNowEnabled(isAuctionBuyNow, false);
    }

    $modeTabs.on('click', function () {
      var tab = $(this).data('wcmv-mode-tab');
      if (tab === 'buy_now') {
        $typeInput.val('buy_now_only');
      } else {
        $typeInput.val($auctionBuyNowToggle.is(':checked') ? 'auction_buy_now' : 'auction_only');
      }
      applyMode();
    });

    $auctionBuyNowToggle.on('change', function () {
      $typeInput.val($(this).is(':checked') ? 'auction_buy_now' : 'auction_only');
      applyMode();
    });

    if (!$typeInput.val()) {
      $typeInput.val('auction_only');
    }
    applyMode();

    /* =====================================
       3) SHIPPING MODE TOGGLER
    ===================================== */
    var $shippingMode = $('#wcmv-shipping-mode');
    if ($shippingMode.length) {
      var $costWrap = $('#wcmv-wrap-shipping-cost');
      var $costInput = $('#wcmv-shipping-cost');
      var $shippingHint = $('#wcmv-shipping-mode-hint');
      var siteName = String($shippingMode.data('site-name') || '').trim();

      var $weightWrap = $('#wcmv-wrap-shipping-weight');
      var $lengthWrap = $('#wcmv-wrap-shipping-length');
      var $widthWrap = $('#wcmv-wrap-shipping-width');
      var $heightWrap = $('#wcmv-wrap-shipping-height');
      var $carrierWrap = $('#wcmv-wrap-shipping-carrier');
      var $scopeWrap = $('#wcmv-wrap-shipping-scope');
      var $scopeSelect = $('#wcmv-shipping-scope');
      var $countriesWrap = $('#wcmv-wrap-shipping-countries');
      var $countriesInputs = $('#wcmv-wrap-shipping-countries input[type="checkbox"]');

      var $weightInput = $('#wcmv-shipping-weight');
      var $lengthInput = $('#wcmv-shipping-length');
      var $widthInput = $('#wcmv-shipping-width');
      var $heightInput = $('#wcmv-shipping-height');

      function setFieldState($wrap, $input, showField, required) {
        if ($wrap.length) {
          $wrap.toggleClass('wcmv-hidden', !showField);
        }
        if ($input && $input.length) {
          $input.prop('required', !!required);
        }
      }

      function applyShippingHint(mode) {
        if (!$shippingHint.length) return;
        var text = '';

        if (mode === 'calculated') {
          text = 'Let ' + siteName + ' calculate based on buyers address';
        } else if (mode === 'flat') {
          text = 'Set fixed shipping cost';
        } else if (mode === 'free') {
          text = 'Free shipping';
        } else if (mode === 'pickup_only') {
          text = 'Pickup only';
        }

        $shippingHint.text(text);
        $shippingHint.toggle(!!text);
      }

      function applyShippingMode() {
        var mode = $shippingMode.val() || '';
        var isCalculated = mode === 'calculated';
        var isFlat = mode === 'flat';
        var isPickupOnly = mode === 'pickup_only';
        var hasSelection = mode === 'calculated' || mode === 'flat' || mode === 'free' || mode === 'pickup_only';

        applyShippingHint(mode);

        if (!hasSelection) {
          setFieldState($costWrap, $costInput, false, false);
          setFieldState($weightWrap, $weightInput, false, false);
          setFieldState($lengthWrap, $lengthInput, false, false);
          setFieldState($widthWrap, $widthInput, false, false);
          setFieldState($heightWrap, $heightInput, false, false);
          if ($carrierWrap.length) {
            $carrierWrap.addClass('wcmv-hidden');
          }
          if ($scopeWrap.length) {
            $scopeWrap.addClass('wcmv-hidden');
          }
          if ($countriesWrap.length) {
            $countriesWrap.addClass('wcmv-hidden');
          }
          if ($countriesInputs.length) {
            $countriesInputs.prop('disabled', true);
          }
          if ($scopeSelect.length) {
            $scopeSelect.prop('disabled', true);
          }
          return;
        }

        setFieldState($costWrap, $costInput, isFlat, isFlat);

        setFieldState($weightWrap, $weightInput, isCalculated, isCalculated);
        setFieldState($lengthWrap, $lengthInput, isCalculated, isCalculated);
        setFieldState($widthWrap, $widthInput, isCalculated, isCalculated);
        setFieldState($heightWrap, $heightInput, isCalculated, isCalculated);

        if ($carrierWrap.length) {
          $carrierWrap.toggleClass('wcmv-hidden', !isCalculated);
        }

        if ($scopeWrap.length) {
          $scopeWrap.toggleClass('wcmv-hidden', isPickupOnly);
        }
        if ($scopeSelect.length) {
          $scopeSelect.prop('disabled', isPickupOnly);
        }

        var scope = $scopeSelect.length ? ($scopeSelect.val() || 'international') : 'international';
        var showAllowedCountries = !isPickupOnly && scope === 'selected';

        if ($countriesWrap.length) {
          $countriesWrap.toggleClass('wcmv-hidden', !showAllowedCountries);
        }
        if ($countriesInputs.length) {
          $countriesInputs.prop('disabled', !showAllowedCountries);
        }
      }

      if ($scopeSelect.length) {
        $scopeSelect.on('change', applyShippingMode);
      }
      $shippingMode.on('change', applyShippingMode);
      applyShippingMode();
    }

    /* =====================================
       4) RETURNS POLICY TOGGLER
    ===================================== */
    var $returnsPolicy = $('#wcmv-returns-policy');
    if ($returnsPolicy.length) {
      var $returnsDaysWrap = $('#wcmv-wrap-returns-days');
      var $returnsDaysInput = $('#wcmv-returns-days');
      var $returnShippingWrap = $('#wcmv-wrap-return-shipping-paid-by');
      var $returnShippingSelect = $('#wcmv-return-shipping-paid-by');

      function applyReturnsPolicy() {
        var acceptsReturns = ($returnsPolicy.val() === 'returns_accepted');

        if ($returnsDaysWrap.length) {
          $returnsDaysWrap.toggleClass('wcmv-hidden', !acceptsReturns);
        }
        if ($returnsDaysInput.length) {
          $returnsDaysInput.prop('required', acceptsReturns);
        }

        if ($returnShippingWrap.length) {
          $returnShippingWrap.toggleClass('wcmv-hidden', !acceptsReturns);
        }
        if ($returnShippingSelect.length) {
          $returnShippingSelect.prop('disabled', !acceptsReturns);
        }
      }

      $returnsPolicy.on('change', applyReturnsPolicy);
      applyReturnsPolicy();
    }

    /* =====================================
       5) FAQ BUILDER
    ===================================== */
    var $addFaq = $('#wcmv-add-faq');
    var $faqList = $('#wcmv-faq-list');
    if ($addFaq.length && $faqList.length) {
      function createFaqItem() {
        return $(
          '<div class="wcmv-faq-item">' +
            '<div class="wcmv-field full">' +
              '<label>Question</label>' +
              '<input type="text" name="faq_question[]" placeholder="Type a common buyer question">' +
            '</div>' +
            '<div class="wcmv-field full">' +
              '<label>Answer</label>' +
              '<textarea name="faq_answer[]" rows="3" placeholder="Type the answer"></textarea>' +
            '</div>' +
            '<button type="button" class="wcmv-remove-faq wcmv-secondary-btn">Remove</button>' +
          '</div>'
        );
      }

      $addFaq.on('click', function () {
        $faqList.removeClass('wcmv-hidden');
        $faqList.append(createFaqItem());
      });

      $faqList.on('click', '.wcmv-remove-faq', function () {
        $(this).closest('.wcmv-faq-item').remove();
        if ($faqList.find('.wcmv-faq-item').length === 0) {
          $faqList.addClass('wcmv-hidden');
        }
      });
    }

  });

})(jQuery);

/* =====================================
   CREATE/EDIT LISTING IMAGE MANAGER
===================================== */
document.addEventListener('DOMContentLoaded', function () {

  var input = document.getElementById('wcmv-images');
  var preview = document.getElementById('wcmv-image-preview');
  var removedInput = document.getElementById('wcmv-removed-images');
  var orderInput = document.getElementById('wcmv-image-order');
  var existingImagesInput = document.getElementById('wcmv-existing-images-json');
  var editorModal = document.getElementById('wcmv-image-editor-modal');
  var editorStage = document.getElementById('wcmv-image-editor-stage');
  var rotateLeftBtn = document.getElementById('wcmv-image-rotate-left');
  var rotateRightBtn = document.getElementById('wcmv-image-rotate-right');
  var cancelEditBtn = document.getElementById('wcmv-image-cancel');
  var applyEditBtn = document.getElementById('wcmv-image-apply');

  if (!input || !preview || typeof Sortable === 'undefined') return;

  var MAX_IMAGES = 12;
  var filesStore = [];
  var removedExisting = [];
  var cropper = null;
  var pendingImageSave = null;

  function uniquePush(arr, value) {
    if (arr.indexOf(value) === -1) arr.push(value);
  }

  function closeEditor() {
    if (cropper) {
      cropper.destroy();
      cropper = null;
    }
    if (editorStage) editorStage.innerHTML = '';
    if (editorModal) editorModal.classList.add('wcmv-hidden');
    pendingImageSave = null;
  }

  function rotateCropper(degrees) {
    if (!cropper) {
      return;
    }

    // Cropper.js v1 API.
    if (typeof cropper.rotate === 'function') {
      cropper.rotate(degrees);
      return;
    }

    // Cropper.js v2 API via the <cropper-image> element.
    if (typeof cropper.getCropperImage === 'function') {
      var imageEl = cropper.getCropperImage();
      if (imageEl && typeof imageEl.$rotate === 'function') {
        imageEl.$rotate(degrees);
      }
    }
  }

  function exportCroppedCanvas(done) {
    if (!cropper || typeof done !== 'function') {
      done(null);
      return;
    }

    // Cropper.js v1 API.
    if (typeof cropper.getCroppedCanvas === 'function') {
      var v1Canvas = cropper.getCroppedCanvas({
        maxWidth: 2200,
        maxHeight: 2200,
        imageSmoothingQuality: 'high'
      });
      done(v1Canvas || null);
      return;
    }

    // Cropper.js v2 API.
    if (typeof cropper.getCropperSelection === 'function') {
      var selection = cropper.getCropperSelection();
      if (selection && typeof selection.$toCanvas === 'function') {
        selection.$toCanvas({ width: 2200, height: 2200 }).then(function (canvas) {
          done(canvas || null);
        }).catch(function () {
          done(null);
        });
        return;
      }
    }

    done(null);
  }

  function openEditor(src, onSave) {
    if (!editorModal || !editorStage || typeof Cropper === 'undefined') {
      return;
    }

    pendingImageSave = onSave;
    editorStage.innerHTML = '';
    editorModal.classList.remove('wcmv-hidden');

    var img = document.createElement('img');
    img.src = src;
    img.alt = 'Edit image';
    editorStage.appendChild(img);

    cropper = new Cropper(img, {
      viewMode: 1,
      autoCropArea: 1,
      background: false,
      responsive: true
    });
  }

  var existingImages = [];
  if (existingImagesInput && existingImagesInput.value) {
    try {
      var parsedImages = JSON.parse(existingImagesInput.value);
      if (Array.isArray(parsedImages)) {
        existingImages = parsedImages;
      }
    } catch (err) {
      existingImages = [];
    }
  }

  if (existingImages.length) {
    existingImages.forEach(function (img) {
      var div = document.createElement('div');
      div.className = 'wcmv-thumb';
      div.dataset.existingId = img.id;
      div.innerHTML =
        '<img src="' + img.url + '">' +
        '<button type="button" class="wcmv-remove-image">&times;</button>' +
        '<button type="button" class="wcmv-edit-image">Edit</button>';
      preview.appendChild(div);
    });
  }

  function refreshInputFiles() {
    if (typeof DataTransfer === 'undefined') return;
    var dt = new DataTransfer();
    filesStore.forEach(function (f) { dt.items.add(f); });
    input.files = dt.files;
  }

  function updateImageOrder() {
    if (!orderInput) return;
    var order = [];
    preview.querySelectorAll('.wcmv-thumb').forEach(function (el) {
      if (el.dataset.existingId) order.push(el.dataset.existingId);
    });
    orderInput.value = order.join(',');
  }

  function renderNewFiles() {
    preview.querySelectorAll('[data-new]').forEach(function (n) { n.remove(); });

    filesStore.forEach(function (file, index) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var div = document.createElement('div');
        div.className = 'wcmv-thumb';
        div.dataset.index = index;
        div.dataset.new = '1';
        div.innerHTML =
          '<img src="' + e.target.result + '">' +
          '<button type="button" class="wcmv-remove-image">&times;</button>' +
          '<button type="button" class="wcmv-edit-image">Edit</button>';
        preview.appendChild(div);
      };
      reader.readAsDataURL(file);
    });

    updateImageOrder();
  }

  input.addEventListener('change', function () {
    var existingCount = preview.querySelectorAll('.wcmv-thumb[data-existing-id]').length;
    Array.from(input.files).forEach(function (file) {
      if (filesStore.length + existingCount < MAX_IMAGES) {
        filesStore.push(file);
      }
    });
    refreshInputFiles();
    renderNewFiles();
  });

  preview.addEventListener('click', function (e) {
    var thumb = e.target.parentElement;
    if (!thumb || !thumb.classList.contains('wcmv-thumb')) return;

    if (e.target.classList.contains('wcmv-remove-image')) {
      if (thumb.dataset.existingId) {
        uniquePush(removedExisting, thumb.dataset.existingId);
        if (removedInput) removedInput.value = removedExisting.join(',');
      }

      if (thumb.dataset.index !== undefined) {
        filesStore.splice(Number(thumb.dataset.index), 1);
        refreshInputFiles();
      }

      thumb.remove();
      renderNewFiles();
      return;
    }

    if (e.target.classList.contains('wcmv-edit-image')) {
      var imgEl = thumb.querySelector('img');
      if (!imgEl) return;

      openEditor(imgEl.src, function (newFile) {
        if (!newFile) return;

        if (thumb.dataset.index !== undefined) {
          filesStore[Number(thumb.dataset.index)] = newFile;
        } else if (thumb.dataset.existingId) {
          uniquePush(removedExisting, thumb.dataset.existingId);
          if (removedInput) removedInput.value = removedExisting.join(',');
          thumb.remove();
          filesStore.push(newFile);
        }

        refreshInputFiles();
        renderNewFiles();
      });
    }
  });

  new Sortable(preview, {
    animation: 150,
    ghostClass: 'wcmv-dragging',
    onEnd: updateImageOrder
  });

  updateImageOrder();

  if (rotateLeftBtn) {
    rotateLeftBtn.addEventListener('click', function () {
      rotateCropper(-90);
    });
  }

  if (rotateRightBtn) {
    rotateRightBtn.addEventListener('click', function () {
      rotateCropper(90);
    });
  }

  if (cancelEditBtn) {
    cancelEditBtn.addEventListener('click', function () {
      closeEditor();
    });
  }

  if (applyEditBtn) {
    applyEditBtn.addEventListener('click', function () {
      if (!cropper || typeof pendingImageSave !== 'function') {
        closeEditor();
        return;
      }

      exportCroppedCanvas(function (canvas) {
        if (!canvas) {
          closeEditor();
          return;
        }

        canvas.toBlob(function (blob) {
          if (!blob) {
            closeEditor();
            return;
          }
          var fileName = 'edited-' + Date.now() + '.jpg';
          var editedFile = new File([blob], fileName, { type: 'image/jpeg' });
          pendingImageSave(editedFile);
          closeEditor();
        }, 'image/jpeg', 0.92);
      });
    });
  }

  if (editorModal) {
    editorModal.addEventListener('click', function (evt) {
      if (evt.target === editorModal) {
        closeEditor();
      }
    });
  }
});

jQuery(function ($) {
  var $form = $('#stakmv-create-listing-form');
  if (!$form.length) return;
  var createCfg =
    (typeof STAKMV_CREATE !== 'undefined' && STAKMV_CREATE) ? STAKMV_CREATE :
    ((typeof STAKMV_CREATE !== 'undefined' && STAKMV_CREATE) ? STAKMV_CREATE : null);
  var ajaxUrl = (createCfg && createCfg.ajax) ? createCfg.ajax : '';
  var clickedSubmitAction = '';

  $form.on('click', 'button[type="submit"][name]', function () {
    clickedSubmitAction = this.name || '';
  });

  $form.on('submit', function (e) {
    if ($form.data('submitting')) {
      return false;
    }

    var submitter = (e.originalEvent && e.originalEvent.submitter) ? e.originalEvent.submitter : document.activeElement;
    var actionName = (submitter && submitter.name) ? submitter.name : clickedSubmitAction;

    if (!actionName) {
      actionName = 'stakmv_create_listing';
    }
    if (actionName !== 'stakmv_create_listing' && actionName !== 'stakmv_delete_listing') {
      actionName = 'stakmv_create_listing';
    }

    if (actionName === 'stakmv_delete_listing' && !window.confirm('Delete this listing?')) {
      return false;
    }

    if (!$form.find('input[type="hidden"][name="' + actionName + '"]').length) {
      $('<input>', { type: 'hidden', name: actionName, value: '1' }).appendTo($form);
    }

    $form.data('submitting', true);

    var $createBtn = $('#wcmv-create-submit');
    var $deleteBtn = $('button[name="stakmv_delete_listing"]');
    var $status = $('#wcmv-submit-status');
    var messageTimer;
    var reassuranceTimer;
    var hasImages = false;
    var messages = [
      'Preparing your listing...',
      'Saving item details...',
      'Almost done, publishing your listing...'
    ];

    if ($('#wcmv-images').length && $('#wcmv-images')[0].files && $('#wcmv-images')[0].files.length > 0) {
      hasImages = true;
    }

    if ($('#wcmv-existing-images-json').length && $('#wcmv-existing-images-json').val()) {
      hasImages = true;
    }

    if (hasImages) {
      messages.splice(1, 0, 'Uploading photos...');
    }

    $createBtn.prop('disabled', true);
    $deleteBtn.prop('disabled', true);

    if ($createBtn.length) {
      $createBtn.data('original-text', $createBtn.text());
      $createBtn.text(actionName === 'stakmv_delete_listing' ? 'Deleting...' : 'Saving...');
    }

    if (actionName === 'stakmv_create_listing' && $status.length) {
      var idx = 0;
      $status.removeClass('wcmv-hidden').text(messages[idx]);

      messageTimer = setInterval(function () {
        idx = (idx + 1) % messages.length;
        $status.text(messages[idx]);
      }, 2200);

      reassuranceTimer = setTimeout(function () {
        $status.text('Still working - slower internet can take longer. Please keep this page open.');
      }, 12000);

      $(window).one('beforeunload', function () {
        clearInterval(messageTimer);
        clearTimeout(reassuranceTimer);
      });
    }

    // Keep delete as normal form submit; create/update uses AJAX for live status updates.
    if (actionName !== 'stakmv_create_listing') {
      return true;
    }

    e.preventDefault();

    if (!ajaxUrl) {
      clearInterval(messageTimer);
      clearTimeout(reassuranceTimer);
      $status.removeClass('wcmv-hidden').text('Could not start save request. Please refresh and try again.');
      $createBtn.prop('disabled', false).text($createBtn.data('original-text') || 'List Item');
      $deleteBtn.prop('disabled', false);
      $form.data('submitting', false);
      return false;
    }

    var formData = new FormData($form[0]);
    formData.set('action', 'stakmv_save_listing');

    $.ajax({
      url: ajaxUrl,
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json'
    }).done(function (res) {
      if (res && res.success && res.data && res.data.redirect) {
        window.location.href = res.data.redirect;
        return;
      }

      var msg = (res && res.data && res.data.message) ? res.data.message : 'Unable to save listing right now. Please try again.';
      clearInterval(messageTimer);
      clearTimeout(reassuranceTimer);
      $status.removeClass('wcmv-hidden').text(msg);
      $createBtn.prop('disabled', false).text($createBtn.data('original-text') || 'List Item');
      $deleteBtn.prop('disabled', false);
      $form.data('submitting', false);
    }).fail(function (xhr) {
      var msg = 'Unable to save listing right now. Please try again.';
      if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
        msg = xhr.responseJSON.data.message;
      }
      clearInterval(messageTimer);
      clearTimeout(reassuranceTimer);
      $status.removeClass('wcmv-hidden').text(msg);
      $createBtn.prop('disabled', false).text($createBtn.data('original-text') || 'List Item');
      $deleteBtn.prop('disabled', false);
      $form.data('submitting', false);
    });

    return false;
  });
});
