(function($){
  var currentDate = new Date();
  var day = currentDate.getDate();
  var month = currentDate.getMonth() + 1;
  var year = currentDate.getFullYear();

  jQuery.datetimepicker.setLocale('pl');

  var defaultTime = currentDate.getHours() + ':' + parseInt(currentDate.getMinutes() / 30) * 30;

	$('input[data-datetime]').datetimepicker({
    minDate: year + '/' + month + '/' + day,
    step: 30,
    defaultTime: defaultTime,
    dayOfWeekStart: 1
  });

  function goToNextStep(form) {
    var step1 = $('[data-form_first_step]', form);
    var step2 = $('[data-form_second_step]', form);
    step1.css({ display: 'none' });
    step2.css({ display: 'block' });
    form.data('step', '1');
  }

  function resetForm(form) {
    $('input,select', form).val('');
    var step1 = $('[data-form_first_step]', form);
    var step2 = $('[data-form_second_step]', form);
    step1.css({ display: 'block' });
    step2.css({ display: 'none' });
    form.data('step', '0');
  }

  function submitForm(form) {
    $.ajax({
        url: 'add-order.php',
        data: form.serialize(),
        processData: false,
        type: 'POST',
        success: function (data) {
          resetForm(form);
          $('.result-success', form).html('Pomyślnie wysłano zlecenie.');
          $('.result-error', form).html('');
        },
        error: function (xhr, status, error) {
          $('.result-error', form).html('Nie udało się wysłać zlecenia.');
          $('.result-success', form).html('');
        }
    });
  }

  function getStep(form) {
    return parseInt(form.data('step'));
  }

  function getValues(form) {
    var values = {};
    $('input,select', form).each(function () {
      values[$(this).attr('name')] = $(this).val();
    });
    return values;
  }

  function validateFirstStep(form, errors) {
    var values = getValues(form);
    var isValid = true;
    if (!values['start_time']) {
      errors['start_time'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['end_time']) {
      errors['end_time'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['start_place']) {
      errors['start_place'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['end_place']) {
      errors['end_place'] = 'To pole jest wymagane.';
      isValid = false;
    }
    return isValid;
  }

  function validateForm(form, errors) {
    var values = getValues(form);
    var isValid = validateFirstStep(form, errors);
    if (!values['service_type']) {
      errors['service_type'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['first_name']) {
      errors['first_name'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['last_name']) {
      errors['last_name'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['city']) {
      errors['city'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['postal_code']) {
      errors['postal_code'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['street']) {
      errors['street'] = 'To pole jest wymagane.';
      isValid = false;
    }
    if (!values['phone']) {
      errors['phone'] = 'To pole jest wymagane.';
      isValid = false;
    }
    return isValid;
  }

  function addError(form, name, value) {
    var element = $('[name=' + name + ']', form).parent();
    var errorEl = $('.error', element);
    if (errorEl.length === 0) {
      element.append('<div class="error"></div>');
      errorEl = $('.error', element);
    }
    errorEl.html(value || '');
  }

  function addErrors(form, errors) {
    var keys = Object.keys(errors);
    $('.error', form).html('');
    for (var i = 0; i < keys.length; i++) {
      addError(form, keys[i], errors[keys[i]] || '');
    }
  }

  var formPart = $('[data-form_first_step]');
  $('[data-form_step_button]', formPart).click(function (e) {
    var form = $(this).parent('[data-form_first_step]').parent();
    var errors = {};
    if (validateFirstStep(form, errors)) {
      goToNextStep(form);
    }
    addErrors(form, errors);
  });

  var forms = $('[data-add_order_form]');
  forms.submit(function (e) {
    var form = $(this);
    var errors = {};
    if (getStep(form) == 0) {
      if (validateFirstStep(form, errors)) {
        goToNextStep(form);
      }
      addErrors(form, errors);
    } else {
      if (validateForm(form, errors)) {
        submitForm(form);
      }
      addErrors(form, errors);
    }

    return false;
  });

  $('input,select', forms).change(function (e) {
    var input = $(this);
    var form = input.closest('form');
    var errors = {};
    validateForm(form, errors);
    addError(form, input.attr('name'), errors[input.attr('name')]);
  });

})(jQuery);
