var Wick = Wick || {};
Wick.Forms = (function(){
  var fieldRow = '.form-row[data-row-required]',
    field = '.form-row__field',
    fieldError = '.form-row__error',
    formInvalid = 'form_invalid',
    rowValidationError = 'form-row_validation-error',
    // validationError = '<div class="form-row__error">Error message here</div>',
    $forgotPassword = $('.link-forgot-password'),
    scenarios = [{
        condition: function(){
          // fill in the valid returning customer's details
          // Email: responsive@test.com; Password: 123456
          return $('#login-email').val() === 'responsive@test.com' && $('#password').val() === '123456';
        },
        action: function(){
          // redirected to the homepage
          Wick.User.login();
          window.location.href = './';
        }
      },
      {
        condition: function(){
          // continue as a new user with "test+random@user.com"
          return $('#registration-email').val().length;
          // return $('#registration-email').val() === 'test+random@user.com';
        },
        action: function(){
          // redirected to the register form
          window.location.href = './page_registration.html';
        }
      },
      {
        condition: function(){
          // When I click forgotten password link
        },
        action: function(){
          // redirected on the "Forgotten Password" page
          window.location.href = './page_forgotten-password.html';
        }
      }
    ];

  validationError = function (errorMsg) {
    return `<div class="form-row__error"> ${errorMsg || 'Error message here'}</div>`
  }
  function isElementInViewport (el) {
    if (typeof jQuery === 'function' && el instanceof jQuery) {
      el = el[0];
    }
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

  var showValidationErrors = function (form, errorMsg) {
    var $form = $(form);
    if (!$form.hasClass(formInvalid)) {
      $form.find('.form-row__error').remove();
      $form.addClass(formInvalid).find(fieldRow).append(validationError(errorMsg)).addClass(rowValidationError);
    }

    var $firstMsg = $form.find(fieldRow).first();
    if($firstMsg.length && !isElementInViewport($firstMsg)){
      var inModal = $firstMsg.closest('.modal').length,
        $scrollableEl = inModal ? $firstMsg.closest('.modal') : $('html, body'),
        y = inModal ? 0 : $firstMsg.offset().top - 30;

      $scrollableEl.animate({ scrollTop: y }, 300);
    }
  };

  var clearValidationErrors = function (form) {
    var $form = $(form);
    if ($form.hasClass(formInvalid)) {
      $form.removeClass(formInvalid)
        .find(fieldRow).removeClass(rowValidationError)
        .find(fieldError).remove();
    }
  };

  var handleSmoothScroll = function () {
    $('html, body').animate({
      scrollTop: $('.cards-store-list').offset().top - 60
    }, 300);
  };

  var handleFormSubmit = function () {
    var form = this;

    if ($(form).is('#form-login') || $(form).is('#form-register')) {
      for (var i = 0; i < scenarios.length; i++) {
        var scenario = scenarios[i];
        if (scenario.condition()) {
          scenario.action(this);
          return false;
        }
      }
    }

    if ($(form).is('#form-forgotten-password')) {
      if ($(form).find('#email').val().length){
        window.location.href = './page_upd-pass.html';
        return false;
      }
    }

    if ($(form).is('#form-forgotten-password-popup')) {
      if ($(form).find('#email').val().length){
        window.location.href = './page_checkout_sign-in.html';
        return false;
      }
    }

    if ($(form).is('#checkout-form-forgotten-password-popup')) {
      if ($(form).find('#email').val().length){
        $('.modal-reset-wrap').addClass('d-block');
        $('.request-pass').addClass('d-none');
        $('.modal-title').text('Password Reset');
        return false;
      }
    }

    if ($(form).is('.update-pass')) {
      if ($(form).find('#new-password').val().length && $(form).find('#confirmed-password').val().length){
        window.location.href = './page_login.html';
        return false;
      }
    }

    if ($(form).is('.change-email')) {
      if ($(form).find('#new-email').val().length &&
        $(form).find('#confirm-new-email').val().length &&
        $(form).find('#password').val().length){
        window.location.href = './page_my-account.html';
        return false;
      }
    }

    if ($(form).is('.form-change-password')) {
      if ($(form).find('#current-password').val().length &&
        $(form).find('#new-password').val().length &&
        $(form).find('#confirm-password').val().length){
        window.location.href = './page_my-account.html';
        return false;
      }
    }

    if ($(form).is('.form-register')) {
      if ($(form).find('#first-name').val().length &&
        $(form).find('#last-name').val().length &&
        $(form).find('#postcode').val().length &&
        $(form).find('#email').val().length &&
        $(form).find('#password').val().length &&
        $(form).find('#confirm-password').val().length){
        window.location.href = './page_my-account.html';
        return false;
      }
    }

    if ($(form).is('.form-personal-details')) {
      if ($(form).find('#first-name').val().length && $(form).find('#surname').val().length){
        window.location.href = './page_my-account.html';
        return false;
      }
    }

    if ($(form).is('.form-address-details')) {
      if ($(form).find('#first-name').val().length &&
          $(form).find('#second-name').val().length &&
          $(form).find('#address1').val().length &&
          $(form).find('#town-city').val().length &&
          $(form).find('#mobile-telephone').val().length) {
        window.location.href = './page_my-account_address-book.html';
        return false;
      }
    }

    if ($(form).is('.form-locator')) {
      if ($(form).find('#store-id').val()){
        window.location.href = './page_store-locator-details.html';
        return false;
      }
    }

    if ($(form).is('.form-locator-list')) {
      if ($(form).find('#postcode-town').val().length){
        var actionAfterSubmit = $(form).attr('data-action');
        if (actionAfterSubmit === 'scroll-to-list'){
          clearValidationErrors(this);
          handleSmoothScroll();
        } else {
          window.location.href = actionAfterSubmit;
        }
        return false;
      }
    }

    if ($(form).is('#form-mini-basket')) {
      if (Wick.User.isLoggedIn()){
        window.location.href = './page_checkout_delivery-address.html';
      } else {
        window.location.href = './page_checkout_sign-in.html';
      }
      return false;
    }

    function isNotEmpty(field){
      return !!$(field).val();
    }

    if ($(form).is('#form-checkout-your-details')) {
      var requiredFields = $(form).find('[data-row-required]:visible :input');
      if (_.every(requiredFields, isNotEmpty)){
        window.location.href = $(form).attr('data-action');
        return false;
      }
    }

    if ($(form).is('#checkout-your-details-modal')) {
      var requiredFields = $(form).find('[data-row-required]:visible :input');
      if (_.every(requiredFields, isNotEmpty)){
        $('#modalDeliveryEdit').modal('hide');
        return false;
      }
    }

    if ($(form).is('#edit-delivery-address')) {
      var requiredFields = $(form).find('[data-row-required]:visible :input');
      if (_.every(requiredFields, isNotEmpty)) {
        $('#modalDeliveryGuest').modal('hide');
        return false;
      }
    }

    if ($(form).is('.checkout-register')){
      if ($(form).find('#password').val().length &&
          $(form).find('#confirm-password').val().length) {
        window.location.href = './page_my-account.html';
        return false;
      }
    }

    if ($(form).is('#form-checkout-voucher')){
      if ($(form).find('#voucher-code').val().length) {
        return false;
      }
    }

    if ($(form).is('.add-list-id__form')) {
      if ($(form).find('#project-id').val().length) {
        return false;
      }
    }

    if ($(form).is('.header-search')){
      window.location.href = './page_search-results.html';
    }

    if ($(form).is('.click-and-collect__locator-form')){
      var $form = $(form);
      if ($form.find('#click-and-collect-town').val().length) {
        clearValidationErrors(this);
      } else if (!$form.hasClass(formInvalid)) {
        // Validation for inline form
        $form.addClass(formInvalid)
          .find(fieldRow).addClass(rowValidationError)
          .find(field).append(validationError);
      }
      return false;
    }

    if($(form).is('.form-track-order')) {
        var $form = $(form);

        if ($form.find('#order').val().length &&
            $form.find('#tel').val().length &&
            $form.find('#email').val().length &&
            $form.find('#postcode').val().length) {
            clearValidationErrors(this);
        } else if (!$form.hasClass(formInvalid)) {
          $form.addClass(formInvalid);

          $(fieldRow).each(function() {
            $(this).addClass(rowValidationError)
              .append('<div class="form-row__error">' + $(this).data('message') + '</div>');
          });
        }

        return false;
    }

    if ($(form).is('#edit-billing-address')) {
      var requiredFields = $(form).find('[data-row-required]:visible :input');
      if (_.every(requiredFields, isNotEmpty)) {
        $('#modalEditBilling').modal('hide');
        return false;
      }
    }

    showValidationErrors(this);
    return false;
  };

  var scrollLocatorListPage = function() {
      var isLocatorListPage = $('.cards-store-list').length;
      var isScrollNeeded = window.location.hash === "#stores-list";
      if (isLocatorListPage && isScrollNeeded) {
          handleSmoothScroll();
      }
  };

  var bindEvents = function () {
    $(document).on('submit', 'form:not([class^="header"])', handleFormSubmit);
    $forgotPassword.on('click', scenarios[2].action);
    $('.btn-cancel').on('click', function(){
      window.location.href = './page_my-account.html';
    });
    $('.btn-previous').on('click', function(){
      window.location.href = './page_login.html';
    });
  };

  var init = function () {
    bindEvents();
    scrollLocatorListPage();
  };

  init();

  return {
    showValidationErrors: showValidationErrors,
    clearValidationErrors: clearValidationErrors
  }
})();
