$(document).ready(applyDCFixes);

function applyDCFixes() {
  //add the empty button on desktop
  $(".header-right-wrapp .header-right__item:eq(-2)").after("<li class=\"header-right__item\"><a href=\"#\" class=\"header-right__link swal-confirm\"><span class=\"btn__text\"><i class=\"fas fa-trash fa-2x\"></i></span><span class=\"header-right__link-title\">Empty</span></a></li>");
  //add the empty button on mobile
  $(".header-mobileicon a:eq(-1)").after("<a class=\"trash-button-dc swal-confirm\" href=\"#\"><div class=\"btn btn-primary header-shop-list\"><span class=\"icon\"><i class=\"svg-inline--fa fas fa-trash fa-w-12 fa-lg\"></i></span></div></a>");
  //add swal
  $("head").append("<script src='https://unpkg.com/sweetalert/dist/sweetalert.min.js'></script>");
  //hide when the screen is too small
  $("head").append("<style>@media (max-width: 399px) { .trash-button-dc { display: none; } }</style>");
  //disable hover on touch devices
   if ('ontouchstart' in window) {
    $('.trash-button-dc .btn').removeClass('btn-primary');
  }
  //link swal
  $(".swal-confirm").click(function(e) {
    e.preventDefault();
    swal({
      title: "Are you sure?",
      text: "You will remove all the items from the basket, including any vouchers applied.",
      buttons: true,
      dangerMode: true
    }).then(function(willDelete) {
      if (willDelete) {
        addLoader();
        // send post request to remove all items from the basket
        $.post("/cart/clear")
        .fail(function() {
          // show error message
          swal({
            title: "Error",
            text: "Failed to remove items from the basket.",
            dangerMode: true
          })
        })
        .done(function() {
          // reload the page
          location.reload();
        })
        .always(function() {
          // remove the loader
          removeLoader();
        });
      }
    });
  });
}

function addLoader() {
  var loader = '<div class="loader-wrapper loader-wrapper--full-page">\
    <div class="loader-container">\
      <div class="loader"></div>\
      <div class="loader-message">Removing items from your basket</div>\
    </div>\
  </div>';
  $('body').append(loader);
}

function removeLoader() {
  $('.loader-wrapper').remove();
}