var Wick = Wick || {};
Wick.YourDetails = (function(){
  var $self = $('.checkout-your-details');
  let closeBlock = $('.close-block'),
      $firstLineAddrRow = closeBlock.find("#first-line-address").parents(".form-row"),
      $firstLineAddrLable = closeBlock.find("#first-line-address").closest(".form-row__label"),
      $firstLineAddrField = closeBlock.find("#first-line-address").parents(".form-row__field"),
      formError = ".form-row__error",
      listElement = $('.close-block').find('li'),
      firstLineAddress = $('.close-block #first-line-address');

  var bindEvents = function () {
    $(document).on('click', '.btn-edit-manually', function(){
      $('[data-finder]').toggle();
      $('[data-manually]').toggle();
      return false;
    });
  };

  //start -> fix for ONLINE-2615
  firstLineAddress.bind("change paste keyup", function() {
    if ($(this).val() == '') {
      $('.close-block [data-manually]').removeClass('d-block');
      $('.close-block [data-manually]').addClass('d-none');
    }
  });

  listElement.on('click', function() {
    $('.close-block [data-manually]').removeClass('d-none');
    $('.close-block [data-manually]').addClass('d-block');
  });
  //end -> fix for ONLINE-2615

  //start -> fix for ONLINE-2616
  $('.btn-enter-details').on('click', function() {
    if(!($("#chb-payment-details-card").is(":checked"))) {
      $firstLineAddrRow.addClass("form-row_validation-error")
      $firstLineAddrLable.addClass("form-row__label_required")
    }
    else {
      $firstLineAddrRow.removeClass("form-row_validation-error")
      $firstLineAddrRow.removeAttr("data-row-required")
      $firstLineAddrField.siblings(".form-row__label").removeClass("form-row__label_required")
    }

    if (firstLineAddress.val() !== '') {
      $('.close-block [data-manually]').removeClass('d-none');
      $('.close-block [data-manually]').addClass('d-block');
      $firstLineAddrRow.removeClass("form-row_validation-error")
      $firstLineAddrRow.removeAttr("data-row-required")
    }
  })

  $('#chb-payment-details-card').on('click', function() {
    if($("#chb-payment-details-card").is(":checked")) {
      $firstLineAddrRow.removeClass("form-row_validation-error")
      $firstLineAddrField.siblings(".form-row__label").removeClass("form-row__label_required")
      $firstLineAddrLable.removeClass("form-row__label_required")
      closeBlock.find(formError).hide()
    }

    else {
      $firstLineAddrField.siblings(".form-row__label").addClass("form-row__label_required")
      $firstLineAddrLable.addClass("form-row__label_required")
    }
  })
  //end -> fix for ONLINE-2616

  var init = function () {
    if (!$self.length){
      return;
    }

    bindEvents();
  };

  init();
})();
