var Wick = Wick || {};

Wick.CheckoutSignInEmulation = (function () {
  var checkoutEmail = $('#checkout-email');

  function validateEmail (argElementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(argElementValue);
  }

  function clearFormValidation (form) {
    if ($(form).hasClass('form_invalid')) {
      $(form).removeClass('form_invalid')
        .find('.form-row[data-row-required]').removeClass('form-row_validation-error')
        .find('.form-row__error').remove();
    }
  }

  function bindEvents () {
    $('#checkout-sign-in-submit').click(function () {
      var isGuestFlow = $('[name=sign-in-password]:checked').val() === 'guest';
      if (validateEmail(checkoutEmail.val())) {
        event.preventDefault();
        if (isGuestFlow){
          window.location.href = './page_checkout_delivery-address_guest.html';
          return false;
        } else if ($('#password').val().length) {
          window.location.href = './page_checkout_delivery-address.html';
          return false;
        }
      }
      Wick.Forms.showValidationErrors($(this).closest('form')[0]);
    });

    $('#modal-request-pass').on('hide.bs.modal', function () {
        var form = $(this).find('form');
        form[0].reset();
        clearFormValidation(form);
    });
  }

  bindEvents();
})();
