var Wick = Wick || {};
(function () {
  var $page = $('.page_basket');

  function bindEvents () {
    var note;

    $page.find('.btn-checkout').on('click', function (e) {
      e.preventDefault();

      var deliveryError = false;

      $('.order-line__delivery-rbn input[type=radio]:checked').each(function(index, radio){
        var $line = $(radio).parents('.order-line');
        if (radio.value === 'collect'){
          if (!$line.data('store-selected')){
            $line.addClass('order-line_delivery-error');
            deliveryError = true;
          }
        } else {
          $line.removeClass('order-line_delivery-error');
          note && note.hide();
        }
      });

      if (deliveryError){
        note = Wick.Notification.show({
          text: 'Please select stores for the entries highlighted in red',
          container: '.notification-area',
          type: 'error'
        });
      } else {
        if (Wick.User.isLoggedIn()){
          window.location.href = './page_checkout_delivery-address.html';
        } else {
          window.location.href = './page_checkout_sign-in.html';
        }
      }

      return false;
    });

    $('.order-line__delivery-action').on('click', function(){
      $line = $(this).parents('.order-line');
      $line.data('store-selected', !$line.data('store-selected'));
      $line.removeClass('order-line_delivery-error');
      note && note.hide();
    });

    $('.order-line__delivery-rbn input[type=radio]')
    .each(function(index, radio){
      radio.checked && radio.value === 'collect' && $(radio).parents('.order-line').data('store-selected', true);
    });
  }

  if (!$page.length){
    return;
  }

  bindEvents();
})();
