$(document).ready(function(){
  function addToCartSuccess() {
    $.get( "/cart?view=mini", function( data ) {
      $('#crt').html(data);
      $('#crt').removeClass('loading');
    });
  }
  function refreshCart(cart) {
    $('.cart-count').text(cart.item_count);
  }

  $('body').on('click','.buttonAddtoCart',function(e){
    e.preventDefault();
    var btn = $(this);
    var form = $(this).closest('form');
    btn.attr('disabled', 'disabled');
    btn.text('adicionando...');
    form.find('.error').remove();

    $.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: form.serialize(),
      dataType: 'json',
      error: function(jqXHR, textStatus, errorThrown){
        var response = $.parseJSON(jqXHR.responseText);
        form.append('<p class="error">'+response.description+'</p>').find('.error').fadeIn().delay(4000).fadeOut();
        btn.text('adicionar ao carrinho');
        btn.removeAttr('disabled');
      }
    }).done(function( data ) {
      addToCartSuccess();
      btn.text('adicionar ao carrinho');
      btn.removeAttr('disabled');
      $.getJSON('/cart.js', function(cart){
        refreshCart(cart);
      });
      $('.productGrid .productItem').removeClass('qvopen');
      $('body').addClass('cartOpen');
      $('.fullPage').addClass('witmenu');
    });

  });

  $('body').on('click','.buttonBuyNow',function(e){
    e.preventDefault();
    var btn = $(this);
    var form = $(this).closest('form');
    btn.attr('disabled', 'disabled');
    btn.text('carregando...');
    form.find('.error').remove();

    $.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: form.serialize(),
      dataType: 'json',
      error: function(jqXHR, textStatus, errorThrown){
        var response = $.parseJSON(jqXHR.responseText);
        form.append('<p class="error">'+response.description+'</p>').find('.error').fadeIn().delay(4000).fadeOut();
        btn.text('COMPRAR AGORA');
        btn.removeAttr('disabled');
      }
    }).done(function() {
      // redirect to cart
      window.location.href = `/cart`;
    });

  });

  $('body').on('click','.fullPage.witmenu, .closemenu, .closecart', function(e){
    e.preventDefault();
    $('body').removeClass('menuOpen');
    $('.fullPage').removeClass('witmenu');
    $('body').removeClass('cartOpen');
  });
  $('.cart_button').on('click',function(e){
    e.preventDefault();
    setTimeout(function(){
      $('body').addClass('cartOpen');
      $('.fullPage').addClass('witmenu');
    }, 50);
  });
  $('body').on('click', '.adjust',function(){
    var input = $(this).parent().find('input');
    var ip = parseInt(input.val());
    if($(this).hasClass('plus')) {
      ip = ip + 1;
    } else {
      ip = ip - 1;
    }
    if(ip==0) {
      return false;
    }
    input.val(ip);

    $('#crt').addClass('loading');
    var id = parseInt(input.attr('data-id'));
    $.ajax({
      type: 'POST',
      url: '/cart/update.js',
      data: 'updates['+id+']='+ip,
      dataType: 'json',
      error: function(jqXHR, textStatus, errorThrown){
        var response = $.parseJSON(jqXHR.responseText);
        alert(response.description);
        $('#crt').removeClass('loading');
      }
    }).done(function( data ) {
      addToCartSuccess();
      $.getJSON("/cart.js", function(cart) {
        refreshCart(cart);
      });
      $('#crt').removeClass('loading');
    });

  });
  $("#crt").on('click', "a.remove_item", function(r){
    $('#crt').addClass('loading');
    r.preventDefault();
    var id = $(this).data("id");
    Shopify.changeItem(id,0, function(c){
      $('.itemCount').text(c.item_count);
      if(!c.item_count) {
        $('#crt').empty();
        $('#crt').append('<p class="emptyCart text-center">Você não tem itens no seu carrinho de compras.</p>');
        $('#crt').removeClass('has-item');
        $('#crt').removeClass('loading');
		$.getJSON("/cart.js", function(cart) {
          refreshCart(cart);
        });
      } else {
        addToCartSuccess();
      }
    });
    $.getJSON("/cart.js", function(cart) {
      refreshCart(cart);
    });
  });
});
