var loadScript = function (url, callback) {
  /* JavaScript that will load the jQuery library on Google's CDN.
     We recommend this code: http://snipplr.com/view/18756/loadscript/.
     Once the jQuery library is loaded, the function passed as argument,
     callback, will be executed. */
  var preorderProductCopy
  var script = document.createElement('script')
  script.type = 'text/javascript'

  if (script.readyState) {
    //IE
    script.onreadystatechange = function () {
      if (script.readyState == 'loaded' || script.readyState == 'complete') {
        script.onreadystatechange = null
        callback()
      }
    }
  } else {
    //Others
    script.onload = function () {
      callback()
    }
  }

  script.src = url
  document.getElementsByTagName('head')[0].appendChild(script)
}

var myFrontendJavascript = function ($) {
  var BUY_NOW_BUTTON_SELECTOR = '.shopify-payment-button'
  var PN_ACTIVE_CLASS = 'preorder-now-active'

  var buttonClicked = false

  // pre stock limit
  var eventCount = 0
  var hasValidData = false
  var hasLimitReachForVarint = false
  var crtItems = []
  getItems()

  function getItems() {
    $.ajax({
      method: 'GET',
      url: '/cart.js',
      dataType: 'json',
      async: false,
      contentType: 'application/json; charset=utf-8',
      success: function (data) {
        crtItems = data
      },
    })
  }

  ForSupplyTheme()

  function ForSupplyTheme() {
    var variant
    var current = $(this)
    var variants_ids = []
    var variant_indx
    var variant_id
    var curr_input
    var isvalid = true
    var alerted = true

    if (
      window.pn.shop.limit_order_quantity ||
      window.pn.shop.notify_when_partial_preorder
    ) {
      if (
        $("form[action='/cart']").find("input[name^='updates[']").length == 0
      ) {
        $('body').on('click', "button[name='checkout']", function (event) {
          $("form[action='/cart']")
            .find('img')
            .each(function () {
              if ($($(this).parent()[0]).attr('href') == undefined) {
                isvalid = false
                return false
              }
              variant_indx = $($(this).parent()[0]).attr('href').split('=')
              variant_id = $($(this).parent()[0]).attr('href').split('=')[
                variant_indx.length - 1
              ]
              variants_ids.push(variant_id)
            })
          if (hasValidData == false && isvalid == true) {
            event.preventDefault()
            $.ajax({
              method: 'get',
              url: getServerAddress() + '/widget/variant_collection',
              data: { ids: variants_ids },
              success: function (data) {
                $("form[action='/cart']")
                  .find('img')
                  .each(function () {
                    variant_indx = $($(this).parent()[0])
                      .attr('href')
                      .split('=')
                    variant_id = $($(this).parent()[0]).attr('href').split('=')[
                      variant_indx.length - 1
                    ]
                    variant = data[variant_id]
                    curr_input = $(this)
                      .parent()
                      .parent()
                      .parent()
                      .parent()
                      .parent()
                      .find('input')
                    hasValidData = stockLimitForCheckout(variant, curr_input)
                  })
                if (hasValidData == false) {
                  alerted = false
                }
                if (hasValidData && alerted) {
                  $("button[name='checkout']").trigger('click')
                }
              },
            })
          }
        })
      }
    }
  }

  if (
    window.pn.shop.limit_order_quantity ||
    window.pn.shop.notify_when_partial_preorder
  ) {
    $('body').on(
      'click',
      '.js--qty-adjuster, .js-qty__adjust, .js-change-quantity, .ajaxifyCart--add, .ajaxifyCart--minus, .ajaxcart__qty-adjust',
      function (e) {
        var that = $(this)
        var quantity
        hasValidData = false
        if (quantity == undefined) {
          that.parent().find("input[name^='updates[']").trigger('change')
          that.parent().find('.ajaxifyCart--num').trigger('change')
        }

        function updateQuantity(line, qty) {
          isUpdating = true

          // Add activity classes when changing cart quantities
          if (!settings.useCartTemplate) {
            var row = $('.ajaxifyCart--row[data-line="' + line + '"]').addClass(
              'ajaxifyCart--is-loading'
            )
          } else {
            var row = $('.cart-row[data-line="' + line + '"]').addClass(
              'ajaxifyCart--is-loading'
            )
          }

          if (qty === 0) {
            row.addClass('is-removed')
          }

          // Slight delay to make sure removed animation is done
          setTimeout(function () {
            Shopify.changeItem(line, qty, adjustCartCallback)
          }, 250)
        }

        Shopify.changeItem = function (line, quantity, callback) {
          quantity = quantity
          var params = {
            type: 'POST',
            url: '/cart/change.js',
            data: 'quantity=' + quantity + '&line=' + line,
            dataType: 'json',
            success: function (cart) {
              if (typeof callback === 'function') {
                callback(cart)
              } else {
                Shopify.onCartUpdate(cart)
              }
              if (that != false) {
                that
                  .parent()
                  .find("input[name^='updates[']")
                  .val(quantity)
                  .trigger('change')
                that
                  .parent()
                  .find('.ajaxifyCart--num')
                  .val(quantity)
                  .trigger('change')
                that = false
              }
            },
            error: function (XMLHttpRequest, textStatus) {
              Shopify.onError(XMLHttpRequest, textStatus)
            },
          }
          jQuery.ajax(params)
        }
      }
    )

    $("button[name='checkout']").click(function (event) {
      var variant
      var current = $(this)
      var variants_ids = []
      var alerted = true
      $("form[action='/cart']")
        .find("input[name^='updates[']")
        .each(function () {
          if ($(this).data('id') != undefined) {
            variants_ids.push(
              $(this)
                .data('id')
                .toString()
                .split(':')[0]
                .replace(/[^0-9]/g, '')
            )
          } else {
            variants_ids.push(
              $(this)
                .attr('id')
                .toString()
                .split(':')[0]
                .replace(/[^0-9]/g, '')
            )
          }
        })
      // for narrative
      if ($(this).hasClass('cart-drawer__checkout')) {
        hasValidData = true
      }
      if (hasValidData == false) {
        event.preventDefault()
        $.ajax({
          method: 'get',
          url: getServerAddress() + '/widget/variant_collection',
          data: { ids: variants_ids },
          success: function (data) {
            $("form[action='/cart']")
              .find("input[name^='updates[']")
              .each(function () {
                if ($(this).data('id') != undefined) {
                  variant =
                    data[
                      $(this)
                        .data('id')
                        .toString()
                        .split(':')[0]
                        .replace(/[^0-9]/g, '')
                    ]
                  hasValidData = stockLimitForCheckout(variant, $(this))
                } else {
                  variant =
                    data[
                      $(this)
                        .attr('id')
                        .toString()
                        .split(':')[0]
                        .replace(/[^0-9]/g, '')
                    ]
                  hasValidData = stockLimitForCheckout(variant, $(this))
                }
                if (hasValidData == false) {
                  alerted = false
                }
              })
            if (hasValidData && alerted) {
              $("button[name='checkout']").trigger('click')
            }
          },
        })
      }
    })

    // partially match name
    $('body').on(
      'change',
      "input[name^='updates['], .ajaxifyCart--num",
      function () {
        hasValidData = false
        var var_img
        var variant_id
        if ($(this).data('id') != undefined && $(this).data('id') != '') {
          variant_id = $(this)
            .data('id')
            .toString()
            .split(':')[0]
            .replace(/[^0-9]/g, '')
        } else if (
          $(this).attr('id') != undefined &&
          $(this).data('id') != ''
        ) {
          variant_id = $(this)
            .attr('id')
            .toString()
            .split(':')[0]
            .replace(/[^0-9]/g, '')
        } else {
          // added this only for supply theme
          var_img = $(this)
            .parent()
            .parent()
            .parent()
            .parent()
            .parent()
            .find('img')
            .parent()
            .attr('href')
            .split('=')
          variant_id = var_img[var_img.length - 1]
        }
        var curr = $(this)
        $.ajax({
          url: getServerAddress() + '/widget/get_variant_settings_for_cart',
          data: { variant_id: variant_id },
          method: 'get',
          success: function (data) {
            if (
              data.id != undefined &&
              data.preorder_stock != null &&
              data.use_shopify_stock_management == false &&
              parseInt(curr.val()) > data.preorder_stock
            ) {
              inputChangeTrigger(curr, data.preorder_stock, variant_id)
            } else if (
              data.id != undefined &&
              data.shopify_preorder_limit != null &&
              data.shopify_stock_mgmt_method == 2 &&
              data.use_shopify_stock_management == true
            ) {
              if (
                parseInt(curr.val().replace(/[^0-9]/g, '')) >
                data.shopify_preorder_limit
              ) {
                inputChangeTrigger(
                  curr,
                  data.shopify_preorder_limit,
                  variant_id
                )
              }
            }
          },
        })
      }
    )
  }

  function stockLimitForCheckout(variant, current) {
    var result = true
    if (variant != undefined && variant.length != undefined) {
      var ind = variant.length - 1
      if (
        variant &&
        variant[ind].preorder_stock != null &&
        variant[ind].use_shopify_stock_management == false
      ) {
        if (
          parseInt(current.val().replace(/[^0-9]/g, '')) >
          variant[ind].preorder_stock
        ) {
          result = false
          stockAlert(current, variant[ind], variant[ind].preorder_stock)
        }
      } else if (
        variant &&
        variant[ind].shopify_preorder_limit != null &&
        variant[ind].shopify_stock_mgmt_method == 2 &&
        variant[ind].use_shopify_stock_management == true
      ) {
        if (
          parseInt(current.val().replace(/[^0-9]/g, '')) >
          variant[ind].shopify_preorder_limit
        ) {
          result = false
          stockAlert(current, variant[ind], variant[ind].shopify_preorder_limit)
        }
      }
    }
    return result
  }

  function stockAlert(current, variant, stock_val) {
    current.val(stock_val)
    current.attr('value', stock_val)
    current.trigger('change')
    insufficientStockAlert(stock_val)
  }

  function inputChangeTrigger(curr, stock_val, variant_id) {
    curr.val(stock_val)
    curr.attr('value', stock_val)
    curr.trigger('change')
    setTimeout(function () {
      insufficientStockAlert(stock_val)
      curr.val(stock_val)
      curr.attr('value', stock_val)
      curr.trigger('change')
      // changeCartForVariant(variant_id, stock_val);
    }, 1000)
  }

  function insufficientStockAlert(qty) {
    var stockInsufficientMessage = window.pn.shop.stock_insufficient_message
    if (stockInsufficientMessage.indexOf('{{qty}}')) {
      stockInsufficientMessage = stockInsufficientMessage.replace(
        '{{qty}}',
        qty
      )
    }
    alert(stockInsufficientMessage)
  }

  function changeCartForVariant(id, qty) {
    $.ajax({
      method: 'GET',
      url: '/cart/change.js?id=' + id + '&quantity=' + qty,
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      success: function (data) {},
    })
  }

  // pre stock limit

  function getShopifyDomain() {
    var page_scripts = document.getElementsByTagName('script'),
      sourceURL = '',
      shopify_domain = ''

    for (var i = 0; i < page_scripts.length; i++) {
      if (
        (sourceURL = page_scripts[i].getAttribute('src')) &&
        (sourceURL = sourceURL.match(/^(.*)widget\/javascript(\?\s*(.+))?\s*/))
      ) {
        shopify_domain = sourceURL[3].match(/shop=(.+).myshopify.com/)[1]
        break
      }
    }

    shopify_domain = shopify_domain + '.myshopify.com'

    if (
      shopify_domain === '.myshopify.com' &&
      objectChecker(window.Shopify) &&
      objectChecker(window.Shopify.shop)
    ) {
      shopify_domain = window.Shopify.shop
    }

    if (shopify_domain === '.myshopify.com') {
      console.log('PN: unable to get shop domain')
    }

    return shopify_domain
  }

  function getServerAddress() {
    if (
      getShopifyDomain() == 'crazy-apps-house.myshopify.com' ||
      getShopifyDomain() == 'ajax-collection.myshopify.com' ||
      getShopifyDomain() == 'wnteststore4.myshopify.com' ||
      getShopifyDomain() == 'preorder-now.myshopify.com' ||
      getShopifyDomain() == 'preorder-tagging.myshopify.com'
    ) {
      return 'https://wod.ngrok.io'
    } else if (getShopifyDomain() == 'pn-marc-local.myshopify.com') {
      return 'https://wod4.ngrok.io'
    } else if (process.env.RAILS_ENV == 'development' || process.env.RAILS_ENV == 'staging') {
      return process.env.APP_URL
    } else {
      return 'https://app.preordernowapp.com'
      // return 'https://preorder-now.herokuapp.com'
      // return "https://9ddc5ccd.ngrok.io";
    }
  }

  // sleep time expects milliseconds
  function sleep(time) {
    return new Promise(function (resolve) {
      setTimeout(resolve, time)
    })
  }

  function getCurrentVariantId(preorderProduct) {
    var currentVariant = null

    if (
      onProductPage() > 0 ||
      onCollectionPage() == -1 ||
      onCollectionPage() == false
    ) {
      currentVariant = location.search.match(/variant=([0-9]+)/)
    }

    //If the URL contains a variant ID, return that
    if (currentVariant != null) {
      return currentVariant[1]

      //Otherwise return the first variant's ID
    } else {
      if (
        $(preorderProduct.formSelectors.form_selector)
          .find(
            "select[name='id'], input[name='id'], select[name='id[]'], input[name='id[]']"
          )
          .attr('type') === 'radio'
      ) {
        return $(preorderProduct.formSelectors.form_selector)
          .find("input[name='id']:checked, input[name='id[]']:checked")
          .val()
      } else {
        return $(preorderProduct.formSelectors.form_selector)
          .find(
            "select[name='id'], input[name='id'], select[name='id[]'], input[name='id[]']"
          )
          .val()
      }
    }
  }

  //Detect product page
  function onProductPage() {
    return window.location.href.indexOf('/products/')
  }

  //Detect cart page
  function onCartPage() {
    var url = window.location.href
    var lastPart = url.substr(url.lastIndexOf('/') + 1)

    if (lastPart === 'cart') {
      return true
    } else {
      return false
    }
  }

  //Detect collection page
  function onCollectionPage() {
    return window.location.href.indexOf('/collections/')
  }

  //Setup env
  function setupEnv(theShop) {
    var shop = window.pn.shop
    var styles = window.pn.styles

    if (shop.custom_css != null && shop.custom_css != '') {
      $('head').append('<style type="text/css">' + shop.custom_css + '</style>')
    }

    //Create style sheet containing preorder button styles
    var buttonStyles = '<style type="text/css">.sbb{'

    if (styles[0]['background_color']) {
      buttonStyles +=
        'background-color: ' + styles[0]['background_color'] + ' !important;'
    }
    if (styles[0]['border_color']) {
      buttonStyles +=
        'border-color: ' + styles[0]['border_color'] + ' !important;'
    }
    if (styles[0]['border_radius']) {
      buttonStyles +=
        'border-radius: ' + styles[0]['border_radius'] + 'px !important;'
    }
    if (styles[0]['border_width']) {
      buttonStyles +=
        'border-width: ' + styles[0]['border_width'] + 'px !important;'
    }
    if (styles[0]['font_family']) {
      buttonStyles +=
        'font-family: ' + styles[0]['font_family'] + ' !important;'
    }
    if (styles[0]['font_size']) {
      buttonStyles += 'font-size: ' + styles[0]['font_size'] + 'px !important;'
    }
    if (styles[0]['margin']) {
      buttonStyles += 'margin: ' + styles[0]['margin'] + 'px !important;'
    }
    if (styles[0]['padding']) {
      buttonStyles += 'padding: ' + styles[0]['padding'] + 'px !important;'
    }
    if (styles[0]['text_color']) {
      buttonStyles += 'color: ' + styles[0]['text_color'] + ' !important;'
    }

    buttonStyles += '}</style>'

    $('head').append(buttonStyles)
  }

  function applyStyles(selector, styleNum) {
    $(selector).css({
      'background-color': window.pn.styles[styleNum]['background_color'],
      'border-color': window.pn.styles[styleNum]['border_color'],
      'border-radius': window.pn.styles[styleNum]['border_radius'] + 'px',
      'border-width': window.pn.styles[styleNum]['border_width'] + 'px',
      'font-family': window.pn.styles[styleNum]['font_family'],
      'font-size': window.pn.styles[styleNum]['font_size'] + 'px',
      margin: window.pn.styles[styleNum]['margin'] + 'px',
      padding: window.pn.styles[styleNum]['padding'] + 'px',
      color: window.pn.styles[styleNum]['text_color'],
    })
    if (window.pn.styles[styleNum]['font_family']) {
      $('head').append(
        '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=' +
          window.pn.styles[styleNum]['font_family'] +
          '" />'
      )
    }
  }

  function shadeColor2(color, percent) {
    var f = parseInt(color.slice(1), 16),
      t = percent < 0 ? 0 : 255,
      p = percent < 0 ? percent * -1 : percent,
      R = f >> 16,
      G = (f >> 8) & 0x00ff,
      B = f & 0x0000ff
    return (
      '#' +
      (
        0x1000000 +
        (Math.round((t - R) * p) + R) * 0x10000 +
        (Math.round((t - G) * p) + G) * 0x100 +
        (Math.round((t - B) * p) + B)
      )
        .toString(16)
        .slice(1)
    )
  }

  function applyBadge(
    setting,
    containerObject,
    additionalBadgeClass,
    additionalContainerClass
  ) {
    if (setting.badge_enabled == true) {
      var styles = window.pn.styles

      if (setting.badge_text == null || setting.badge_text == '') {
        setting.badge_text = 'Pre-Order'
      }

      if (
        containerObject.hasClass('preorder-container-' + setting.product_id) &&
        containerObject.children('.preorder-badge span').length > 0
      ) {
        containerObject
          .children(
            'preorder-container-' + setting.product_id + ' .preorder-badge span'
          )
          .text(setting.badge_text)
      } else {
        containerObject.addClass(
          'preorder-container-' +
            setting.product_id +
            ' ' +
            additionalContainerClass
        )
        containerObject.append(
          "<div class='preorder-badge " +
            setting.badge_shape +
            ' ' +
            additionalBadgeClass +
            "'><span>" +
            setting.badge_text +
            '</span></div>'
        )
      }

      //Apply badge styles
      //Background
      if (
        styles[2].background_color != '' &&
        styles[2].background_color != null
      ) {
        var darkColor = styles[2].background_color
        var lightColor = shadeColor2(styles[2].background_color, 0.5)
        var linearGradient =
          'linear-gradient(' + lightColor + ' 0%, ' + darkColor + ' 100%)'

        if (setting.badge_shape == 'ribbon') {
          $(
            '.preorder-container-' +
              setting.product_id +
              ' .preorder-badge.' +
              setting.badge_shape +
              ' span'
          ).css('background', darkColor)
          if (styles[2].badge_gradient) {
            $(
              'preorder-container-' +
                setting.product_id +
                ' .preorder-badge.' +
                setting.badge_shape +
                ' span'
            ).css('background', linearGradient)
          }
        } else {
          $(
            '.preorder-container-' +
              setting.product_id +
              ' .preorder-badge.' +
              setting.badge_shape
          ).css('background', darkColor)
          if (styles[2].badge_gradient) {
            $(
              '.preorder-container-' +
                setting.product_id +
                ' .preorder-badge.' +
                setting.badge_shape
            ).css('background', linearGradient)
          }
        }
      } else {
        if (setting.badge_shape == 'ribbon') {
          $(
            '.preorder-container-' +
              setting.product_id +
              ' .preorder-badge.' +
              setting.badge_shape +
              ' span'
          ).css('background', '#79A70A')
          if (styles[2].badge_gradient) {
            $(
              '.preorder-container-' +
                setting.product_id +
                ' .preorder-badge.' +
                setting.badge_shape +
                ' span'
            ).css('background', 'linear-gradient(#9BC90D 0%, #79A70A 100%)')
          }
        } else {
          $(
            '.preorder-container-' +
              setting.product_id +
              ' .preorder-badge.' +
              setting.badge_shape
          ).css('background', '#79A70A')
          if (styles[2].badge_gradient) {
            $(
              '.preorder-container-' +
                setting.product_id +
                ' .preorder-badge.' +
                setting.badge_shape
            ).css('background', 'linear-gradient(#9BC90D 0%, #79A70A 100%)')
          }
        }
      }

      if (styles[2].badge_shadow) {
        if (setting.badge_shape == 'ribbon') {
          $(
            '.preorder-container-' +
              setting.product_id +
              ' .preorder-badge.' +
              setting.badge_shape +
              ' span'
          ).css('box-shadow', '0 3px 10px -5px rgba(0, 0, 0, 1)')
        } else {
          $(
            '.preorder-container-' +
              setting.product_id +
              ' .preorder-badge.' +
              setting.badge_shape
          ).css('box-shadow', '0 3px 10px -5px rgba(0, 0, 0, 1)')
        }
      }

      if (styles[2].text_color != '' && styles[2].text_color != null) {
        $(
          '.preorder-container-' + setting.product_id + ' .preorder-badge span'
        ).css('color', styles[2].text_color)
      }

      if (styles[2].font_family != '' && styles[2].font_family != null) {
        $(
          '.preorder-container-' + setting.product_id + ' .preorder-badge span'
        ).css('font-family', styles[2].font_family)
        $('head').append(
          '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=' +
            styles[2]['font_family'] +
            '" />'
        )
      }

      if (styles[2].font_size != '' && styles[2].font_size != null) {
        $(
          '.preorder-container-' + setting.product_id + ' .preorder-badge span'
        ).css('font-size', styles[2].font_size + 'px')
      }
    } else {
      containerObject.removeClass('preorder-container-' + setting.product_id)
      $(
        '.preorder-container-' + setting.product_id + ' .preorder-badge'
      ).remove()
    }
  }

  function showStockRemaining(preorderProduct) {
    if (preorderProduct.activeVariant.use_stock_management) {
      getItems()
      var curr_item
      var stock_val
      for (var i = 0; i < crtItems.items.length; i++) {
        if (
          preorderProductCopy.activeVariant &&
          crtItems.items[i].variant_id ==
            preorderProductCopy.activeVariant.settings_type_id &&
          preorderProductCopy.activeVariant.preorder_stock != null &&
          preorderProductCopy.activeVariant.use_shopify_stock_management ==
            false
        ) {
          curr_item = crtItems.items[i]
        } else if (
          preorderProductCopy.activeVariant &&
          crtItems.items[i].variant_id ==
            preorderProductCopy.activeVariant.settings_type_id &&
          preorderProduct.activeVariant.shopify_preorder_limit != null &&
          preorderProduct.activeVariant.shopify_stock_mgmt_method == 2 &&
          preorderProductCopy.activeVariant.use_shopify_stock_management == true
        ) {
          curr_item = crtItems.items[i]
        }
      }
      if (curr_item != undefined) {
        stock_val =
          parseInt(preorderProduct.activeVariant.preorder_stock) -
          curr_item.quantity
      } else {
        stock_val = preorderProduct.activeVariant.preorder_stock
      }
      if (!preorderProduct.activeVariant.use_shopify_stock_management) {
        if (
          preorderProduct.activeVariant.show_stock_remaining &&
          preorderProduct.activeVariant.preorder_stock > 0 &&
          preorderProduct.activeVariant.stock_remaining_message != null
        ) {
          //console.log(preorderProduct.activeVariant);
          var stock_message =
            preorderProduct.activeVariant.stock_remaining_message.replace(
              '{{qty}}',
              noNegative(stock_val)
            )
          if (
            $(preorderProduct.formSelectors.form_selector).find(
              'div.stock-level'
            ).length == 0
          ) {
            $(preorderProduct.formSelectors.button_selector).after(
              "<div class='stock-level'>" + stock_message + '</div>'
            )
          } else {
            $(preorderProduct.formSelectors.form_selector)
              .find('div.stock-level')
              .show()
            $(preorderProduct.formSelectors.form_selector)
              .find('div.stock-level')
              .text(stock_message)
          }
        }
      }
    }
  }

  function checkStockShowBadge(theSetting) {
    if (theSetting.settings_enabled) {
      if (
        beforePreorderStartDate(theSetting) ||
        afterPreorderEndDate(theSetting)
      ) {
        return false
      } else {
        if (theSetting.use_stock_management) {
          if (theSetting.use_shopify_stock_management) {
            if (theSetting.shopify_stock_mgmt_method == 1) {
              if (
                theSetting.shopify_inventory > 0 ||
                theSetting.shopify_inventory == null
              ) {
                return true
              } else {
                return false
              }
            } else if (theSetting.shopify_stock_mgmt_method == 2) {
              if (
                theSetting.shopify_inventory <= 0 &&
                theSetting.oversell_enabled &&
                !(
                  typeof theSetting.shopify_preorder_limit == 'number' &&
                  theSetting.shopify_preorder_limit == 0
                )
              ) {
                return true
              } else {
                return false
              }
            }
          } else {
            if (
              theSetting.preorder_stock > 0 ||
              theSetting.preorder_stock == null
            ) {
              return true
            } else {
              return false
            }
          }
        } else if (
          theSetting.shopify_inventory != null &&
          theSetting.shopify_inventory <= 0 &&
          !theSetting.oversell_enabled &&
          theSetting.inventory_management != ''
        ) {
          return false
        } else {
          return true
        }
      }
    } else {
      return false
    }
  }

  function beforePreorderStartDate(setting) {
    if (
      setting.preorder_start_date != '' &&
      setting.preorder_start_date != null
    ) {
      var startDate = new Date(setting.preorder_start_date)
      var currentDate = new Date()
      if (currentDate < startDate) {
        return true
      } else {
        return false
      }
    } else {
      false
    }
  }

  function afterPreorderEndDate(setting) {
    if (setting.preorder_end_date != '' && setting.preorder_end_date != null) {
      var endDate = new Date(setting.preorder_end_date)
      var currentDate = new Date()
      if (currentDate > endDate) {
        return true
      } else {
        return false
      }
    } else {
      false
    }
  }

  function notifyPartialPreorder(preorderProduct) {
    sleep(250).then(function () {
      if ($('.notify-partial-preorder').length) {
        $('.notify-partial-preorder').remove()
      }

      var quantityDesired = getQuantityDesired(preorderProduct)

      if (
        window.pn.shop.notify_when_partial_preorder &&
        preorderProduct.activeVariant.shopify_inventory < quantityDesired
      ) {
        var stockInsufficientMessage =
          window.pn.shop.notify_when_partial_preorder_message

        stockInsufficientMessage = stockInsufficientMessage.replace(
          /{{qty}}/g,
          noNegative(preorderProduct.activeVariant.shopify_inventory)
        )

        if (
          preorderProduct.formSelectors
            .partial_preorder_notice_placement_selector != null &&
          preorderProduct.formSelectors
            .partial_preorder_notice_placement_selector != ''
        ) {
          $(
            preorderProduct.formSelectors
              .partial_preorder_notice_placement_selector
          ).after(
            "<div class='notify-partial-preorder'>" +
              stockInsufficientMessage +
              '</div>'
          )
        } else {
          $(preorderProduct.formSelectors.button_selector).after(
            "<div class='notify-partial-preorder'>" +
              stockInsufficientMessage +
              '</div>'
          )
        }

        $(preorderProduct.formSelectors.form_selector).prepend(
          '<input type="hidden" id="preorder-note" class="notify-partial-preorder" name="properties[' +
            window.pn.shop.pn_note_label +
            ']" value="' +
            stockInsufficientMessage +
            '" />'
        )
      }
    })
  }

  function showBuyNowButton(preorderProduct) {
    if (typeof preorderProduct.formSelectors.form_missing === 'undefined') {
      $(preorderProduct.formSelectors.form_selector).removeClass(
        PN_ACTIVE_CLASS
      )
      if (window.pn.shop.hide_buy_now_button) {
        $(preorderProduct.formSelectors.form_selector)
          .find(BUY_NOW_BUTTON_SELECTOR)
          .show()
      }
    }
  }

  function hideBuyNowButton(preorderProduct) {
    if (typeof preorderProduct.formSelectors.form_missing === 'undefined') {
      $(preorderProduct.formSelectors.form_selector).addClass(PN_ACTIVE_CLASS)
      if (window.pn.shop.hide_buy_now_button) {
        $(preorderProduct.formSelectors.form_selector)
          .find(BUY_NOW_BUTTON_SELECTOR)
          .hide()
      }
    }
  }

  //Create the widget
  function createWidget(preorderProduct) {
    preorderProductCopy = preorderProduct
    //Showing button in case merchant asked us to hide until our app loads
    $(preorderProduct.formSelectors.button_selector).show()

    preorderProduct.activeVariant = getActiveVariantSetting(preorderProduct)

    if (preorderProduct.activeVariant.settings_enabled) {
      if (
        preorderProduct.activeVariant.oversell_enabled &&
        preorderProduct.activeVariant.use_stock_management &&
        preorderProduct.activeVariant.use_shopify_stock_management &&
        preorderProduct.activeVariant.shopify_stock_mgmt_method == 2
      ) {
        if (
          preorderProduct.activeVariant.shopify_preorder_limit != null &&
          preorderProduct.activeVariant.shopify_preorder_limit <= 0 &&
          preorderProduct.activeVariant.shopify_inventory != null &&
          preorderProduct.activeVariant.shopify_inventory < 1
        ) {
          $(preorderProduct.formSelectors.button_selector).val(
            window.pn.shop.out_of_stock_text
          )
          $(preorderProduct.formSelectors.button_selector).text(
            window.pn.shop.out_of_stock_text
          )
          $(preorderProduct.formSelectors.button_selector).prop(
            'disabled',
            true
          )
          hideBuyNowButton(preorderProduct)
        } else if (
          preorderProduct.activeVariant.shopify_inventory != null &&
          preorderProduct.activeVariant.shopify_inventory > 0
        ) {
          //Need to run it once in case they've switched variants and have already chosen a quantity
          notifyPartialPreorder(preorderProduct)

          $('input[name=quantity]:visible').change(function (event) {
            notifyPartialPreorder(preorderProduct)
          })
          $(
            ".js-qty__adjust, .js-change-quantity, div[data-control='+'], div[data-control='-']"
          ).click(function (event) {
            notifyPartialPreorder(preorderProduct)
          })
        }
      } else if (
        preorderProduct.activeVariant.use_stock_management &&
        !preorderProduct.activeVariant.use_shopify_stock_management &&
        typeof preorderProduct.activeVariant.preorder_stock == 'number' &&
        preorderProduct.activeVariant.preorder_stock === 0
      ) {
        $(preorderProduct.formSelectors.button_selector).val(
          preorderProduct.activeVariant.out_of_stock_message
        )
        $(preorderProduct.formSelectors.button_selector).text(
          preorderProduct.activeVariant.out_of_stock_message
        )
        $(preorderProduct.formSelectors.button_selector).prop('disabled', true)
        hideBuyNowButton(preorderProduct)
      }
    }

    if (
      preorderProduct.activeVariant.preorder_status &&
      preorderProduct.activeVariant.settings_enabled
    ) {
      if (getShopifyDomain() == 'globalviews.myshopify.com') {
        $(preorderProduct.formSelectors.button_selector).off('click')
      }

      showStockRemaining(preorderProduct)

      $(preorderProduct.formSelectors.button_selector).addClass('sbb')

      if (
        preorderProduct.activeVariant.use_stock_management &&
        preorderProduct.activeVariant.use_shopify_stock_management &&
        preorderProduct.activeVariant.shopify_inventory < 1 &&
        !preorderProduct.activeVariant.oversell_enabled &&
        preorderProduct.activeVariant.shopify_inventory != null
      ) {
        $(preorderProduct.formSelectors.button_selector).val(
          window.pn.shop.out_of_stock_text
        )
        $(preorderProduct.formSelectors.button_selector).text(
          window.pn.shop.out_of_stock_text
        )
        $(preorderProduct.formSelectors.button_selector).prop('disabled', true)
      } else {
        $(preorderProduct.formSelectors.button_selector).text(
          preorderProduct.activeVariant.preorder_button_text
        )
        $(preorderProduct.formSelectors.button_selector).val(
          preorderProduct.activeVariant.preorder_button_text
        )
        hideBuyNowButton(preorderProduct)
      }

      var cartLabel = ''

      if (
        preorderProduct.activeVariant.cart_label_text != '' &&
        preorderProduct.activeVariant.cart_label_text != null
      ) {
        cartLabel = preorderProduct.activeVariant.cart_label_text
      } else {
        cartLabel = window.pn.shop.cart_label_text
      }

      if (cartLabel != '' && cartLabel != null) {
        if (
          $(preorderProduct.formSelectors.form_selector).find('#preorder-note')
            .length == 0
        ) {
          $(preorderProduct.formSelectors.form_selector).prepend(
            '<input type="hidden" id="preorder-note" name="properties[' +
              window.pn.shop.pn_note_label +
              ']" value="' +
              cartLabel +
              '" />'
          )
        } else {
          $(preorderProduct.formSelectors.form_selector)
            .find('#preorder-note')
            .val(cartLabel)
        }
      }

      if (preorderProduct.activeVariant.preorder_description != null) {
        if (
          preorderProduct.activeVariant.preorder_description_position == 'below'
        ) {
          if (getShopifyDomain() == 'genevieve-lorange.myshopify.com') {
            $(preorderProduct.formSelectors.button_selector)
              .parent()
              .after(
                "<div class='preorder-description'>" +
                  preorderProduct.activeVariant.preorder_description +
                  '</div>'
              )
          } else {
            if (
              $(preorderProduct.formSelectors.form_selector).find(
                '.preorder-description'
              ).length == 0
            ) {
              $(preorderProduct.formSelectors.button_selector).after(
                "<div class='preorder-description'>" +
                  preorderProduct.activeVariant.preorder_description +
                  '</div>'
              )
            } else {
              $(preorderProduct.formSelectors.form_selector)
                .find('.preorder-description')
                .text(preorderProduct.activeVariant.preorder_description)
            }
          }
        } else if (
          preorderProduct.activeVariant.preorder_description_position == 'above'
        ) {
          if (
            $(preorderProduct.formSelectors.form_selector).find(
              '.preorder-description'
            ).length == 0
          ) {
            $(preorderProduct.formSelectors.button_selector).before(
              "<div class='preorder-description'>" +
                preorderProduct.activeVariant.preorder_description +
                '</div>'
            )
          } else {
            $(preorderProduct.formSelectors.form_selector)
              .find('.preorder-description')
              .text(preorderProduct.activeVariant.preorder_description)
          }
        } else {
          $('div.preorder-description').hide()
          $(preorderProduct.formSelectors.button_selector).prop(
            'title',
            preorderProduct.activeVariant.preorder_description
          )
          $.getScript(
            'https://code.jquery.com/ui/1.12.1/jquery-ui.min.js',
            function () {
              $('head').append(
                '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" type="text/css" />'
              )
              $(preorderProduct.formSelectors.button_selector).tooltip()
            }
          )
        }
      }

      applyStyles('div.preorder-description, div.ui-tooltip', 1)
      applyBadge(
        preorderProduct.activeVariant,
        findProductImageContainer(
          preorderProduct.activeVariant,
          $(preorderProduct.formSelectors.product_image_container_selector)
        ),
        '',
        ''
      )

      // pre stock limit code

      $('body').on(
        'change',
        window.pn.quickviewSettings.variantSelectors,
        function () {
          hasLimitReachForVarint = false
        }
      )
      if (eventCount == 0) {
        $('body').on('click', "button[name='checkout']", function (event) {
          getItems()
          logCheckout(preorderProductCopy, event)
        })

        $(preorderProduct.formSelectors.button_selector).click(function (
          event
        ) {
          getItems()
          logClick(preorderProduct, event)
        })
        eventCount = 1
      }
      // pre stock limit code

      return true
    } else {
      return false
    }
  }

  function getActiveVariantSetting(preorderProduct) {
    var currentVariantSetting = false
    var currentVariantId = getCurrentVariantId(preorderProduct)
    $.each(preorderProduct.settings, function (index, setting) {
      if (setting.settings_type_id == currentVariantId) {
        currentVariantSetting = setting
      }
    })
    return currentVariantSetting
  }

  function findProductImageContainer(variantSetting, imageContainer) {
    if (
      imageContainer.length == 0 &&
      variantSetting.product_image_src != '' &&
      variantSetting.product_image_src != null
    ) {
      var productImageFilename = variantSetting.product_image_src

      productImageFilename = productImageFilename
        .substring(productImageFilename.lastIndexOf('/') + 1)
        .split('?')[0]

      productImageFilename = productImageFilename.split('.')[0]

      var productImageSelector = 'img[src*=' + productImageFilename + ']'

      var imageContainer = $(productImageSelector)

      if (imageContainer.length > 1) {
        for (var i = 0; i < imageContainer.length; i++) {
          if (imageContainer[i].offsetWidth > 200) {
            imageContainer = imageContainer[i]
            break
          }
        }
      }

      if (getShopifyDomain() == 'fairley.myshopify.com') {
        imageContainer = $($(imageContainer).parent())
      } else {
        imageContainer = $($(imageContainer).parent().parent())
      }
    }

    return imageContainer
  }

  function restoreDefaults(preorderProduct) {
    preorderProduct.activeVariant = getActiveVariantSetting(preorderProduct)

    $('input[name=quantity]:visible').off('change')

    $('.notify-partial-preorder').remove()
    showBuyNowButton(preorderProduct)

    //If activeVariant is false then no pre-order setting exists for this variant (and we're expecting the theme to adjust text on the button as appropriate)
    //This was necessary on products where pre-order is never active and all settings are false and shopper switches from instock variant to out of stock variant
    if (preorderProduct.activeVariant) {
      //If the variant is in stock / available, change text back to add to cart
      //This check was necessary for when preorder is active and switching from preorder/instock product to out of stock/no preorder product
      if (inStock(preorderProduct.activeVariant)) {
        $(preorderProduct.formSelectors.button_selector).text(
          window.pn.shop.add_to_cart_text
        )
        $(preorderProduct.formSelectors.button_selector).val(
          window.pn.shop.add_to_cart_text
        )
        //Else change text to out of stock (expecting theme will disable button)
      } else {
        $(preorderProduct.formSelectors.button_selector).text(
          window.pn.shop.out_of_stock_text
        )
        $(preorderProduct.formSelectors.button_selector).val(
          window.pn.shop.out_of_stock_text
        )
      }
    }

    if (typeof preorderProduct.formSelectors.button_selector == 'string') {
      $(
        preorderProduct.formSelectors.button_selector.replace(':first', '')
      ).prop('disabled', false)
    } else {
      $(preorderProduct.formSelectors.button_selector).prop('disabled', false)
    }

    $(preorderProduct.formSelectors.button_selector).removeClass('sbb')

    $(preorderProduct.formSelectors.form_selector)
      .find('#preorder-note')
      .remove()
    $(preorderProduct.formSelectors.form_selector)
      .find('div.preorder-description')
      .remove()
    $(preorderProduct.formSelectors.form_selector)
      .find('div.stock-level')
      .remove()

    if (typeof $('.sbb').tooltip === 'function') {
      $(preorderProduct.formSelectors.button_selector).prop('title', '')
    }

    $(
      '.preorder-container-' +
        preorderProduct.activeVariant.product_id +
        ' div.preorder-badge'
    )
      .not('.collection-badge')
      .remove()
    $('.preorder-container-' + preorderProduct.activeVariant.product_id)
      .not('.collection-badge-container')
      .removeClass(
        'preorder-container-' + preorderProduct.activeVariant.product_id
      )

    if (preorderProduct.activeVariant != null) {
      if (
        preorderProduct.activeVariant.settings_enabled &&
        preorderProduct.activeVariant.use_stock_management &&
        preorderProduct.activeVariant.use_shopify_stock_management &&
        preorderProduct.activeVariant.shopify_inventory < 1 &&
        preorderProduct.activeVariant.shopify_inventory != null &&
        !preorderProduct.activeVariant.oversell_enabled
      ) {
        $(preorderProduct.formSelectors.button_selector).text(
          window.pn.shop.out_of_stock_text
        )
        $(preorderProduct.formSelectors.button_selector).val(
          window.pn.shop.out_of_stock_text
        )
        $(preorderProduct.formSelectors.button_selector).prop('disabled', true)
      }
      //This situation is for if they're switching to a variant that's out of stock and pre-order is disabled. Our script above is setting the button text to add to cart in this situation which is incorrect.
      if (
        !preorderProduct.activeVariant.settings_enabled &&
        !preorderProduct.activeVariant.oversell_enabled &&
        !isNaN(parseInt(preorderProduct.activeVariant.shopify_inventory)) &&
        preorderProduct.activeVariant.shopify_inventory < 1 &&
        preorderProduct.activeVariant.shopify_inventory != null
      ) {
        $(preorderProduct.formSelectors.button_selector).text(
          window.pn.shop.out_of_stock_text
        )
        $(preorderProduct.formSelectors.button_selector).val(
          window.pn.shop.out_of_stock_text
        )
        $(preorderProduct.formSelectors.button_selector).prop('disabled', true)
      }
    }
  }

  function inStock(variantSetting) {
    if (
      variantSetting.shopify_inventory == null ||
      variantSetting.shopify_inventory > 0 ||
      variantSetting.oversell_enabled
    ) {
      return true
    } else {
      return false
    }
  }

  function setQuantityField(quantityAvailable, preorderProduct) {
    if (
      $(preorderProduct.formSelectors.form_selector).find(
        'input[name=quantity]:visible'
      )
    ) {
      $(preorderProduct.formSelectors.form_selector)
        .find('input[name=quantity]:visible')
        .val(quantityAvailable)
    }
  }

  function getQuantityDesired(preorderProduct) {
    var quantityDesired = 1
    if (
      $(preorderProduct.formSelectors.form_selector).find(
        'input[name=quantity]:visible'
      ).length > 0
    ) {
      quantityDesired = $(preorderProduct.formSelectors.form_selector)
        .find('input[name=quantity]:visible')
        .val()
    }
    return quantityDesired
  }

  function logCheckout(preorderProductCopy, event) {
    // $(".ajaxifyCart--num").each(function(){
    $("form[action='/cart']")
      .find('input')
      .each(function () {
        logCart($(this), preorderProductCopy, event)
      })
  }

  function logCart(current, preorderProductCopy, event) {
    var current = current
    var variant
    var stock_val
    if (current.data('id') != undefined) {
      variant =
        preorderProductCopy.settings[
          current
            .data('id')
            .split(':')[0]
            .replace(/[^0-9]/g, '')
        ]
    } else if (current.attr('id') != undefined) {
      variant =
        preorderProductCopy.settings[
          current
            .attr('id')
            .split(':')[0]
            .replace(/[^0-9]/g, '')
        ]
    }
    if (
      variant != undefined &&
      variant &&
      variant.preorder_stock != null &&
      variant.use_shopify_stock_management == false
    ) {
      stock_val = variant.preorder_stock
    } else if (
      variant != undefined &&
      variant &&
      variant.shopify_preorder_limit != null &&
      variant.shopify_stock_mgmt_method == 2 &&
      variant.use_shopify_stock_management == true
    ) {
      stock_val = variant.shopify_preorder_limit
    }
    if (variant != undefined && variant) {
      if (
        (variant.preorder_stock != null &&
          variant.use_shopify_stock_management == false &&
          parseInt(current.val().replace(/[^0-9]/g, '')) >
            variant.preorder_stock) ||
        (variant.shopify_preorder_limit != null &&
          variant.shopify_stock_mgmt_method == 2 &&
          variant.use_shopify_stock_management == true &&
          parseInt(current.val().replace(/[^0-9]/g, '')) >
            variant.shopify_preorder_limit)
      ) {
        var stockInsufficientMessage = window.pn.shop.stock_insufficient_message
        if (current.next().attr('data-qty') != undefined) {
          // for plus and minus icon click
          current.val(stock_val - 1)
          current.attr('value', stock_val - 1)
          current.next().attr('data-qty', stock_val - 1)
          current
            .next()
            .next()
            .attr('data-qty', stock_val - 1)
          current.next().trigger('click')
        } else {
          current.val(stock_val)
          current.attr('value', stock_val)
        }

        if (stockInsufficientMessage.indexOf('{{qty}}')) {
          if (
            variant.use_stock_management &&
            variant.use_shopify_stock_management &&
            variant.shopify_stock_mgmt_method == 1 &&
            variant.shopify_inventory != null
          ) {
            stockInsufficientMessage = stockInsufficientMessage.replace(
              '{{qty}}',
              noNegative(variant.shopify_inventory)
            )
          } else if (
            variant.use_stock_management &&
            variant.use_shopify_stock_management &&
            variant.shopify_stock_mgmt_method == 2 &&
            variant.shopify_preorder_limit != null
          ) {
            stockInsufficientMessage = stockInsufficientMessage.replace(
              '{{qty}}',
              noNegative(variant.shopify_preorder_limit)
            )
          } else {
            stockInsufficientMessage = stockInsufficientMessage.replace(
              '{{qty}}',
              noNegative(variant.preorder_stock)
            )
          }
        }

        alert(stockInsufficientMessage)
        event.preventDefault()
        return false
      }
    }
  }

  function logClick(preorderProduct, event) {
    var quantityDesired = getQuantityDesired(preorderProduct)
    var curr_item
    for (var i = 0; i < crtItems.items.length; i++) {
      if (
        preorderProductCopy.activeVariant &&
        crtItems.items[i].variant_id ==
          preorderProductCopy.activeVariant.settings_type_id &&
        preorderProductCopy.activeVariant.preorder_stock != null &&
        preorderProductCopy.activeVariant.use_shopify_stock_management == false
      ) {
        curr_item = crtItems.items[i]
      } else if (
        preorderProductCopy.activeVariant &&
        crtItems.items[i].variant_id ==
          preorderProductCopy.activeVariant.settings_type_id &&
        preorderProduct.activeVariant.shopify_preorder_limit != null &&
        preorderProduct.activeVariant.shopify_stock_mgmt_method == 2 &&
        preorderProductCopy.activeVariant.use_shopify_stock_management == true
      ) {
        curr_item = crtItems.items[i]
      }
    }
    if (curr_item != undefined) {
      quantityDesired = parseInt(quantityDesired) + curr_item.quantity
    }
    if (
      !window.pn.shop.limit_order_quantity ||
      !(
        (preorderProduct.activeVariant.use_stock_management &&
          preorderProduct.activeVariant.use_shopify_stock_management &&
          preorderProduct.activeVariant.shopify_stock_mgmt_method == 1 &&
          preorderProduct.activeVariant.shopify_inventory != null &&
          preorderProduct.activeVariant.shopify_inventory < quantityDesired) ||
        (preorderProduct.activeVariant.use_stock_management &&
          preorderProduct.activeVariant.use_shopify_stock_management &&
          preorderProduct.activeVariant.shopify_stock_mgmt_method == 2 &&
          preorderProduct.activeVariant.shopify_preorder_limit != null &&
          preorderProduct.activeVariant.shopify_preorder_limit <
            quantityDesired) ||
        (preorderProduct.activeVariant.use_stock_management &&
          !preorderProduct.activeVariant.use_shopify_stock_management &&
          preorderProduct.activeVariant.preorder_stock != null &&
          preorderProduct.activeVariant.preorder_stock < quantityDesired)
      )
    ) {
      var eventText = 'Preorder Now: Preorder button clicked'
      //Get variant price
      var varIndex = 0

      //record an event in analytics
      window.ga &&
        ga.loaded &&
        ga(
          'send',
          'event',
          'Preorder Now',
          eventText,
          preorderProduct.activeVariant.handle
        )

      if (
        !buttonClicked &&
        getShopifyDomain() != 'cosmic-toys.myshopify.com' &&
        getShopifyDomain() != 'wiinkbcn.myshopify.com' &&
        !$(event.target).is(preorderProduct.formSelectors.button_selector)
      ) {
        //trigger button event
        buttonClicked = true
        $(preorderProduct.formSelectors.button_selector).trigger('click')
      }
    } else {
      var stockInsufficientMessage = window.pn.shop.stock_insufficient_message

      if (stockInsufficientMessage.indexOf('{{qty}}')) {
        if (
          preorderProduct.activeVariant.use_stock_management &&
          preorderProduct.activeVariant.use_shopify_stock_management &&
          preorderProduct.activeVariant.shopify_stock_mgmt_method == 1 &&
          preorderProduct.activeVariant.shopify_inventory != null
        ) {
          setQuantityField(
            noNegative(preorderProduct.activeVariant.shopify_inventory),
            preorderProduct
          )
          stockInsufficientMessage = stockInsufficientMessage.replace(
            '{{qty}}',
            noNegative(preorderProduct.activeVariant.shopify_inventory)
          )
        } else if (
          preorderProduct.activeVariant.use_stock_management &&
          preorderProduct.activeVariant.use_shopify_stock_management &&
          preorderProduct.activeVariant.shopify_stock_mgmt_method == 2 &&
          preorderProduct.activeVariant.shopify_preorder_limit != null
        ) {
          if (curr_item != undefined) {
            setQuantityField(
              noNegative(
                preorderProduct.activeVariant.shopify_preorder_limit -
                  curr_item.quantity
              ),
              preorderProduct
            )
            stockInsufficientMessage = stockInsufficientMessage.replace(
              '{{qty}}',
              noNegative(
                preorderProduct.activeVariant.shopify_preorder_limit -
                  curr_item.quantity
              )
            )
          } else {
            setQuantityField(
              noNegative(preorderProduct.activeVariant.shopify_preorder_limit),
              preorderProduct
            )
            stockInsufficientMessage = stockInsufficientMessage.replace(
              '{{qty}}',
              noNegative(preorderProduct.activeVariant.shopify_preorder_limit)
            )
          }
        } else {
          if (curr_item != undefined) {
            setQuantityField(
              noNegative(
                preorderProduct.activeVariant.preorder_stock -
                  curr_item.quantity
              ),
              preorderProduct
            )
            stockInsufficientMessage = stockInsufficientMessage.replace(
              '{{qty}}',
              noNegative(
                preorderProduct.activeVariant.preorder_stock -
                  curr_item.quantity
              )
            )
          } else {
            setQuantityField(
              noNegative(preorderProduct.activeVariant.preorder_stock),
              preorderProduct
            )
            stockInsufficientMessage = stockInsufficientMessage.replace(
              '{{qty}}',
              noNegative(preorderProduct.activeVariant.preorder_stock)
            )
          }
        }
      }
      alert(stockInsufficientMessage)
      event.preventDefault()
      return false
    }
  }

  function noNegative(amount) {
    if (amount < 0) {
      return 0
    } else {
      return amount
    }
  }

  function getRandomInt(minNum, maxNum) {
    return Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum
  }

  function getRandomizedURL() {
    return window.location.href + '?' + getRandomInt(0, 10000)
  }

  function configureFormSelectors(preorderProduct) {
    var formSelectors = {}

    if (
      typeof window.pn.quickviewClicked !== 'undefined' &&
      window.pn.quickviewClicked
    ) {
      window.pn.quickviewClicked = false
      formSelectors.form_selector = $(
        window.pn.quickviewSettings.quickviewModalContainerSelectors
      ).find(window.pn.quickviewSettings.formSelectors)
      formSelectors.button_selector = $(
        window.pn.quickviewSettings.quickviewModalContainerSelectors
      ).find(window.pn.quickviewSettings.addToCartButtonSelectors)
      formSelectors.product_image_container_selector = $(
        window.pn.quickviewSettings.quickviewModalContainerSelectors
      ).find(window.pn.quickviewSettings.productImageContainerSelectors)
      formSelectors.variant_selector = $(
        window.pn.quickviewSettings.quickviewModalContainerSelectors
      ).find(window.pn.quickviewSettings.variantSelectors)

      if (
        window.pn.shop.partial_preorder_notice_placement_selector != '' &&
        window.pn.shop.partial_preorder_notice_placement_selector != null
      ) {
        formSelectors.partial_preorder_notice_placement_selector = $(
          window.pn.quickviewSettings.quickviewModalContainerSelectors
        ).find(window.pn.shop.partial_preorder_notice_placement_selector)
      } else {
        formSelectors.partial_preorder_notice_placement_selector =
          formSelectors.button_selector
      }
    } else {
      formSelectors.form_selector = $(
        window.pn.shop.fss_selector_prefix +
          "input[value='" +
          preorderProduct.settings[
            Object.keys(preorderProduct.settings)[
              Object.keys(preorderProduct.settings).length - 1
            ]
          ].settings_type_id +
          "'], " +
          window.pn.shop.fss_selector_prefix +
          "option[value='" +
          preorderProduct.settings[
            Object.keys(preorderProduct.settings)[
              Object.keys(preorderProduct.settings).length - 1
            ]
          ].settings_type_id +
          "']"
      ).parents(window.pn.shop.fss_parent_selector)

      if ($(formSelectors.form_selector).length == 0) {
        formSelectors.form_selector = $(window.pn.shop.form_selector)
        formSelectors.form_missing = true
      }

      formSelectors.button_selector = formSelectors.form_selector.find(
        stripFormSelector(window.pn.shop.button_selector)
      )

      if ($(formSelectors.button_selector).length == 0) {
        formSelectors.button_selector = $(window.pn.shop.button_selector)
      }

      formSelectors.product_image_container_selector = $(
        stripFormSelector(window.pn.shop.product_image_container_selector)
      )
      formSelectors.variant_selector = formSelectors.form_selector.find(
        stripFormSelector(window.pn.shop.variant_selector)
      )

      if (
        window.pn.shop.partial_preorder_notice_placement_selector != '' &&
        window.pn.shop.partial_preorder_notice_placement_selector != null
      ) {
        formSelectors.partial_preorder_notice_placement_selector =
          formSelectors.form_selector.find(
            stripFormSelector(
              window.pn.shop.partial_preorder_notice_placement_selector
            )
          )
      } else {
        formSelectors.partial_preorder_notice_placement_selector =
          formSelectors.button_selector
      }
    }

    return formSelectors
  }

  function setupPreorderForm(preorderProduct) {
    preorderProduct.formSelectors = configureFormSelectors(preorderProduct)

    var delay = 0
    if (getShopifyDomain() == 'for-real-snacks.myshopify.com') {
      delay = 2000
    }

    sleep(delay).then(function () {
      createWidget(preorderProduct)
    })

    $(preorderProduct.formSelectors.variant_selector).on('change', function () {
      initializeForm(preorderProduct)
    })

    if (
      $(
        ".swatchColor, .panda-swatch, button.swatch, div.swatch-element, div.swatch-item, .product-variant ul li, div.swatches-container ul.options li a, div.template--product-variants-container div.product-variant-group label, .gf_swatch, .variant-input-wrap label, ul.clickyboxes li a, .product-single__thumbnail, .Popover__Value, .selectric-scroll li, .select-dropdown li, .VariantSelector__Button, .bc-quickview-single-option-swatch-item,.variant-options input[type='radio'],.variant-swatch, .option-value, .collection-swatch-wrap li, .collection-swatch-wrap li div, .product-options__value, .product-item__radio, .basel-swatch, .swatch, .SizeSwatch, .js-variant-thumbnail-trigger"
      )
    ) {
      $(
        ".swatchColor, .panda-swatch, button.swatch, div.swatch-element, div.swatch-item, .product-variant ul li, div.swatches-container ul.options li a, div.template--product-variants-container div.product-variant-group label, .gf_swatch, .variant-input-wrap label, ul.clickyboxes li a, .product-single__thumbnail, .Popover__Value, .selectric-scroll li, .select-dropdown li, .VariantSelector__Button, .bc-quickview-single-option-swatch-item,.variant-options input[type='radio'],.variant-swatch, .option-value, .collection-swatch-wrap li, .collection-swatch-wrap li div, .product-options__value, .product-item__radio, .basel-swatch, .swatch, .SizeSwatch, .js-variant-thumbnail-trigger"
      ).on('click', function () {
        initializeForm(preorderProduct)
      })
    }
  }

  function hasActivePreoderSettings(preorderProduct) {
    var hasActivePreoderSetting = false

    $.each(preorderProduct.settings, function (index, setting) {
      if (setting) {
        hasActivePreoderSetting = true
      }
    })

    return hasActivePreoderSetting
  }

  function initializeForm(preorderProduct) {
    sleep(250).then(function () {
      var availableCriteriaOne =
        $(preorderProduct.formSelectors.form_selector)
          .find('.sbb')
          .attr('aria-label') != 'Unavailable'
      var availableCriteriaTwo =
        $(preorderProduct.formSelectors.form_selector)
          .parents('#ProductSection-product-template')
          .find('.visually-hidden[data-product-status]')
          .text() != 'Unavailable'
      var availableCriteriathree = !$(
        preorderProduct.formSelectors.form_selector
      )
        .find('.sbb')
        .hasClass('btn--disabled')

      //Check if the newly selected variant is available - if it's unavailable, disable the button and show unavailable and remove all our app's widgets
      if (
        availableCriteriaOne &&
        availableCriteriaTwo &&
        availableCriteriathree
      ) {
        if (!$(preorderProduct.formSelectors.button_selector).is(':visible')) {
          preorderProduct.formSelectors.button_selector = $(
            preorderProduct.formSelectors.form_selector
          ).find(stripFormSelector(window.pn.shop.button_selector))
        }

        restoreDefaults(preorderProduct)
        buttonClicked = false
        if (!createWidget(preorderProduct)) {
          $(preorderProduct.formSelectors.button_selector).off(
            'click',
            preorderProduct.formSelectors.button_selector
          )
        }
      } else {
        $(preorderProduct.formSelectors.button_selector).text('Unavailable')
        $(preorderProduct.formSelectors.button_selector).val('Unavailable')
        $(preorderProduct.formSelectors.button_selector).off(
          'click',
          preorderProduct.formSelectors.button_selector
        )
        $(preorderProduct.formSelectors.form_selector)
          .find('#preorder-note')
          .remove()
        $(preorderProduct.formSelectors.form_selector)
          .find('.preorder-description')
          .remove()
        $(preorderProduct.formSelectors.form_selector)
          .find('.notify-partial-preorder')
          .remove()
        $(preorderProduct.formSelectors.form_selector)
          .parents('#ProductSection-product-template')
          .find('.preorder-badge')
          .remove()
      }
    })
  }

  function stripFormSelector(selector) {
    if (selector.indexOf('form') != -1) {
      var formPart = selector.substring(
        selector.indexOf('form'),
        selector.indexOf(' ')
      )
      selector = selector.replace(formPart, '')
    }
    return selector
  }

  function productPage() {
    var theProduct = ''

    $.getJSON(getRandomizedURL(), function (shopifyProduct) {
      theProduct = shopifyProduct
    }).done(function () {
      getPreorderSettings(theProduct)
    })
  }

  function getPreorderSettings(theProduct) {
    if (
      !preorderSettingsForProductInCache(theProduct.product.id) ||
      getShopifyDomain() === 'the-tinkers-packs.myshopify.com'
    ) {
      populateCache([], [theProduct.product.id], [], function () {
        prepareProductForPreorder(theProduct.product.id)
      })
    } else {
      prepareProductForPreorder(theProduct.product.id)
    }
  }

  function prepareProductForPreorder(id) {
    var preorderProduct = retrievePreorderSettingsForProductFromCache(id)
    runPreorderOnProduct(preorderProduct)
  }

  function preorderSettingsForProductInCache(productId) {
    return productId in window.pn.cache
  }

  function retrievePreorderSettingsForProductFromCache(productId) {
    return window.pn.cache[productId]
  }

  function runPreorderOnProduct(preorderProduct) {
    if (
      typeof preorderProduct !== 'undefined' &&
      Object.keys(preorderProduct).length > 0 &&
      Object.keys(preorderProduct.settings).length > 0 &&
      hasActivePreoderSettings(preorderProduct)
    ) {
      setupEnv()
      setupPreorderForm(preorderProduct)
    }

    $(window.pn.shop.button_selector).show()
  }

  function collectionPage() {
    if (collectionBadgesOrButtonsEnabled()) {
      initializeAjaxCategoryPageObserver()
      setupEnv()
      addBadgesAndButtonsToCategoryPage()
    }
  }

  function addBadgesAndButtonsToCategoryPage() {
    var productHandles = getProductHandlesFromLinks(getProductLinks())
    var variantIds = getVariantIds()

    if (productHandles.length != 0 || variantIds.length != 0) {
      populateCache(productHandles, [], variantIds, function () {
        if (Object.keys(window.pn.cache).length > 0) {
          applyBadges()
          applyButtons()
        }
      })
    }
  }

  function populateCache(handles, productIds, variantIds, callback) {
    var settings = []

    var uncachedHandles = filterHandles(handles)
    var uncachedProductIds = filterProductIds(productIds)
    var uncachedVariantIds = filterVariantIds(variantIds)
    var url = window.location.href

    if (
      uncachedHandles.length == 0 &&
      uncachedProductIds.length == 0 &&
      uncachedVariantIds.length == 0
    ) {
      callback()
    } else {
      //console.log("calling server for settings");
      $.post(
        getServerAddress() + '/widget/settings',
        {
          shopify_domain: getShopifyDomain(),
          product_handles: uncachedHandles,
          product_ids: uncachedProductIds,
          variant_ids: uncachedVariantIds,
          url: url,
        },
        function (data) {
          settings = data
        }
      ).done(function () {
        addSettingsFromServerToCache(settings)
        callback()
      })
    }
  }

  function addSettingsFromServerToCache(settings) {
    addPreorderProductsToCache(groupSettingsIntoProducts(settings))
  }

  function groupSettingsIntoProducts(settings) {
    var preorderProducts = {}
    $.each(settings, function (index, setting) {
      setting.preorder_status = checkStockShowBadge(setting)
      if (!(setting.product_id in preorderProducts)) {
        preorderProducts[setting.product_id] = {}
        preorderProducts[setting.product_id].handle = setting.handle
        preorderProducts[setting.product_id].settings = {}
        preorderProducts[setting.product_id].settings[
          setting.settings_type_id
        ] = setting
      } else {
        //Product has no setting for this variant ID
        if (
          !(
            setting.settings_type_id in
            preorderProducts[setting.product_id].settings
          )
        ) {
          preorderProducts[setting.product_id].settings[
            setting.settings_type_id
          ] = setting
        } else {
          //Setting is a single product setting which always takes priority
          if (setting.tag == null) {
            preorderProducts[setting.product_id].settings[
              setting.settings_type_id
            ] = setting
            //New setting is a tag setting and existing setting is not a single product setting
          } else if (
            setting.tag != 'all' &&
            preorderProducts[setting.product_id].settings[
              setting.settings_type_id
            ].tag != null
          ) {
            preorderProducts[setting.product_id].settings[
              setting.settings_type_id
            ] = setting
          }
        }
      }
    })
    return preorderProducts
  }

  function addPreorderProductsToCache(preorderProducts) {
    $.each(preorderProducts, function (index, preorderProduct) {
      window.pn.cache[index] = preorderProduct
    })
  }

  function filterHandles(handles) {
    var uncachedHandles = []
    $.each(handles, function (index, handle) {
      if (!handleInCache(handle)) {
        uncachedHandles.push(handle)
      }
    })
    return uncachedHandles
  }

  function filterProductIds(ids) {
    var uncachedIds = []
    if (getShopifyDomain() === 'the-tinkers-packs.myshopify.com') {
      uncachedIds = ids
    } else {
      $.each(ids, function (index, id) {
        if (!productIdInCache(id)) {
          uncachedIds.push(id)
        }
      })
    }
    return uncachedIds
  }

  function filterVariantIds(ids) {
    var uncachedIds = []
    $.each(ids, function (index, id) {
      if (!variantIdInCache(id)) {
        uncachedIds.push(id)
      }
    })
    return uncachedIds
  }

  function handleInCache(handle) {
    var handleInCache = false
    $.each(window.pn.cache, function (index, preorderProduct) {
      if (preorderProduct.handle == handle) {
        handleInCache = true
      }
    })
    return handleInCache
  }

  function productIdInCache(id) {
    var idInCache = false
    if (id in window.pn.cache) {
      idInCache = true
    }
    return idInCache
  }

  function variantIdInCache(id) {
    var idInCache = false
    $.each(window.pn.cache, function (index, preorderProduct) {
      if (id in preorderProduct.settings) {
        idInCache = true
      }
    })
    return idInCache
  }

  function applyBadges() {
    if (window.pn.shop.enable_collection_page_badge) {
      var preorderMustBeEnabledForAllVariants =
        window.pn.shop.show_collection_badge_only_if_all_variants_out_of_stock
      $.each(window.pn.cache, function (index, productSettings) {
        var productContainers = getProductContainerFromHandle(
          productSettings.handle
        )
        if (productContainers.length > 0) {
          if (
            (preorderMustBeEnabledForAllVariants &&
              preorderEnabledForAllVariants(productSettings.settings)) ||
            (!preorderMustBeEnabledForAllVariants &&
              preorderEnabledForSomeVariants(productSettings.settings))
          ) {
            var activePreorderSetting = getSingleActivePreorderSetting(
              productSettings.settings
            )
            if (activePreorderSetting) {
              $.each(productContainers, function (index, productContainer) {
                applyBadge(
                  activePreorderSetting,
                  $(productContainer),
                  'collection-badge',
                  'collection-badge-container'
                )
              })
            }
          }
        }
      })
    }
  }

  function applyButtons() {
    if (window.pn.shop.enable_collection_page_button) {
      $.each(window.pn.cache, function (index, preorderProduct) {
        setupPreorderForm(preorderProduct)
      })
    }
  }

  function getSingleActivePreorderSetting(settings) {
    var activePreorderSetting = false
    $.each(settings, function (index, setting) {
      if (checkStockShowBadge(setting)) {
        if (!activePreorderSetting) {
          activePreorderSetting = setting
        } else {
          if (setting.tag == null || setting.tag == '') {
            activePreorderSetting = setting
          } else if (activePreorderSetting.tag == 'all') {
            activePreorderSetting = setting
          }
        }
      }
    })
    return activePreorderSetting
  }

  function preorderEnabledForAllVariants(settings) {
    var enabledForAllVariants = true
    $.each(settings, function (index, setting) {
      if (!checkStockShowBadge(setting)) {
        enabledForAllVariants = false
      }
    })
    return enabledForAllVariants
  }

  function preorderEnabledForSomeVariants(settings) {
    var enabledForSomeVariants = false
    $.each(settings, function (index, setting) {
      if (checkStockShowBadge(setting)) {
        enabledForSomeVariants = true
      }
    })
    return enabledForSomeVariants
  }

  function initializeAjaxCategoryPageObserver() {
    initializeAjaxCategoryPageSettingCache()

    var trigger = false
    var observer = new MutationObserver(function (mutations) {
      // For the sake of...observation...let's output the mutation to console to see how this all works
      mutations.forEach(function (mutation) {
        //console.log(mutation);
        if (!trigger) {
          if (checkMutations(mutation, 'ajaxCollectionPage')) {
            addBadgesAndButtonsToCategoryPage()
            trigger = true
          }
        }
      })

      sleep(2000).then(function () {
        trigger = false
      })
    })

    // Notify me of everything!
    var observerConfig = {
      attributes: true,
      childList: true,
      characterData: true,
      subtree: true,
    }

    // Node, config
    // In this case we'll listen to all changes to body and child nodes
    var targetNode = document.body
    observer.observe(targetNode, observerConfig)
  }

  function collectionBadgesOrButtonsEnabled() {
    return collectionBadgesEnabled() || collectionButtonsEnabled()
  }

  function collectionBadgesEnabled() {
    return (
      typeof window.pn.shop.enable_collection_page_badge !== 'undefined' &&
      window.pn.shop.enable_collection_page_badge
    )
  }

  function collectionButtonsEnabled() {
    return (
      typeof window.pn.shop.enable_collection_page_button !== 'undefined' &&
      window.pn.shop.enable_collection_page_button
    )
  }

  function objectChecker(objectToCheck) {
    if (typeof objectToCheck !== 'undefined') {
      return true
    } else {
      return false
    }
  }

  function stringChecker(stringToCheck) {
    if (
      typeof stringToCheck !== 'undefined' &&
      stringToCheck != '' &&
      stringToCheck != null
    ) {
      return true
    } else {
      return false
    }
  }

  function getProductLinks() {
    var productLinks = []

    if (collectionBadgesEnabled()) {
      if (getShopifyDomain() == 'skinid.myshopify.com') {
        //Grab all the product handles
        productLinks = $("a[href*='/products/']:empty")
      } else if (getShopifyDomain() == 'the-brag-company.myshopify.com') {
        productLinks = $("a[href*='/products/']:not(.fancybox)").has('img')
      } else if (
        getShopifyDomain() == 'fretlight2.myshopify.com' ||
        getShopifyDomain() == 'minasan-us-outlet.myshopify.com'
      ) {
        productLinks = $(
          "a[href*='/products/'].grid-view-item__image-container"
        )
      } else {
        //Grab all the product handles
        if (
          objectChecker(window.pn.shop) &&
          stringChecker(window.pn.shop.product_link_selector)
        ) {
          productLinks = $(window.pn.shop.product_link_selector)
          if (stringChecker(window.pn.shop.product_link_selector_has)) {
            productLinks = $(productLinks).has(
              window.pn.shop.product_link_selector_has
            )
          }
        } else {
          productLinks = $("a[href*='/products/']").has('img')
        }

        if ($(productLinks).length == 0) {
          productLinks = $(window.pn.shop.product_link_selector)
        }
      }
    }

    return productLinks
  }

  function getProductHandlesFromLinks(productLinks) {
    var productHandles = []

    for (var x = 0; x < productLinks.length; x++) {
      productHandles[x] = $(productLinks[x])
        .attr('href')
        .substring(
          $(productLinks[x]).attr('href').lastIndexOf('/products/') + 10
        )
        .split('?')[0]
    }

    return productHandles
  }

  function getVariantIds() {
    var variantIds = []

    if (collectionButtonsEnabled()) {
      var variantSelectors = $(
        "form[action^='/cart/add'] select[name='id'], form[action^='/cart/add'] input[name='id']"
      )
      var counter = 0
      for (var x = 0; x < variantSelectors.length; x++) {
        if (
          $(variantSelectors[x]).val() != '' &&
          $(variantSelectors[x]).val() != null &&
          $.inArray($(variantSelectors[x]).val(), variantIds) == -1
        ) {
          variantIds[counter] = $(variantSelectors[x]).val()
          counter++
        }
      }
    }

    return variantIds
  }

  function getProductContainerFromHandle(handle) {
    var shop = window.pn.shop

    var productContainer = []

    if (getShopifyDomain() == 'arlo-and-arrows.myshopify.com') {
      productContainer = $("a[href$='products/" + handle + "']").has('img')
    } else if (
      getShopifyDomain() == 'fretlight2.myshopify.com' ||
      getShopifyDomain() == 'minasan-us-outlet.myshopify.com'
    ) {
      productContainer = $(
        "a[href$='products/" + handle + "'].grid-view-item__image-container"
      )
    } else if (getShopifyDomain() == 'skinid.myshopify.com') {
      productContainer = $("a[href$='products/" + handle + "']:empty")
    } else if (
      getShopifyDomain() == 'ecococonut-store.myshopify.com' ||
      getShopifyDomain() == 'mouldmagicssouthafrica.myshopify.com' ||
      getShopifyDomain() == 'limeprogaming.myshopify.com' ||
      getShopifyDomain() == 'lucidaletra.myshopify.com' ||
      getShopifyDomain() == 'tutu-shop.myshopify.com' ||
      getShopifyDomain() == 'prime-party.myshopify.com' ||
      getShopifyDomain() == 'snakehive-store.myshopify.com'
    ) {
      productContainer = $("a[href*='products/" + handle + "']").has('img')
    } else if (getShopifyDomain() == 'js-collectables-games.myshopify.com') {
      productContainer = $("a[href$='products/" + handle + "']")
        .has('img')
        .closest('div, li, article, figure')
        .last()
    } else if (getShopifyDomain() == 'jack-willow.myshopify.com') {
      productContainer = $(".inner > a[href$='products/" + handle + "']")
        .has('img')
        .closest('div, li, article, figure')
        .last()
    } else if (window.pn.datastore.theme_setting.theme_name === 'Dawn') {
      productContainer = $("a[href$='products/" + handle + "']")
        .closest('div.card-wrapper')
        .has('img')
    } else {
      var handleSelector =
        shop.product_container_handle_element_selector.replace(
          /{{handle}}/g,
          handle
        )

      productContainer = $(handleSelector)

      if (
        shop.product_container_handle_element_selector_has != 'null' &&
        shop.product_container_handle_element_selector_has != ''
      ) {
        productContainer = $(productContainer).has(
          shop.product_container_handle_element_selector_has
        )
      }

      if (
        shop.product_container_handle_element_selector_closest != 'null' &&
        shop.product_container_handle_element_selector_closest != ''
      ) {
        productContainer = $(productContainer).closest(
          shop.product_container_handle_element_selector_closest
        )
      }

      if ($(productContainer).length == 0) {
        if (
          shop.product_container_handle_element_selector_has != 'null' &&
          shop.product_container_handle_element_selector_has != ''
        ) {
          productContainer = $(handleSelector)
            .parent(shop.product_container_handle_element_selector_closest)
            .has(shop.product_container_handle_element_selector_has)
        }
      }
    }

    return productContainer
  }

  function quickview() {
    if (
      typeof window.pn.shop.quickview_support_enabled !== 'undefined' &&
      window.pn.shop.quickview_support_enabled
    ) {
      initializeQuickviewSettingCache()
      createQuickViewButtonListener()
    }
  }

  function initializeAjaxCategoryPageSettingCache() {
    window.pn.collectionPageSettings.filterMutationClassArray = [
      'searchit-search-results',
      'snize-search-results-content',
      'aos-init',
    ]
    window.pn.collectionPageSettings.filterMutationIdArray = [
      'bc-sf-filter-tree',
      'bc-sf-filter-products',
      'searchit_results',
    ]
  }

  function initializeQuickviewSettingCache() {
    window.pn.quickviewSettings.buttonSelectors =
      '.button--quick-shop, .sca-qv-button, .quick-view-btn, .bc-quickview-btn-wrapper, .sca-qv-cartbtn, .js-quick-shop-link, .searchit-quick-view-button, .quick-view, .js-quickbuy-button, .quick-product__btn, .product-card-interaction-quickshop, .product-modal, .productitem--action button, a.quickview, .has-quick-view .btn .v-b'
    window.pn.quickviewSettings.modalLoadedMutationClassArray = [
      'quick-shop',
      'sca-fancybox-opened',
      'mfp-ready',
      'bc-quickview-popup-active',
      'remodal-is-opened',
      'searchit-no-scroll',
      'modal--is-active',
      'quickshop-loaded',
      'fancybox-opened',
      'fancybox-is-open',
      'modal-visible',
      'quickview-raised',
      'popup',
    ]
    window.pn.quickviewSettings.modalLoadedMutationIdArray = ['colorbox']
    window.pn.quickviewSettings.formSelectors =
      ".product__form:visible, #sca-qv-add-item-form:visible, .shopify-product-form:visible, .bc-modal-wrapper:visible #bc-quickview-cart-form:visible, .product_form:visible, .searchit-quick-view-form-wrapper form:visible, .product-form:visible, .quick-buy__product-form:visible, .product-single__form:visible, form[action='/cart/add']:visible, #AddToCartForm:visible"
    window.pn.quickviewSettings.addToCartButtonSelectors =
      '.sca-qv-cartbtn:visible, #addToCart:visible, #bc-quickview-cart-btn:visible, .add_to_cart:visible, #searchit-quick-view-add-to-cart:visible, .product-form__cart-submit:visible, .quickbuy__submit:visible, .add-to-cart:visible, .product-submit:visible, .add:visible, .product-form--atc-button:visible, .addto.cart.sliding-cart:visible'
    window.pn.quickviewSettings.productImageContainerSelectors =
      '.quick-shop__slideshow:visible, .zoomWrapper:visible, .slides:visible, .bc-quickview-featured-image-wrapper:visible, .flickity-viewport:visible, .searchit-quick-view-image-wrapper:visible, .slick-slider:visible, .product-image-main:visible, .product-main-image:visible, .product-photos .bigimage:visible, .product-gallery:visible, .product-image-zoom:visible, .responsive-image:visible'
    window.pn.quickviewSettings.variantSelectors =
      '#sca-qv-variant-options select.single-option-selector, .bc-quickview-single-option-selector, .searchit-option-selector-wrapper select'
    window.pn.quickviewSettings.quickviewModalContainerSelectors =
      '.sca-fancybox-wrap:visible, .mfp-container:visible, .bc-modal-wrapper:visible, .quick-shop:visible, .searchit-modal:visible, #colorbox:visible, .modal--quick-shop:visible, .quickshop:visible, .fancybox-wrap:visible, .fancybox-container:visible, .modal-content:visible, .product-quick-view, section.quick-view'
  }

  function initializePreorderSettingCache() {
    if (typeof window.pn === 'undefined') {
      window.pn = {}
    }
    if (typeof window.pn.cP === 'undefined') {
      window.pn.cP = {}
    }
    if (typeof window.pn.settings === 'undefined') {
      window.pn.settings = {}
      window.pn.settings.defaultSetting = {}
      window.pn.settings.singleProductSettings = {}
      window.pn.settings.tagSettings = {}
    }
    if (typeof window.pn.shop === 'undefined') {
      window.pn.shop = {}
    }
    if (typeof window.pn.quickviewSettings === 'undefined') {
      window.pn.quickviewSettings = {}
    }
    if (typeof window.pn.collectionPageSettings === 'undefined') {
      window.pn.collectionPageSettings = {}
    }
    if (typeof window.pn.cache === 'undefined') {
      window.pn.cache = {}
      createSettings()
    }
  }

  function createSettings() {
    if (Object.keys(window.pn.cP).length > 0 && hasSettingsInLiquid()) {
      //For each product in cP
      $.each(window.pn.cP, function (index, product) {
        //Create product settings object
        var productSettings = {}

        var tags = product.t

        //For each variant in product
        $.each(product.v, function (index, variant) {
          var variantSetting = false

          //Get single product setting
          variantSetting = getSingleProductSettingForVariant(product, variant)

          //If no single product setting, get tag setting
          if (!variantSetting) {
            variantSetting = getTagSettingForVariant(product, tags, variant)

            //If no tag setting, get all product setting
            if (!variantSetting) {
              variantSetting = getAllProductsSettingForVariant(product, variant)
            }
          }

          //If setting was created for this variant, add to product setting object
          if (variantSetting) {
            variantSetting.preorder_status = checkStockShowBadge(variantSetting)
            productSettings[variant.id] = variantSetting
          } else {
            productSettings[variant.id] = false
          }
        })

        //Add product setting object to cache
        if (Object.keys(productSettings).length > 0) {
          window.pn.cache[product.id] = {}
          window.pn.cache[product.id].handle = product.h
          window.pn.cache[product.id].tags = product.t
          window.pn.cache[product.id].settings = productSettings
        }
      })
    }
  }

  function hasSettingsInLiquid() {
    return (
      (Object.keys(window.pn.settings.defaultSetting).length > 1 &&
        window.pn.shop.apply_default_to_all) ||
      window.pn.settings.singleProductSettings.length > 0 ||
      window.pn.settings.tagSettings.length > 0
    )
  }

  function getSingleProductSettingForVariant(product, variant) {
    var variantSetting = false
    $.each(window.pn.settings.singleProductSettings, function (index, setting) {
      setting = decodeSetting(setting)
      if (setting.settings_type_id == variant.id) {
        variantSetting = createVariantSetting(product, variant, setting)
      }
    })
    return variantSetting
  }

  function getTagSettingForVariant(product, tags, variant) {
    var variantSetting = false
    $.each(window.pn.settings.tagSettings, function (index, setting) {
      setting = decodeSetting(setting)
      $.each(tags, function (index, tag) {
        if (
          typeof tag !== 'undefined' &&
          typeof setting.tag !== 'undefined' &&
          tag.toUpperCase() == setting.tag.toUpperCase()
        ) {
          variantSetting = createVariantSetting(product, variant, setting)
        }
      })
    })
    return variantSetting
  }

  function getAllProductsSettingForVariant(product, variant) {
    var variantSetting = false
    if (
      Object.keys(window.pn.settings.defaultSetting).length > 0 &&
      typeof window.pn.shop.apply_default_to_all !== 'undefined' &&
      window.pn.shop.apply_default_to_all
    ) {
      variantSetting = createVariantSetting(
        product,
        variant,
        decodeSetting(window.pn.settings.defaultSetting)
      )
    }
    return variantSetting
  }

  function decodeSetting(oldSetting) {
    var newSetting = {}

    newSetting.preorder_button_text = oldSetting.a
    newSetting.settings_enabled = oldSetting.b
    newSetting.preorder_stock = oldSetting.c
    newSetting.out_of_stock_message = oldSetting.d
    newSetting.show_stock_remaining = oldSetting.e
    newSetting.stock_remaining_message = oldSetting.f
    newSetting.preorder_description = oldSetting.g
    newSetting.preorder_description_position = oldSetting.h
    newSetting.badge_enabled = oldSetting.i
    newSetting.badge_text = oldSetting.j
    newSetting.preorder_start_date = oldSetting.k
    newSetting.preorder_end_date = oldSetting.l
    newSetting.settings_type = oldSetting.m
    newSetting.settings_type_id = oldSetting.n
    newSetting.use_default = oldSetting.o
    newSetting.product_id = oldSetting.p
    newSetting.use_stock_management = oldSetting.q
    newSetting.use_shopify_stock_management = oldSetting.r
    newSetting.shopify_inventory = oldSetting.s
    newSetting.shopify_preorder_limit = oldSetting.t
    newSetting.shopify_stock_mgmt_method = oldSetting.u
    newSetting.oversell_enabled = oldSetting.v
    newSetting.badge_shape = oldSetting.w
    newSetting.cart_label_text = oldSetting.x
    newSetting.product_image_src = oldSetting.y
    newSetting.discount_type = oldSetting.z
    newSetting.discount_percentage = oldSetting.aa
    newSetting.discount_fixed_amount = oldSetting.ab

    newSetting.tag = oldSetting.tag
    newSetting.handle = oldSetting.handle

    return newSetting
  }

  function createVariantSetting(product, variant, setting) {
    var variantSetting = JSON.parse(JSON.stringify(setting))

    variantSetting.handle = product.h
    variantSetting.product_id = product.id

    if (typeof product.i !== 'undefined') {
      if (typeof product.i == 'string') {
        variantSetting.product_image_src = product.i
      }
    }

    variantSetting.settings_type_id = variant.id
    variantSetting.inventory_management = variant.m
    variantSetting.shopify_inventory = variant.q

    if (variant.p == 'continue') {
      variantSetting.oversell_enabled = true
    } else {
      variantSetting.oversell_enabled = false
    }

    return variantSetting
  }

  function createQuickViewButtonListener() {
    $('body').on(
      'click',
      window.pn.quickviewSettings.buttonSelectors,
      function (event) {
        var handle = getHandleFromTarget(event.currentTarget)
        if (typeof handle !== 'undefined') {
          getClickedProductIdFromHandle(handle)
        }
      }
    )
  }

  function getHandleFromTarget(target) {
    var handle = $(target).attr('handle')
    if (typeof handle === 'undefined') {
      handle = $(target).attr('href')
      if (typeof handle !== 'undefined') {
        if (handle.indexOf('#qv') > -1) {
          handle = $(target)
            .parent()
            .children('.overlay-second-link:first')
            .attr('href')
        } else if (handle.indexOf('?view=quick_view') > -1) {
          handle = handle.replace('?view=quick_view', '')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else if (handle.indexOf('?view=quickview') > -1) {
          handle = handle.replace('?view=quickview', '')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else if ($(target).hasClass('button--quick-shop')) {
          handle = $(target).parent().attr('href')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else if (handle.indexOf('?view=quick') > -1) {
          handle = handle.replace('?view=quick', '')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else if (handle === 'javascript:;') {
          handle = $(target).data('src')
          handle = handle.replace('?view=quick', '')
          handle = handle.split('/')[handle.split('/').length - 1]
        }
      } else {
        handle = $(target).attr('data-handle')
        if (typeof handle !== 'undefined') {
          handle = $(target).attr('data-handle')
        } else if ($(target).parents('.grid-product__link').length > 0) {
          handle = $(target).parents('.grid-product__link').attr('href')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else if ($(target).parents('.product-card-overlay').length > 0) {
          handle = $(target).parents('.product-card-overlay').attr('href')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else if ($(target).parents('.productgrid--item').length > 0) {
          handle = $(target)
            .parents('.productgrid--item')
            .find('.productitem--image-link')
            .attr('href')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else if ($(target).parents('.product-image').length > 0) {
          handle = $(target).parents('.product-image').attr('href')
          handle = handle.split('/')[handle.split('/').length - 1]
        } else {
          handle = $(target)
            .parents('div.bc-quickview-btn-wrapper')
            .attr('data-bc-qv-template')
          var re = /products\/([\w\-]*)\?/
          var resultArray = re.exec(handle)
          if (resultArray.length > 0) {
            handle = resultArray[1]
          }
        }
      }
    }
    return handle
  }

  function getClickedProductIdFromHandle(handle) {
    var url = getProductPageJsURL(handle)
    getProductDataFromShopify(url)
  }

  function getProductPageJsURL(handle) {
    if (handle.indexOf('/products/') < 0) {
      handle = '/products/' + handle
    }

    if (handle.indexOf('/') < 0) {
      handle = '/' + handle
    }

    var url =
      'https://' +
      window.location.hostname +
      handle +
      '?' +
      +getRandomInt(0, 10000)
    return url
  }

  function getProductDataFromShopify(url) {
    var shopifyProduct = ''
    $.getJSON(url, function (data) {
      shopifyProduct = data
    }).done(function () {
      initializeQuickviewModalObserver(shopifyProduct)
    })
  }

  function checkMutationIds(mutation, typeOfCheck) {
    var idArray = []

    if (typeOfCheck == 'quickview') {
      idArray = window.pn.quickviewSettings.modalLoadedMutationIdArray
    } else if (typeOfCheck == 'ajaxCollectionPage') {
      idArray = window.pn.collectionPageSettings.filterMutationIdArray
    } else if (typeOfCheck == 'ajaxCart') {
      idArray = window.pn.ajaxCartSettings.mutationIds
    }

    if (idArray.indexOf(mutation.target.id) !== -1) {
      return true
    } else {
      return false
    }
  }

  function checkMutationClasses(mutation, typeOfCheck) {
    var classArray = []

    if (typeOfCheck == 'quickview') {
      classArray = window.pn.quickviewSettings.modalLoadedMutationClassArray
    } else if (typeOfCheck == 'ajaxCollectionPage') {
      classArray = window.pn.collectionPageSettings.filterMutationClassArray
    } else if (typeOfCheck == 'ajaxCart') {
      classArray = window.pn.ajaxCartSettings.mutationClasses
    }

    var classFound = false

    $.each(classArray, function (index, className) {
      if (
        typeof mutation.target.classList !== 'undefined' &&
        mutation.target.classList.contains(className)
      ) {
        classFound = true
      }
    })

    return classFound
  }

  function checkMutations(mutation, typeOfCheck) {
    var mutationCheckResult =
      checkMutationIds(mutation, typeOfCheck) ||
      checkMutationClasses(mutation, typeOfCheck)
    //console.log("MUTATION RESULT: " + mutationCheckResult);
    return mutationCheckResult
  }

  function initializeQuickviewModalObserver(shopifyProduct) {
    //If modal already visible, apply pre-order settings to it
    if (
      $(
        appendVisibleToSelectors(
          window.pn.quickviewSettings.quickviewModalContainerSelectors
        )
      ).length > 0
    ) {
      sleep(1000).then(function () {
        window.pn.quickviewClicked = true
        cleanupModal()
        getPreorderSettings(shopifyProduct)
      })
      //If not, initialize an observer and wait for it to become visible
    } else {
      var trigger = false
      var observer = new MutationObserver(function (mutations) {
        // For the sake of...observation...let's output the mutation to console to see how this all works
        mutations.forEach(function (mutation) {
          //console.log(mutation);
          if (!trigger) {
            if (checkMutations(mutation, 'quickview')) {
              cleanupModal()
              trigger = true
              sleep(1000).then(function () {
                window.pn.quickviewClicked = true
                getPreorderSettings(shopifyProduct)
              })
            }
          }
        })
      })

      sleep(2000).then(function () {
        trigger = false
      })

      // Notify me of everything!
      var observerConfig = {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true,
      }

      // Node, config
      // In this case we'll listen to all changes to body and child nodes
      var targetNode = document.body
      observer.observe(targetNode, observerConfig)
    }
  }

  function appendVisibleToSelectors(selectors) {
    var selectorArray = selectors.split(',')
    var visibleSelectorArray = []
    $.each(selectorArray, function (index, selector) {
      selector = selector.trim()

      if (selector.indexOf(':visible') < 0) {
        selector = selector + ':visible'
      }

      visibleSelectorArray.push(selector)
    })
    selectors = visibleSelectorArray.join(',')
    return selectors
  }

  function cleanupModal() {
    $(window.pn.quickviewSettings.quickviewModalContainerSelectors)
      .find('.preorder-badge')
      .remove()
    $(window.pn.quickviewSettings.quickviewModalContainerSelectors)
      .find('.preorder-description')
      .remove()
    $(window.pn.quickviewSettings.quickviewModalContainerSelectors)
      .find('#preorder-note')
      .remove()
  }

  function getCartItems(_callback) {
    var cartItems = []

    $.ajax({
      cache: false,
      type: 'GET',
      url: 'https://' + window.location.hostname + '/cart.js',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      success: function (data) {
        cartItems = data['items']
        if (cartItems.length > 0) {
          _callback(cartItems)
        }
      },
    })
  }

  function mixedCartWarning() {
    if (window.pn.shop.mixed_cart_warning_enabled) {
      window.pn.ajaxCartSettings = {}
      window.pn.ajaxCartSettings.mutationIds = [
        'ajaxifyCart',
        'cart-loading',
        'AjaxifyCart',
        'layer-addcart-modal',
      ]
      window.pn.ajaxCartSettings.mutationClasses = [
        'drawer',
        'cart-drawer__item-list',
        'cart-item__qty',
        'mm-opened',
        'cart-sidebar',
        'opened',
        'cart-preview',
        'ajaxcart__inner',
        'cart--is-visible',
      ]
      initAjaxCartObserver()
      if (onCartPage()) {
        checkCartItemsAndShowWarning()
      }
    }
  }

  function initAjaxCartObserver() {
    var trigger = false
    var observer = new MutationObserver(function (mutations) {
      // For the sake of...observation...let's output the mutation to console to see how this all works
      mutations.forEach(function (mutation) {
        //console.log(mutation);

        if (!trigger && checkMutations(mutation, 'ajaxCart')) {
          setTimeout(function () {
            checkCartItemsAndShowWarning()
          }, 250)

          trigger = true
        }
      })
      trigger = false
    })

    // Notify me of everything!
    var observerConfig = {
      attributes: true,
      childList: true,
      characterData: true,
      subtree: true,
    }

    // Node, config
    // In this case we'll listen to all changes to body and child nodes
    var targetNode = document.body
    observer.observe(targetNode, observerConfig)
  }

  function checkCartItemsAndShowWarning() {
    //get list of items in cart

    getCartItems(function (cartItems) {
      var preorderItemFound = false
      var nonPreorderItemFound = false
      var preorderNoteFoundOnThisItem = false

      //for each item in cart
      $.each(cartItems, function (index, item) {
        if (
          item.properties != null &&
          Object.keys(item.properties).length > 0
        ) {
          $.each(
            Object.keys(item.properties),
            function (keyIndex, itemProperty) {
              if (
                Object.keys(item.properties)[keyIndex] ==
                window.pn.shop.pn_note_label
              ) {
                preorderItemFound = true
                preorderNoteFoundOnThisItem = true
              }
            }
          )
        }

        if (!preorderNoteFoundOnThisItem) {
          nonPreorderItemFound = true
        }
        preorderNoteFoundOnThisItem = false
      })

      if (
        preorderItemFound &&
        nonPreorderItemFound &&
        typeof window.pn.mixedCartWarningShown === 'undefined'
      ) {
        showWarning()
        window.pn.mixedCartWarningShown = true
      }
    })
  }

  function showWarning() {
    $('#pn-mixed-cart-warning').addClass('pn-manual-modal-container')
    $('#pn-mixed-cart-warning-content').addClass('pn-manual-modal-content')
    $('#pn-mixed-cart-warning').show()

    $('#pn-mixed-cart-warning-title').html(
      window.pn.shop.mixed_cart_warning_title
    )
    $('#pn-mixed-cart-warning-text').html(
      window.pn.shop.mixed_cart_warning_text
    )

    $(window).click(function (event) {
      if (event.target.classList.contains('pn-manual-modal-container')) {
        $('#pn-mixed-cart-warning').hide()
      }
    })

    $('#pn-modal-close-btn').click(function (event) {
      $('#pn-mixed-cart-warning').hide()
    })
  }

  $(document).ready(function () {
    if (typeof window.pn_running === 'undefined') {
      window.pn_running = true
      initializePreorderSettingCache()
      if (onProductPage() != -1 && onProductPage() != false) {
        productPage()
      } else if (!onCartPage()) {
        collectionPage()
        quickview()
      }
      mixedCartWarning()
    }
  })
}
try {
  var neverLoadJquery = window.pn.shop.never_load_jquery
} catch (err) {
  var neverLoadJquery = false
}
if (
  !neverLoadJquery &&
  (typeof jQuery === 'undefined' || parseFloat(jQuery.fn.jquery) < 2.2)
) {
  loadScript(
    '//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js',
    function () {
      loadScript('//code.jquery.com/ui/1.12.1/jquery-ui.min.js', function () {
        jQuery341 = jQuery.noConflict(true)
        myFrontendJavascript(jQuery341)
      })
    }
  )
} else {
  myFrontendJavascript(jQuery)
};
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//;
