Soben
10/28/2015 - 4:00 PM

stillpoint-cart-dropdown.coffee

class MiniCartHandler

  constructor : (@jQuery, @popupElement, @navElement) ->
    @cartCount = @popupElement.data('itemcount')

    @cartLimit = @popupElement.data('itemlimit')
    @cartLimit ?= 5
    
    @cartDisplay = @popupElement.find('.cart-items')
    @navElement.on 'click', @popupOnClick
    @checkForAndUpdateExtraProductsWarning()

  popupOnClick : (e) =>
    e.preventDefault()
    @popupToggle()

  addProduct : (item) ->
    @cartHide()

    @clearNewProducts()
    @clearEmptyNotice()

    @cartDisplay.prepend(@buildCartItemHTML(item))
    @incrementCartCount()
    
    @cartShow()

  getExtraItemsDOM : (remaining) ->
    domObject = @cartDisplay.find('.notice-cart-extra')
    if domObject.length <= 0
      @cartDisplay.append(@buildExtraItemsHTML(remaining))
      domObject = @cartDisplay.find('.notice-cart-extra')

    return domObject

  buildCartItemHTML : (item) ->
    # name : 'example product'
    # image : 'http://'
    # href : 'http://'
    # option : 'product option'
    # quantity : 1

    $ """
    <article class="cart-item new-item">
      <img src="#{item.image}" alt="#{item.name}" />
      <div>
        <p class="title">#{item.quantity}x <a href="#{item.href}">#{item.name}</a></p>
        <p class="option-details">#{item.option}</p>
      </div>
    </article>
    """

  buildExtraItemsHTML : (remaining) ->
    $ """
    <div class="notice-cart-extra">
      plus <span class="cart-count"></span> more items(s)
    </div>
    """

  clearNewProducts : () ->
    @cartDisplay.find('article').removeClass('new-item')
    @cartDisplay.find('article .option-details').remove()

  clearEmptyNotice : () ->
    @cartDisplay.find('.notice-empty').removeClass('new-item')

  popupToggle : () ->
    if ( @popupElement.hasClass('hidden') )
      @cartShow()
    else 
      @cartHide()

  cartShow : () ->
    @popupElement.removeClass('hidden')
  cartHide : () ->
    @popupElement.addClass('hidden')

  incrementCartCount : () ->
    @cartCount++
    @popupElement.data('itemcount', @cartCount)
    @navElement.find('.cart-count').html(@cartCount)
    @checkForAndUpdateExtraProductsWarning()

  checkForAndUpdateExtraProductsWarning : () ->
    if @cartCount > @cartLimit
      remaining = @cartCount - @cartLimit

      moreItemsDom = @getExtraItemsDOM(remaining)
      moreItemsDom.find('.cart-count').html(remaining);

jQuery ($) ->
  window.mini_cart =
    new MiniCartHandler($, $('#mini-cart'), $('.cart-toggle'))